MATLAB: How to vectorize inside user defined functions to avoid nested loops

for loopindexingvectorization

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?

Best Answer

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.