How to vectorize inside user defined functions to avoid nested loops?

4 views (last 30 days)
Hello everyone, I'm trying to vectorize some code so as to avoid making a nested loop. However, at the innermost loop I have to run a function that I've defined myself, and I can't seem to find a way to make that function "understand" its inputs properly. What I have right now, which works but is rather slow, is something like this:
for i = 1:n*m
for j = 1:n*m
I_ww(i,j) = InfluenceLine(XcWing(i,j),YcWing(i,j),ZcWing(i,j),XvWing,YvWing,ZvWing,XnWing(i,j),YnWing(i,j),ZnWing(i,j),AngleOfAttack);
end
end
I'd like to rewrite that so it looks something like this:
I_ww(:,:) = InfluenceLine(XcWing(:,:),YcWing(:,:),ZcWing(:,:),XvWing,YvWing,ZvWing,XnWing(:,:),YnWing(:,:),ZnWing(:,:),AngleOfAttack);
I've realized, however, that with this syntax, the inputs which were supposed to be scalars, namely XcWing(i,j) and so forth, are now the entire matrices XcWing, which my function does not support. Is there a way to get the function to compute only one element of each of the input matrices at a time?
  5 Comments
Stephen23
Stephen23 on 27 Jan 2016
Edited: Stephen23 on 27 Jan 2016
The usual way to resolve if-like decisions in vectorized code is to use indexing (logical indexing is the fastest), typically either:
  • pick an array susbset using indices, apply operation to it, replace into a subset of the array. The rest of the array remain unchanged.
  • apply an operator to the entire array, then use indices to replace a subset of elements with zero/NaN/...
Also note that both cross and dot can be applied to multidimensional arrays, so you can vectorize these operations too. Read the documentation to see how this works: I would highly recommend that you use the syntax using the optional dimension argument, like this example from the documentation:
>> A = cat(3,[1 1;1 1],[2 3;4 5],[6 7;8 9]);
>> B = cat(3,[2 2;2 2],[10 11;12 13],[14 15; 16 17]);
>> C = dot(A,B,3)
C =
106 140
178 220
"The result, C, contains four separate dot products. The first dot product, C(1,1) = 106, is equal to the dot product of A(1,1,:) with B(1,1,:)."
Both of these changes will mean going through your entire code and rewriting it all... but is seems like it might be possible. Good luck!

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 27 Jan 2016
I_ww = arrayfun(@InfluenceLine, XcWing, YcWing, ZcWing, XvWing, YvWing, ZvWing, XnWing, YnWing, ZnWing, AngleOfAttack);
provided that all of the arguments are either scalars or arrays the same size as each other.
This will not necessarily be any faster than looping, and typically would be slower.
It would be far better to write the function to accept arrays.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!