Vectorization and Minor Random Number Issues

Consider the following code:

srand(1234);
x = zeros(2);
y = zeros(2);
A = 3.5;
y.=x.+ A * randn.()
srand(1234);
x = zeros(2);
y = zeros(2);
B = 3.5;
y.=x.+ A .* randn.()

The first piece produces

2-element Array{Float64,1}:
 3.03572
 3.03572

while the second produces:

2-element Array{Float64,1}:
  3.03572
 -3.1561 

It is this latter version that I exepcted. While I can appreciate why this is happening, it’s quite easy to forget a ., which could result in some very bad behavior with stochastic problems.

Use @.

Or randn(2) is probably nicer
Also isn’t it breaking the bimdas rules? ie randn.() has to jump a .* and a .+ to know it needs 2 elements?

transpose is a bit interesting too

[0; 0] .+2 .* randn.()' .+ [0 0]; __ ~= randn(1)
[0; 0] .+2 .* randn.() .+ [0 0]; ___ ~= randn(2, 2)

zeros() and zeros.() don’t seem to behave very well either (0 dim arrays with a value in?)

[5 5 5] .+ zeros.(); → Array{Array{Float64, 0}, 2} [5.0 5.0 5.0]
[5 5 5] .+ zeros.(0) → Array{Array{Float64, 1}, 2} [Float64 Float64 Float64]
[5 5 5] .+ zeros.(1) → Array{Array{Float64, 1}, 2} [[5.0] [5.0] [5.0]]

Is there a full discussion somewhere of @. and related approaches to vectorization?

2 Likes