Search code examples
arraysjuliabroadcastingelementwise-operations

Julia - Multiplication of values in an array


If I have an array A with random values, I would like define an array B with, for each i in length A, B[i] = (A[i])²

First, I tried the following code:

using Distributions

A = rand(Uniform(1,10),1,20)

B = A

for i in 1:20
       B[i] = (A[i])^2
end

After these operations, I have A = B

A
1×20 Array{Float64,2}:
 26.0478  5.36654  99.675  23.18  …  1.54846  91.3444  9.41496  2.91666

B
1×20 Array{Float64,2}:
 26.0478  5.36654  99.675  23.18  …  1.54846  91.3444  9.41496  2.91666

So I tried an other method:

B = A^2

There is the following error:

ERROR: DimensionMismatch("A has dimensions (1,20) but B has dimensions (1,20)")

If I do, for instance, B = 2*A it works fine...

Some ideas to help ?

Thank you


Solution

  • I think the easiest solution here is to use broadcasting via ..

    julia> A = rand(Uniform(1,10),1,20)
    1×20 Array{Float64,2}:
     8.84251  1.90331  8.5116  2.50216  …  1.67195  9.68628  4.05879  1.50231
    
    julia> B = A .^ 2
    1×20 Array{Float64,2}:
     78.19  3.62257  72.4473  6.26081  …  2.7954  93.8241  16.4738  2.25693
    

    This gives you what you expect:

    julia> A
    1×20 Array{Float64,2}:
     8.84251  1.90331  8.5116  2.50216  …  1.67195  9.68628  4.05879  1.50231
    
    julia> B
    1×20 Array{Float64,2}:
     78.19  3.62257  72.4473  6.26081  …  2.7954  93.8241  16.4738  2.25693
    

    This . operator works with any function and what it does it broadcasts (applies) all the function to each and every element of the array/object.

    Here's an example with a custom function:

    julia> my_func(a) = a * 5
    my_func (generic function with 1 method)
    
    julia> my_func.(1:5)
    5-element Array{Int64,1}:
      5
     10
     15
     20
     25
    

    Have a look at the docs for more info.