How to preallocate 2D array before for loop?

11 Ansichten (letzte 30 Tage)
Blondi
Blondi am 11 Aug. 2022
Beantwortet: Jan am 11 Aug. 2022
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 Kommentare
Walter Roberson
Walter Roberson am 11 Aug. 2022
Bearbeitet: Walter Roberson am 11 Aug. 2022
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 am 11 Aug. 2022
length(occWorld(:,1)) is less efficient than size(occWorld,1).

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Jan
Jan am 11 Aug. 2022
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.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by