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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by