Question about Dot Notation and "$"


I=10;J=5;
P=zeros(I,J);

#Related to Q1
P.= @. 1e-2*ones(I,J)*1; #Option 1.1, Don't work
P.=  1e-2.*ones(I,J).*1; #Option1.2, works

#Related to Q2
P.= @. 1e-2*ones(I,J)*1; #Option 2.1, Don't work
P.= @. 1e-2*$ones(I,J)*1; #Option2.2, works

Q-1 What is the exact difference between options 1.1 and 1.2 ? Why does one work and other don’t ?

Q-2 What does “$” exactly do so that option 2.2 gives the relevant output?

2 Likes

@. adds a dot to every function call in the expression. In the case of 1.1, that includes the function ones, which isn’t what you want. We can write out what the @. is producing by hand like this:

P .= 1e-2 .* ones.(I, J) .* 1  # doesn't work

This fails because it’s trying to assign the entire output of ones (a I x J matrix) to each element of P. Or, other words, it’s trying to do:

for i in eachindex(P)
  P[i] = 1e-2 * ones(I, J) * 1
end

which doesn’t work.

The $ syntax within @. means “don’t add a dot to this particular function call”, so:

@. 1e-2 * $ones(I, J) * 1

is equivalent to:

1e-2 .* ones(I, J) .* 1

i.e. the same as Option 1.2.

5 Likes