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
댓글 수: 0
채택된 답변
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!