How to preallocate 2D array before for loop?

16 visualizzazioni (ultimi 30 giorni)
Blondi
Blondi il 11 Ago 2022
Risposto: Jan il 11 Ago 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 Commenti
Walter Roberson
Walter Roberson il 11 Ago 2022
Modificato: Walter Roberson il 11 Ago 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 il 11 Ago 2022
length(occWorld(:,1)) is less efficient than size(occWorld,1).

Accedi per commentare.

Risposte (1)

Jan
Jan il 11 Ago 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.

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by