Vectorize array of filters to avoid for-loop for different filters

3 Ansichten (letzte 30 Tage)
Dave Lee
Dave Lee am 15 Nov. 2018
Kommentiert: Mathieu NOE am 17 Mai 2023
Hi,
I need to use different filters for data. Each filter is applied to a 2D array, one dimension is time vector, the other dimension is the cases we want to apply filter. I have to run for-loop for different filters. Is there a faster way for the implementation as usually we vectorize to matrix operation to make it faster. The simplified code for representing the problem using for-loop is as below.
Thanks
clear all;
% Create a 2D-array for two vectors of data vs. time
time = [0:1e-3:10]';
x = [sin(time)+0.2*randn(size(time)),1.5*sin(time)+0.3*randn(size(time))];
% There are two filters
[b_filt(1,:),a_filt(1,:)] = butter(2,0.1);
[b_filt(2,:),a_filt(2,:)] = butter(2,0.2);
% Scan through all filters
for index_filter=1:size(b_filt,1)
% for each filter, apply filter to the data, along time axis, which is the first axis i.e. row
x_filtered(index_filter,:,:) = filter(b_filt(index_filter,:),a_filt(index_filter,:),x);
end
% Plot the result for one case for illustration
x_plot = x(:,1);
x_filt_plot = x_filtered(1,:,1);
figure;
hold on;
plot(time,x_plot(:),'b');
plot(time,x_filt_plot(:),'r');
legend('Pre-filtered','Filtered');
  2 Kommentare
Peter
Peter am 4 Mai 2023
I'm looking for the same solution!
Mathieu NOE
Mathieu NOE am 17 Mai 2023
you could put all your filters is serie (either by using series or making the convolution of the filter coefficients) and then run the time simulation only once

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by