How to preallocate 2D array before for loop?

조회 수: 11 (최근 30일)
Blondi
Blondi 2022년 8월 11일
답변: Jan 2022년 8월 11일
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