For loop FASTER than matrix multiplication

56 views (last 30 days)
Ben
Ben on 18 Feb 2014
Edited: Matt J on 7 Mar 2014
I am attempting to optimize some code I wrote a few months ago for speed. The code (see below or attached .m file) is used to "smooth" data by computing a weighted average of each points nearest two neighbors. I originally had this in a loop but have recently decided more smoothing is in order and therefore I have to do the entire process many more times, anywhere from 5,000 to 30,000 times as part of a larger function. This led me to attempt to optimize the code in terms of speed.
I read that matrix operations are typically much faster than loops in MATLAB and figured out a "matrix equivalent" way of doing the routine. Using the "Run and Time" function in MATLAB, however, I find that the old way (loops) is almost 3x as fast. Can anyone explain this to me and/or make suggestions of alternative methods? I have attached a typical data set as a .csv file.
function [smoothed_points] = smoothing(input_y,smoothing_loops,method)
f = input_y;
f_length = length(f);
f_smoothed = zeros(1,f_length);
if method == 0
%%%New Method
smooth_1 = diag(ones(f_length,1),-2);
smoothing_matrix = smooth_1(1:end-2,1:end-4) + eye(f_length,f_length-2);
for j = 1:smoothing_loops
center_points = f(2:end-1)./2;
surrounding_points = f./4;
f_smoothed(2:f_length-1) = surrounding_points*smoothing_matrix + center_points;
f_smoothed(1) = 3*f(1)/4 + f(2)/4;
%smooth last point
f_smoothed(length(f)) = 3*f(length(f))/4 + f(length(f)-1)/4;
f = f_smoothed;
end
else
%%%Old Method
for j = 1:smoothing_loops
for i = 2:length(f)-1
f_smoothed(i) = f(i-1)/4 + f(i)/2 + f(i+1)/4;
end
%smooth first point
f_smoothed(1) = 3*f(1)/4 + f(2)/4;
%smooth last point
f_smoothed(length(f)) = 3*f(length(f))/4 + f(length(f)-1)/4;
%set solution to smoothed solution
f = f_smoothed;
end
end
smoothed_points = f_smoothed;

Answers (2)

per isakson
per isakson on 18 Feb 2014
Edited: per isakson on 6 Mar 2014
"matrix operations are typically much faster than loops in MATLAB". With recent releases of Matlab, that is a rule with many exceptions.
One reason why your "matrix equivalent" takes longer might be that it allocates and moves around a lot more data in the memory than does the for-loop-solution.
See:

Matt J
Matt J on 7 Mar 2014
Edited: Matt J on 7 Mar 2014
Another reason the matrix version may be slower is that you are not using the sparse matrix data type to hold "smooth_1" and "smoothing_matrix". This makes the matrix multiplication operations much more expensive than they could be.
Conversely, the double for-loop method uses only the non-zero data that participate non-trivially in the calculations.

Community Treasure Hunt

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

Start Hunting!