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

1 visualización (últimos 30 días)
Ted Baker
Ted Baker el 22 de Oct. de 2019
Comentada: Ted Baker el 22 de Oct. de 2019
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

Respuesta aceptada

Adam
Adam el 22 de Oct. de 2019
Editada: Adam el 22 de Oct. de 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 comentario
Ted Baker
Ted Baker el 22 de Oct. de 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...

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by