# how to improve loops in matlab, especially with big variables.

3 views (last 30 days)
Markus on 14 Sep 2013
hei, i have two loops, where each point is checked how many other points are within a certain radius.
the point is, that i have a huge point cloud. 100000 xy coordinates are one of the smaller files. - this makes is run for ever.
data=rand(100000,3);
k=size(data,1);
data(:,4)=0;
for i = 1:k
for j=1:k
P=data(j,1:2);
if isPointInCircle(P, CR)
data(i,4)=data(i,4)+1;
end
end
end
##### 2 CommentsShowHide 1 older comment
Markus on 14 Sep 2013
the run and time analyses showed, that by 1000 datapoints the function isPointInCircle http://www.mathworks.com/matlabcentral/fileexchange/7844-geom2d/content/geom2d/geom2d/isPointInCircle.m needs about 20 seconds, while the loops need only 6 seconds. therefore is it more essential, to find a way to avoid unnecessary comparisons.

Chetan Rawal on 14 Sep 2013
You may want to see the vectorization link here. I tried doing the vectorization for you, but just got confused in the loops. Since you understand your program better than I do, you might be able to find a way after reading the info in this link.
##### 2 CommentsShowHide 1 older comment
Markus on 14 Sep 2013
ill try to explain the loops: loop 1 (i = 1:k), defines the point in the point cloud with a certain radius. and each point in the point cloud has to be compared to all others, whether the point is within the distance or not.
loop 2 (j = 1 : k), chooses one point (P) after another and checks whether this point lies within the radius of the first point (CR) if yes, the counter goes up.

Image Analyst on 14 Sep 2013
Allocate the 4th column of data in advance of the loops. Then, data has 3 (or 4) columns so what do you think you're getting for CR and P when you refer to data(i,1:2)? What's the third index? Why are you not specifying it?
Markus on 14 Sep 2013
i tried this and it went faster. unfortunatly only one second. - the problem is, that i need to get rid of unnecessary loops. so that points wich are far out of range are not going to be tested again. or i need a method, to skip the points in the second loop, when they have been tested in the first loop.
Generated 14-Sep-2013 18:13:12 using cpu time.
Function Name Calls Total Time Self Time*Total Time Plot
cleanPointClouds 1 24.952 s 5.131 s
isPointInCircle 1000000 19.822 s 19.822 s

### Categories

Find more on Classification Ensembles in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by