Inner loop not working
Afficher commentaires plus anciens
Hi, I am trying to run the following code with a nested loop. It seems that for each value of i the inner loop works only once, that is only for k=0 and does not run for the rest of the values of k. Any advice will be highly appreciated. If you need any further information, please let me know.
N.B. I deliberately avoided writing out the full question that I am trying to solve since it's a homework question and I don't want specific answers to be publicly available.
function summa=my_func(n)
t=linspace(0,4*pi, 1001);
len=length(t);
summa=zeros(1,len);
b=0;
for i=1:1001
for k=0:n
numerat=((-1)^k)*sin((2*k+1)*t(i));
denomat= ((2*k)+1)^2;
b=b+ (numerat/denomat);
end
summa(i)=summa(i)+b;
end
5 commentaires
Jan
le 28 Fév 2017
Thanks for mentioning explicitly, that this is a homework.
Chad Greene
le 28 Fév 2017
What value for n are you using?
Tasneem Raihan
le 28 Fév 2017
Walter Roberson
le 28 Fév 2017
Are you sure that you want b to accumulate over all i values? Perhaps b should initialize inside the i loop?
Tasneem Raihan
le 28 Fév 2017
Réponse acceptée
Plus de réponses (1)
Chad Greene
le 28 Fév 2017
Modifié(e) : Chad Greene
le 28 Fév 2017
Perhaps you need to move the b=0 after i=1:1001:
for i=1:1001
b=0;
for k=0:n
1 commentaire
Tasneem Raihan
le 28 Fév 2017
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!