Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Torsten
Torsten il 23 Ott 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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by