Can someone help me optimize my MATLAB code by vectorizing loops?

  • Context: MATLAB 
  • Thread starter Thread starter dpsguy
  • Start date Start date
  • Tags Tags
    Loops Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 9K views
dpsguy
Messages
69
Reaction score
0
Could someone please tell me how to make the following code in MATLAB more efficient? I am particularly keen to remove the for loop, as I understand that vectorizing the loop makes the program run much faster.

R=rand(ret,len);
[i j]=find(R<pm);
N=horzcat(i,j);
for i=1:length(N)
X(N(i,1),N(i,2))=bitcmp(X(N(i,1),N(i,2)),1);
end

Here ret and len are positive integers and pm is a number between 0 and 1. X is a matrix of dimensions (ret x len) and is filled with 0s and 1s at random. Basically what this piece of code does is meant to do is generate a random number between 0 and 1 for each element of the matrix X and check if the generated number is less than pm. If it is, then it replaces that element in the matrix with its ones complement.

Any help would be appreciated.
 
Physics news on Phys.org
You can use logical indexing:


Code:
R = rand(ret,len);
X(R<pm) = bitcmp(X(R<pm),1);

or equivalently since I don't think you need to use bitcmp,

Code:
R = rand(ret,len);
X(R<pm) = ~X(R<pm);

That overwrites the values of X that have the same indices of the desired values of R.

I'm not sure if that will appreciably speed up your code (you can check using tic and toc or using MATLAB's profiler). Logical indexing is faster, but I thought MATLAB accelerates its code nowadays so that for loops actually run as fast (provided they follow certain rules; check the mathworks website for code acceleration/optimization). Changing from calling bitcmp to just negating the value may speed things up a bit... but it may not since I think built-in functions run pretty fast... Hope that helps...
 
Thanks a lot jamesrc! Your suggestions improved the speed and also the look of the program.