How to preallocate 2D array before for loop?
16 views (last 30 days)
Show older comments
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 Comments
Walter Roberson
on 11 Aug 2022
Edited: Walter Roberson
on 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.
Answers (1)
Jan
on 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.
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!