Vectorize array of filters to avoid for-loop for different filters
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Mathieu NOE
2023-5-17
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
回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!