How do I store values from inside a loop?

1 view (last 30 days)
In my program, I'm creating a Butterworth filter and making a couple of calculations (E1 and E2 in the code). I want to store the values of E1 and E2 into a file, and be able to identify the order (i in the code), and the cutoff frequency (w in the code) of a specific value later on. If I write them into an array or a matrix, I'm afraid I won't be able to identify the values. What should I do?
order = input('Enter max order of the filter: ')
Fsam = input('Enter sampling frequency in Hertz: ')
f = 0 : 0.01 : Fsam/2;
for i = 1:order
for w = 0.1:0.1:0.9
[b,a] = butter(i,w);
H = freqz(b,a,f,Fsam);
fc = w * Fsam / 2;
p = find(f == fc);
PassBand = ones(1,p);
I1 = PassBand - H(1:p);
J1 = mean(I1);
E1 = abs(J1);
StopBand = zeros(1,length(f)-p);
I2 = H(p+1:length(f)) - StopBand;
J2 = mean(I2);
E2 = abs(J2);
end
end

Accepted Answer

Tobias
Tobias on 19 Mar 2013
Firstly, I'll pass on an advice that I was once given here on the forum. You ought to use another letter in your loop than i, k for example. I believe this is because Matlab uses i and j for imaginary numbers, so just to safe yourself the mess, make it a habit to use another letter.
To fix your problem, you can assign variables as functions, which will store it in a vector / matrix. To do this, you should change your code to the following:
Notice especially the lines: 4, 6, 13 and 17
order = input('Enter max order of the filter: ')
Fsam = input('Enter sampling frequency in Hertz: ')
f = 0 : 0.01 : Fsam/2;
for k = 1:order
for w = 0.1:0.1:0.9
[b,a] = butter(k,w);
H = freqz(b,a,f,Fsam);
fc = w * Fsam / 2;
p = find(f == fc);
PassBand = ones(1,p);
I1 = PassBand - H(1:p);
J1 = mean(I1);
E1(k) = abs(J1);
StopBand = zeros(1,length(f)-p);
I2 = H(p+1:length(f)) - StopBand;
J2 = mean(I2);
E2(k) = abs(J2);
end
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!