How to preallocate 2D array before for loop?

11 次查看(过去 30 天)
Hi!
I have a 2D array with Points in every row (called occWorld). Now I want to calculate the distances between every point and write the points in a new array, when the distance between them is below 0.24. Matlab tells me to preallocate my array, but I cant figure out how to do that.
I want to find all the points in a range of 0.24 meter and cluster them.
This is what I have got:
Trees = [];
for f = 1:length(occWorld(:,1))
for e = f+1:length(occWorld(:,1))
Points = [occWorld(f,:);occWorld(e,:)];
Dist = pdist(Points);
if Dist < 0.24
Trees = [Trees;Points];
Trees = unique(Trees,'rows');
end
end
% delete before new set of points ist calculated
Trees = [];
end
Thank you!
  2 个评论
Walter Roberson
Walter Roberson 2022-8-11
编辑:Walter Roberson 2022-8-11
Note that because of that Trees = []; just before the end of the for loop, the only output from this code will be Trees = [] and Dist being a scalar numeric value.
This is an important point because it affects our preallocation strategy.
Jan
Jan 2022-8-11
length(occWorld(:,1)) is less efficient than size(occWorld,1).

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2022-8-11
Do not collect the points, but a list of their indices. If you use logical indexing, you can omit the expensive unique also:
n = size(occWorld, 1);
M = false(n, 1);
Dist2 = 0.24^2;
for f = 1:n
P1 = occWorld(f, :);
for e = f+1:n
v = P1 - occWorld(e, :);
if v * v.' < Dist2
M(e) = true;
M(f) = true;
end
end
end
Trees = occWorld(M, :);
Your example replies Trees=[] in every case, as Walter has mentioned. I guess, that you do want to obtain the Trees as result.

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by