Debug nested loop to calculate frequency sampling fir filter coefficients

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Voss
Voss am 7 Dez. 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.
  1 Kommentar
Justin Gilmore
Justin Gilmore am 7 Dez. 2021
Thank you for clarifying that. I don't know how long I've been overlooking that type of k-->kk detail

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by