Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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.

Réponse acceptée

Torsten
Torsten le 23 Oct 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by