Please see the second piece of code snippet from my last blog post . We were able to reduce the execution time of the algorithm from 66.5 msec to 36.5 msec after relying on Preallocation. In this post I want to work on the same algorithm, and see if I can make it more efficient. For this I want to rely on the power of logical expressions and indexing in Matlab. Without too much explanation let me share the code which does this: b = a(a < 0.5); Yes, Thats it! Just one line. :) Let me explain the code. The line (a < 0.5) creates a logical array of 1's and 0's depending on whether the element is less than 0.5 or not. The size of this logical array is same as the size of array 'a'. Suppose if a=[0.01 0.49 0.5 0.8], the logical array would be like this, [1 1 0 0]. The 1's are equivalent to the logical value TRUE and 0's imply a logical value of FALSE. Now, when I write, a(a < 0.5) it means that I am interested in only elements which hav...
This is the first post in the series of Making Matlab Code Faster series. As you might have realized already, getting stuff somehow to get to work, might be a fairly simple task with Matlab. But why stop there? Why not make the necessary changes to see if your code can perform better. There are few things you can do towards this goal. Preallocation is just one of them. Let's look at an example: a=rand(1000000,1); %Declare a random matrix with 1 million elements b=0; j=1; for i=1:size(a,1) %run the loop for the all the elements in 'a'. if (a(i) < 0.5) %if the current element is less than 0.5 save it in an array 'b' b(j)=a(i); j=j+1; %increment j to save next element in the next location in 'b' end end We can see that initially array 'b' is single element matrix. But as time goes on, we keep ...