Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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.

Akzeptierte Antwort

Torsten
Torsten am 23 Okt. 2022
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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by