How can I structure a loop to calculate a range of residuals to determine optimal filter cut-off frequency?

7 views (last 30 days)
I'm new to loops and I'd like some help in structuring a for loop statement so I can calculate the root mean square error for a range of different filter cut-off frequencies and store those results in a vector.
This is the design of my filter. However, I'm not certain of how to assign fcutlow to account for a wide range of cut-offs.
% Filter design.
fs = 800 % Sampling frequency.
fcutlow = (4:0.1:20); % Cut-off frequency in Hz. Start at 4 Hz, increment by 0.1 Hz and end at 20 Hz.
order = 4;
[b, a] = butter(order, fcutlow / (fs / 2));
% Filter data.
filt = filtfilt(b, a, rawdata);
I essentially want to run a for loop to repeat the statements above. I'm just stuck on how to structure my for loop so I can calculate the root mean square error between the filtered data (filt) and rawdata for a cut-off starting at 4 Hz, incrementing by 0.1 Hz and ending at 20 Hz. My residual calculation is:
rmse = sqrt(mean((rawdata - filt) .^2));
I then want the rmse of every iteration stored in a separate vector so I can plot them later.
Can someone please help me structure these statements in a for loop?
Thank you.

Accepted Answer

Ahmed Redissi
Ahmed Redissi on 14 Apr 2021
Edited: Ahmed Redissi on 14 Apr 2021
Hi,
You can structure your loop this way to iterate over the cutoff frequencies and calculate the root mean square error:
fcutlow = (4:0.1:20); % Cut-off frequency in Hz. Start at 4 Hz, increment by 0.1 Hz and end at 20 Hz.
N = numel(fcutlow); % Number of cut-off frequencies
rmse = zeros(1,N); % Initialize the RMSE array to zeros
fs = 800; % Sampling frequency.
order = 4;
for i = 1:N
% Filter design.
[b, a] = butter(order,fcutlow(i)/(fs/2));
% Filter data.
filt = filtfilt(b,a,rawdata);
% Calculate the RMSE
rmse(i) = sqrt(mean((rawdata-filt) .^2));
end
% Plot the RMSE versus the cut-off frequency
plot(fcutlow,rmse)
xlabel('Cut-off Frequency (Hz)')
ylabel('RMSE')

More Answers (0)

Community Treasure Hunt

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

Start Hunting!