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

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