Stuart’s MATLAB Videos

Watch and Learn

When only small speed improvements are possible in MATLAB 2

Posted by Doug Hull,

The profiler is very important when you want to speed up your code. It is nearly impossible to know where the bottleneck will be in your code until it is written and tested. Often times there are basic things you can do to speed your code. These basic things include pre-allocate vectors. What do you do when the basic things do not help or have already been done?

2 CommentsOldest to Newest

Sven replied on : 1 of 2

While each of the steps in the video are well described, I think it’s important to reiterate one of MATLAB’s strengths – working with matrices/vectors. In this case, tinkering with the for-loop gains a 2x speedup, but recognising when a loop can be vectorised and “calculated at once” gains a 40x speedup.

function value = optimiseMe5( big )
value = ones(1,big)*3; % Init to the “else” part
% Which entries belong to the first “if” statement ?
ifMask = rand(1,big) > 0.5;
% Set them to the sum of 3 rand numbers
value(ifMask) = sum(rand(3,nnz(ifMask)));
% Of the remaining (~ifMask) entries, flip them randomly
ifMask(~ifMask) = rand(1,nnz(~ifMask)) > 0.5;
% Whichever entries remain (~ifMask) belong to “elseif”
value(~ifMask) = 0;

Doug replied on : 2 of 2


Yes, this was a very academic exercise that was overlooking larger issues so that focus could be put into one piece in isolation.

Thanks for watching!

Add A Comment

What is 2 + 7?

Preview: hide