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

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

 采纳的回答

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.

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品

版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by