2 CommentsOldest to Newest
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;
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!