With newer versions of MATLAB loops aren't as costly as you may think. If your function F
is something relatively simple that can be easily vectorized then you can usually get faster performance than using a for loop, but if F
represents a rather complex operation there may actually be more work required in trying to get around using a for loop.
Without knowing what F
actually does, it's difficult to give you a specific answer. However, in addition to vectorizing your operations, there are a few functions that can be used in place of for loops for certain situations. Some examples of these would be ARRAYFUN, CELLFUN, STRUCTFUN, and BSXFUN.
As an example of how to use BSXFUN, let's say that the operation F
that you are performing involves multiplying each column of B
by the value in the corresponding column of A
. In other words, C(:,i) = A(1,i).*B(:,i);
for all i
. You could do this using BSXFUN as follows:
C = bsxfun(@times,B,A);