optimize inefficient piece of code
3 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I have a piece of code as part of a bigger piece that is inefficient. The code is called many times and is a bottleneck in the proces also according to the matlab profiler. I feel it can be done faster. The code looks as follows
clear all
% initialize variables of interest
l1=rand(1,10);
l2=rand(1,10);
p1=rand(3,10);
p2=rand(3,10);
% start inefficient code
[c,ind]=min([l1;l2]);
r(:,:,1)=p1;
r(:,:,2)=p2;
for it=1:10
p3(:,it)=r(:,it,ind(it));
end
I would like to do the for loop in one go (so remove the for loop). l1 and l2 are distances (l1 is norm of p1 and l2 is norm of p2), and p1, p2 are 3d coordinates. The goal of the code is to pick the coordinates of p1, p2 from the one with the smallest distance.
採用された回答
Simon
2014 年 1 月 6 日
Hi!
You can of course avoid the loop with
p3(1:3, ind==1) = p1(:, ind==1);
p3(1:3, ind==2) = p2(:, ind==2);
This avoids the r-lines before the loop as well. Use '~' instead of 'c' if you are not interessted in the value of the 'min' call.
4 件のコメント
Simon
2014 年 1 月 7 日
I think because of the overhead, like checking the input for correct type and dimension and things like that. But that implies that you know what you do and what kind of input to your substitutes you have.
その他の回答 (0 件)
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!