0

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?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Shika93
  • 635
  • 4
  • 24

2 Answers2

5

"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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
4

ones outputs a matrix filled with ones, not the identitiy matrix which is given by function eye. You also need to specify the size of ones or eye, otherwise it will simply output a scalar 1 (i.e. a 1-by-1 matrix filled with ones, or the 1-by-1 identity matrix).

Try (assuming all matrices have the same size):

siz=length(S_1);
S_A = S_3*S_5*((eye(siz)-(S_1*S_5))^(-1))*S_2+S_4
Brice
  • 1,560
  • 5
  • 10
  • That's exactly what I did, Adriaan. I replaced `.^(-1)` with `^(-1)` because when `S_1*S_5 = 0` the ratio gives a `1/0` problem while with `.^(-1)` I don't have this problem. It seems you solved my problem. Thanks a lot! – Shika93 Nov 12 '18 at 10:59
  • Indeed, I had missed the element-wise operation on my side. – Brice Nov 12 '18 at 12:23