FOR Loop not giving correct answer

1 view (last 30 days)
Mark Sc
Mark Sc on 15 Mar 2021
Commented: David Hill on 15 Mar 2021
Hi all,
I'd like to calculate the sum of C_ortho based on two different conditions, so I introduced 2 different for loops however, the result obtained are the same ,
In other terms, I'd like to add C(:,:,1,1)+C(:,:,2,1)... and C(:,:,1,2)+C(:,:,2,2).......
I attached my code below
clearvars
clc;
C(:,:,1,1)=[1.3621 0.0391 0.0391 0 0 0;
0.0391 .0925 0.0373 0 0 0;
.0391 .0373 .00925 0 0 0;
0 0 0 .0276 0 0;
0 0 0 0 .0431 0;
0 0 0 0 0 .0431];
C(:,:,2,1)=[.0925 .0391 0.0373 0 0 0;
0.0391 1.3621 0.0391 0 0 0;
.0373 .0391 .0925 0 0 0;
0 0 0 .0431 0 0;
0 0 0 0 .0276 0;
0 0 0 0 0 .0431];
C(:,:,1,2)=[1.3386 .0023 0 0 0 0;
0.0023 .00012 0 0 0 0;
0 0 .00012 0 0 0;
0 0 0 7 0 0;
0 0 0 0 5 0;
0 0 0 0 0 5];
C(:,:,2,2)=[10 .45 0 0 0 0;
.45 .00012 0 0 0 0;
0 0 .00012 0 0 0;
0 0 0 8 0 0;
0 0 0 0 6.1 0;
0 0 0 0 0 5];
C_ortho = zeros(6,6,2);
for i=1:2
for j=1:2
C_ortho = C_ortho+1.5*C(:,:,i,j);
end
end

Answers (1)

David Hill
David Hill on 15 Mar 2021
C(:,:,1,1)+C(:,:,1,2);
C(:,:,2,1)+C(:,:,2,2);
  2 Comments
Mark Sc
Mark Sc on 15 Mar 2021
Thanks David for your comment, however, I need to do it in a loop as it's a part of large code, and sometimes, i, j indices changes...
David Hill
David Hill on 15 Mar 2021
for i=1:2
for j=1:2
C_ortho(:,:,i) = C_ortho(:,:,i)+1.5*C(:,:,i,j);
end
end

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!