Unexpected, unexplained, difference between Matrix linear index and row and column subscripts

1 view (last 30 days)
Good Morning;
writing a script I found myself discovering a difference i cannot explained.
for i=size(P,1)*size(P,2)
if A(i)>1
A(i)=1;
B(i)=P(i).*(2./(gamma+1));
C(i)=P(i)-(P(i)-B(i))./eta(type);
D(i)=Q(i).*(C(i)./P(i)).^(gamma./(gamma-1));
E(i)=sqrt(gamma.*R.*B(i));
F(i)=E(i);
end
end
writing the above code the end results were not as expected. i then wrote the same operations nesting 2 for cycles (row and column subscripts)
for i=1:size(P,1)
for j=1:size(P,2)
if A(i,j)>1
A(i,j)=1;
B(i,j)=P(i,j).*(2./(gamma+1));
C(i,j)=P(i,j)-(P(i,j)-B(i,j))./eta(type);
D(i,j)=Q(i,j).*(C(i,j)./P(i,j)).^(gamma./(gamma-1));
E(i,j)=sqrt(gamma.*R.*B(i,j));
F(i,j)=E(i,j);
end
end
end
this, strangely to me, gave me a different end result. I could not understand why.
A,B,C,D,E,F,P,Q
are all matrices of same dimension and enter both cycles with same values, same goes for
gamma,eta, type
I would appreciate if someone would be able to explain the difference in the two methods, that should have behaved identically in my mind.
tips on more efficient/elegant ways of achieving the above are also welcome

Accepted Answer

Bruno Luong
Bruno Luong on 26 Oct 2021
Edited: Bruno Luong on 26 Oct 2021
Try to change
for i=size(P,1)*size(P,2)
to
for i=1:size(P,1)*size(P,2)
You light also learn to use debugger so such task.

More Answers (1)

Esen Ozbay
Esen Ozbay on 26 Oct 2021
Edited: Esen Ozbay on 26 Oct 2021
You have forgotten to write 1: in the first line.
for i=size(P,1)*size(P,2)
must be
for i = 1:size(P,1)*size(P,2)
You probably got 0's in all elements except one in the arrays you obtained.

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!