Search code examples
matlabmatrixmatrix-multiplication

Matrix multiplication and differences


I need to compute this equation with MATLAB:

enter image description here

where Sn can be both matrices or scalar and I tried to do it with

S_A = S_3*S_5*((ones-(S_1*S_5)).^(-1))*S_2+S_4

The problem is it doesn't give me the right result and the problem it seems to be with the difference enter image description here but I cannot figure why is giving me wrong results.

The result is supposed to be this one

enter image description here

but the MATLAB result is

enter image description here

I don't understand why the two results are not the same. The only way that I figured is through this

diff = ones-(S_1*S_5);
if S_1*S_5 == zeros         %Perchè senza non funziona?
    diff = ones;
else 
    diff = (ones-(S_1*S_5)).^(-1)
end
S_A = S_3*S_5*diff*S_2+S_4;

But I don't think it's a smart solution. Anyone knows why I'm not getting the correct results?


Solution

  • "I tried to do it with S_A = S_3*S_5*((ones-(S_1*S_5)).^(-1))*S_2+S_4"

    The problem here is that A^(-1) in mathematical notation means "take the inverse", whereas you used A. ^(-1), note the dot, which in MATLAB's notation means "take the each matrix element to the power -1". Taking the inverse of a matrix is not smart in MATLAB anyway, be it via inv() or ^(-1), instead, use mldivide:

    S_A = S_3*S_5*(eye(size(S_1*S_5,1))-(S_1*S_5))\S_2+S_4
    

    Also, as mentioned in Brice's answer use eye, not ones to create an identity matrix, and feed it a size argument as opposed to nothing. All in all it looks to me like you do not have a firm grasp of basic MATLAB functionality, so I'd like to point you to The MathWorks own tutorial on MATLAB.