Debug nested loop to calculate frequency sampling fir filter coefficients

조회 수: 1 (최근 30일)
Hello all,
I'm trying to simulate a frequency sampling fir filter, and I'm getting unanticipated output from my for loop. I don't understand why the first n-loop finishes (to 21), but the following iterations stop at n=1. Could I get another set of eyes on my code? Thank you, Justin
Hk =[Hb(6915) Hb(7517) Hb(8118) Hb(8719) Hb(9320) Hb(9922) Hb(10523) Hb(11124) Hb(11726) Hb(12327)] ;
H_ks = zeros((N-1)/2,N);
for k = 1:(length(k)-1)/2
for n = 1:length(n)
H_ks(k,n) = (2/N)*Hk(k)*cos((2*pi)/N).*k.*(n-((N-1)/2));
end
end

채택된 답변

Voss
Voss 2021년 12월 7일
Consider this loop:
k = [2 7 15 40 99];
for k = 1:(length(k)-1)/2 % this line redefines k
% do stuff
end
% after the loop, k has the value 2, which is (5-1)/2, so if you were to use this loop
% inside a bigger loop, you no longer have your original k (i.e., [2 7 15
% 40 99]) the next time through the big loop. This is the cause of the
% problem.
The problem is that you are using the same variable as the loop iteration variable and the vactor on which that variable is based. So, rewrite your code to be something like this:
Hk =[Hb(6915) Hb(7517) Hb(8118) Hb(8719) Hb(9320) Hb(9922) Hb(10523) Hb(11124) Hb(11726) Hb(12327)] ;
H_ks = zeros((N-1)/2,N);
for kk = 1:(length(k)-1)/2
for nn = 1:length(n)
H_ks(kk,nn) = (2/N)*Hk(kk)*cos((2*pi)/N).*kk.*(nn-((N-1)/2));
end
end
This preserves the values of k and n so you can use them again the next time through the loops.
  댓글 수: 1
Justin Gilmore
Justin Gilmore 2021년 12월 7일
Thank you for clarifying that. I don't know how long I've been overlooking that type of k-->kk detail

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by