Debug nested loop to calculate frequency sampling fir filter coefficients

1 view (last 30 days)
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

Accepted Answer

Voss
Voss on 7 Dec 2021
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!