3

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

niczky12
  • 4,953
  • 1
  • 24
  • 34
Julien
  • 763
  • 8
  • 32
  • 2
    You have a major misconception here: `B = A` does not make a copy — both `B` and `A` will be two names for the same data. You want `B = copy(A)` to make a copy. – mbauman Apr 18 '18 at 16:35
  • 1
    The reason `A^2` doesn't work, is that it is the same as `A*A`, and you cannot multiply two vectors together. Instead you must specify that you want element-by-element operation, which is what `.*` will do. – DNF Apr 18 '18 at 18:41

1 Answers1

5

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.

niczky12
  • 4,953
  • 1
  • 24
  • 34