Reputation: 21
I am trying to vectorise a for
loop. I have a set of coordinates listed in a [68x200]
matrix called plt2
, and I have another set of coordinates listed in a [400x1]
matrix called trans1
. I want to create a three dimensional array called dist1
, where in dist1(:,:,1)
I have all of the values of plt2
with the first value of trans1
subtracted, all the way through to the end of trans1
. I have a for loop like this which works but is very slow:
for i=1:source_points;
dist1(:,:,i)=plt2-trans1(i,1);
end
Thanks for any help.
Upvotes: 2
Views: 101
Reputation: 318
Vectorizing is a good first optimization, and is usually much easier than going all in writing your own compiled mex-function (in c).
However, the golden middle-way for power users is Matlab Coder (this also applies to slightly harder problems than the one posted, where vectorization is more or less impossible). First, create a small m-file function around the slow code, in your case:
function dist1 = do_some_stuff(source_points,dist1,plt2,trans1)
for i=1:source_points;
dist1(:,:,i)=plt2-trans1(i,1);
end
Then create a simple wrapper function which calls do_some_stuff as well as defines the inputs. This file should really be only 5 rows, with only the bare essentials needed. Matlab Coder uses the wrapper function to understand what typical proper inputs to do_some_stuff are.
You can now fire up the Matlab Coder gui from the Apps section and simply add do_some_stuff under Entry-Point Files. Press Autodefine types and select your wrapper function. Go to build and press build, and you are good to go! This approach usually bumps up the execution speed substantially with almost no effort.
BR Magnus
Upvotes: 0
Reputation: 112689
If I understood correctly, this can be easily solved with bsxfun
:
dist1 = bsxfun(@minus, plt2, shiftdim(trans1,-2));
Or, if speed is important, use this equivalent version (thanks to @chappjc), which seems to be much faster:
dist1 = bsxfun(@minus, plt2, reshape(trans1,1,1,[]));
In general, bsxfun
is a very useful function for cases like this. Its behaviour can be summarized as follows: for any singleton dimension of any of its two input arrays, it applies an "implicit" for
loop to the other array along the same dimension. See the doc for further details.
Upvotes: 3