Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Vectorizing loops in MATLAB

  1. Jan 24, 2009 #1
    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.

    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.
     
  2. jcsd
  3. Jan 28, 2009 #2

    jamesrc

    User Avatar
    Science Advisor
    Gold Member

    You can use logical indexing:


    Code (Text):

    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 (Text):

    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...
     
  4. Jan 31, 2009 #3
    Thanks a lot jamesrc!! Your suggestions improved the speed and also the look of the program.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Vectorizing loops in MATLAB
  1. Vectors in matlab (Replies: 3)

  2. For loop in matlab (Replies: 3)

Loading...