FOR Loop not giving correct answer

1 次查看(过去 30 天)
Mark Sc
Mark Sc 2021-3-15
评论: David Hill 2021-3-15
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

回答(1 个)

David Hill
David Hill 2021-3-15
C(:,:,1,1)+C(:,:,1,2);
C(:,:,2,1)+C(:,:,2,2);
  2 个评论
Mark Sc
Mark Sc 2021-3-15
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 2021-3-15
for i=1:2
for j=1:2
C_ortho(:,:,i) = C_ortho(:,:,i)+1.5*C(:,:,i,j);
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by