Vectorization is a programming technique where operations are applied to entire arrays or matrices simultaneously, rather than iterating element by element using explicit loops. By reshaping the 3D image stack into a 2D matrix, where each column corresponds to the time-series of a single pixel, the lowpass function can be applied simultaneously across all pixels without explicit loops. This approach not only improves speed significantly but also reduces overhead and makes better use of memory. After filtering, the data can be reshaped back into the original 3D form.
The following steps can be followed to achieve the same:
- Reshape the 3D stack into a 2D matrix:
[rows, cols, frames] = size(gaus_filt);
reshaped_data = reshape(gaus_filt, [], frames);
Size: [rows*cols, frames]
- Transpose the matrix to have time-series as columns:
data_T = reshaped_data.';
- Apply the low-pass filter simultaneously to all pixel time-series:
filtered_T = lowpass(data_T, 0.2);
- Transpose back and reshape to the original 3D size:
filtered_data = reshape(filtered_T.', rows, cols, frames);
The following shows how the outputs matches but the elapsed time is less in the vectorized method:
Please refer to the following documentation to get more information on vectorization in MATLAB:
I hope this helps!