フィルターのクリア

Storing output from inner for loop after every itteration of outer for loop in nested for loops.

1 回表示 (過去 30 日間)
I want to be able to store the output from n=1 and n=2 into an array.
With my current code a(1) is retrived as 0.124( sum of cos(n=1*m=1) and cos(n=1*m=2)) which is correct, but a(2) is retrieved as -0.945 which is incorrect.
I want a(2) to be -1.069(sum of cos(n=2*m=1) and cos(n=2*m=2)). How can i ensure it runs through inner loop for n value stores it to array, runs for inner loop for next n value and again stores it to the array?
a=zeros(1,2);
sum=0;
for n=1:2;
for m=1:2;
sum = sum + cos(n*m);
end
a(n)=sum;
end
thank you.

採用された回答

Torsten
Torsten 2022 年 10 月 23 日
a=zeros(1,2);
for n=1:2
sum = 0.0;
for m=1:2
sum = sum + cos(n*m);
end
a(n)=sum;
end
a
a = 1×2
0.1242 -1.0698

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by