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.