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

조회 수: 2 (최근 30일)
Ted Baker
Ted Baker 2019년 10월 22일
댓글: Ted Baker 2019년 10월 22일
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