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

1 次查看(过去 30 天)
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

采纳的回答

Adam
Adam 2019-10-22
编辑:Adam 2019-10-22
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 个评论
Ted Baker
Ted Baker 2019-10-22
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...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by