How to increase the speed of this code?

1 回表示 (過去 30 日間)
Zhongruo Wang
Zhongruo Wang 2016 年 4 月 9 日
回答済み: Kuifeng 2016 年 4 月 9 日
Hi,
I write a script to check the lattice point the (vector pts), which is in the sphere centered at certain points(x and y) which is on the top side of the lattice. But this code works so slow which contains a lot of for loop and square root operation. Can you help me to fix this problem?
if true
% vt = 0.4;
pts1 = []
for i = 1:1:length(x)
for j = 1:1:length(pts)
dist = (x(i)-pts(j,1))^2+(y(i)-pts(j,2))^2+(pts(j,3))^2;
%distance from lattice to the seed
if dist <= vt^2
a = [pts(j,1) pts(j,2) -pts(j,3)];
disp(a);
pts1 = [pts1;a];
end
end
end
end

回答 (1 件)

Kuifeng
Kuifeng 2016 年 4 月 9 日
% 1. use vectors instead of the for loop to calculate distance, example
dist = sqrt(x.-xCenter).^2.+(y.-yCenter).^2.+(z.-zCenter).^2);
% 2. use 'find' for criteria <=vt^2. make some changes to the two lines
find(dist <=vt^2).

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by