One element vector cannot be used to multiply another vector/matrix

rand(1,3)*rand(3)
is possible, and returns a 1-element vector
but rand(1,3)*rand(3)*(another matrix) is usually not possible,
rand(1,3)*rand(3)*rand(3) gives error:
MethodError: no method matching *(::Vector{Float64}, ::Vector{Float64})

I understand Julia is a strongly typed language (hope it means what I want to say). So bascially i understand why it’s not possible in Julia. But this is funny when encountered

1 Like

Julia follows * matrix-multiplication rules, i.e. the matrices/vectors/tensors need to have correct shapes for that to work. Alternatively, you can use the .* to do element-wise multiplication (with potential broadcasting); again the operands need to have sizes which fit under element-wise rules. Have a look at the manual, that should be fairly complete on the subject. Your example “works” with element-wise multiplcation

julia> rand(1,3).*rand(3).*rand(3)
3×3 Matrix{Float64}:
 0.0771117  0.044531   0.199846
 0.0370739  0.0214097  0.0960824
 0.141504   0.0817167  0.366728
2 Likes

I understand your point. But what i want is actually something like
(rand(1,3)*rand(3)) .*rand(4)

that works :slight_smile:

1 Like

I agree it’s a noteworthy observation! It can be surprising coming from Matlab: Matlab also follows matrix multiplication rules and operands must have the right shape so [1; 2; 3] * [1; 2; 3] doesn’t work. However the following does work in Matlab:

a = rand(3, 1);
b = rand(3, 1);
c = rand(3, 1);

a' * b * c

Matlab doesn’t distinguish between scalars and 1x1 matrices, so the above can be interpreted as a scalar a'*b multiplying c. But as you say it doesn’t work in Julia because a'*b is not a scalar, it’s a 1-element matrix.

Another way to put it: in Matlab you can implement dot(a, b) as a' * b. In Julia this is not a correct implementation of the dot product (Edit: in the sense that it fails if a or b is a nx1 matrix rather than a vector).

Note that you can also write this calculation as c * a' * b. This works both in Julia and Matlab, but I fear it will do the inefficient (c * a') * b rather than the efficient c * (a' * b).

2 Likes

Not sure if that is clear, but if all where actually vectors all that works, i. e:

julia> rand(3)' * rand(3) # is a dot product, returns a scalar
0.3042989054310262

all the confusion boils down to the difference between matrix with one column and a vector, difference that does not exist in Matlab.

That is, in Julia rand(3,1) is not the same as rand(3), and unless you get that 1-column matrix from another source, that is not the Julian way to define vectors. You can also convert that one-column matrix to a vector, using vec(rand(3,1)).

5 Likes

I think this hits the true reason.