Strange matrix multiplication behavior in Matlab

85 Views Asked by At

I noticed strange behavior of some calculations in Matlab.

Matlab code listing:

% w_x, w_y, w_z are scalars
Q_0 = [0.788604; 0.41303067; 0.41303067; 0.192129]        % 4d vector
A = [ 0 -w_x -w_y -w_z; w_x 0 w_z -w_y; w_y -w_z 0 w_x; w_z w_y -w_x 0 ]       % 4x4 matrix
w = sqrt(w_x^2 + w_y^2 + w_z^2)        % scalar

Q_w1 = (cos(w*t/2.) + sin(w*t/2.) * 1./w * A ) * Q_0             % 4d vector
Q_w2 = (cos(w*t/2.) * Q_0+ (sin(w*t/2.) * 1./w * A)* Q_0 )       % 4d vector

I've got diffenet values of Q_w1 and Q_w2. Do theese sentenses equal in terms of math? For me, it seems like they do. Is it just a Matlab bug?

1

There are 1 best solutions below

0
On BEST ANSWER

When you have $+$ in the two lines, it's not doing the same thing in both places. Under the current definition, cos(w*t/2.) is a number, and the $+$ operator in the code

Q_w1 = (cos(w*t/2.) + sin(w*t/2.) * 1./w * A ) * Q_0

adds that real number to every element in the matrix on the right. The second code multiplies the matrix and vector beforehand, so the behaviour is different.

If you replace the first line of code with

Q_w1 = (cos(w*t/2.)*eye(4) + sin(w*t/2.) * 1./w * A ) * Q_0

then it gives the same output as line 2.


So the key difference is that adding a number to a matrix is not the same as adding the scalar times the identity matrix.

Note: I tested this in Octave, not Matlab - but AFAIK, they treat these the same.