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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by