views:

93

answers:

2

I'm looking for any good tutorials on vectorizing (loops) in MATLAB.

I have quite simple algorithm, but it uses two for loops. I know that it should be simple to vectorize it and I would like to learn how to do it instead of asking you for the solution.

But to let you know what problem I have, so you would be able to suggest best tutorials that are showing how to solve similar problems, here's the outline of my problem:

B = zeros(size(A));    % //A is a given matrix.
for i=1:size(A,1)
   for j=1:size(A,2)
      H = ... %// take some surrounding elements of the element at position (i,j) (i.e. using mask 3x3 elements)
      B(i,j) = computeSth(H); %// compute something on selected elements and place it in B
   end
end

So, I'm NOT asking for the solution. I'm asking for a good tutorials, examples of vectorizing loops in MATLAB. I would like to learn how to do it and do it on my own.

+5  A: 

Here are a couple of MathWorks tutorials I often link to as references on the subject:

And here's one of Loren's blog posts that has a nice walkthrough of code vectorization for a particular sample problem:

The particular type of problem you gave as a sample, which involves processing submatrices of a given matrix, could be vectorized in different ways depending greatly on what sort of operation you are doing. You may be able to use CONV2 or FILTER2 instead of your nested for loops. There are also a number of functions in the Image Processing Toolbox that handle neighborhood and block processing of matrices, such as NLFILTER and BLOCKPROC. The documentation for these functions should help you figure out how to use them as a way to vectorize your code.

gnovice
@gnovice: I would strongly argue against using blockproc if you can avoid it - it's very slow (also, it underwent an incompatible change from 2009a to 2009b). If you have sufficient RAM, it's always preferable to run `im2col` and apply the function in one go.
Jonas
@Jonas: Good to know. I don't actually use BLOCKPROC often enough to have come across those issues. I was just listing it as one of a number of options the OP might want to look into.
gnovice
+1  A: 

The rule of thumb is that you should use built-in matlab functions that operate on arrays in place of loops whenever possible. For example, it seems to me that the problem you've described can be formulated as a convolution, and then you can use matlab's conv2() or filter() functions to implement it without the loop.

Another general trick is to try to formulate your problem in terms of matrix operations.

You should also prefer trading space for time. Let's say you have an n-dimensional vector v and an m x n matrix M, where every row is also an n-dimensional vector. Let's say you want the Euclidean distances between v and every row of M. In this case you should use repmat() to create a matrix containing m copies of v, and calculate the distances using element-wise array operations without a loop.

Dima