Why do I need to declare a variable inside a nested 'for' loop?

1 visualizzazione (ultimi 30 giorni)
Hi, I have some code, below, which fails on the last line before both 'end's (T_noise_out(it) = ....). The Command Window tells me that this is due to T_noise_out being an unrecognised variable. However, just a few lines above it, I am able to use 'F_noise_in(term_num)' and 'F_noise_out(term_num)' without explicitly declaring them. Why is this? I anticipated that this code would create an array of complex numbers called T_noise_out.
%term loop
for term_num = 1: 2: nterms
fprintf('Processing term %g of %g \n', term_num, nterms);
%Add new Fourier coefficient
F_noise_in(term_num) = -i*4/(pi*term_num);
F_noise_out(term_num) = F_noise_in(term_num).*H(term_num);
for it = 1: 1: ntsamples
t = (it-1).*dt;
real_F_noise_out = real(F_noise_out(term_num));
imag_F_noise_out = imag(F_noise_out(term_num));
T_noise_out(it) = T_noise_out(it)+real_F_noise_out*cos(2*pi*f0*term_num*t)-imag_F_noise_out*sin(2*pi*f0*term_num*t);
end
end

Risposta accettata

Adam
Adam il 22 Ott 2019
Modificato: Adam il 22 Ott 2019
You are referring to it on the right-hand side of the equation as well as on the left. First time round it does not exist yet so that will error. You would need to initialise it before your outer loop to contain 0s of the correct size if you intend to store a running sum in it.
  1 Commento
Ted Baker
Ted Baker il 22 Ott 2019
Thanks Adam for the clear answer. For reference, my working code is as follows:
T_noise_out = zeros(1,ntsamples,'uint32');
for term_num = 1: 2: nterms
fprintf('Processing term %g of %g \n', term_num, nterms);
%etc etc etc...

Accedi per commentare.

Più risposte (0)

Categorie

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

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by