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

3 次查看(过去 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 CenterFile Exchange 中查找有关 Loops 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