# Double for loop problem. Function within 2nd for loop no longer works properly.

1 view (last 30 days)
Ben Robson on 24 Nov 2021
Commented: Ben Robson on 25 Nov 2021
I'm trying to create graphs of 8 Fourier transform calcultations. When I input the nmax value manually, my function works correctly, but as I'd like to graph all 8 results simultanneously, i've created another for loop. However, this is changing the function output and I don't understand why. nmax(i) has the correct value becuase it's displayed in the graph subtitle correctly, yet the function does not output the same graph as when I input the values for nmax manually.
It must be an issue with the structure of my for loops. I'm new to MATLAB. Any help apprecitated, thank you :)
clear, clc, clf;
nmax = [1, 3, 5, 10, 20, 50, 100, 200];
t = 0:0.01:20;
T = 5;
A = 2;
a0 = A/2;
wo = 2*pi/T;
Q = ones(1,length(t));
FS = a0*Q;
for i = 1:length(nmax)
for n = 1:nmax(i)
an = A / (pi*n) * sin(pi*n);
bn = A * (1- cos(pi*n)) / (pi*n);
FS = FS + an*cos(n*wo*t) + bn*sin(n*wo*t);
end
subplot(length(nmax)/2,2,i);
plot(FS);
title('Trigonometric Fourier Series Sum');
txt=['nMax = ', num2str(nmax(i))];
subtitle(txt);
xlabel('Time');
ylabel('Amplitude');
ylim ([-5 20]);
end
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Benjamin on 24 Nov 2021
Move this line:
FS = a0*Q;
into your outer for loop (but still outside the inner loop). This will re-initialize FS each time through the outer loop, which is necessary because otherwise the result is accumulated with the previously calculated FS values.
##### 1 CommentShowHide None
Ben Robson on 25 Nov 2021
That's it! Thanks for your help.

Sign in to comment.

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by