pre-allocation of array used like a FIFO stack
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
am writing a code for image segmentation based on region growing and am using an array as a FIFO stack , i don't know how to pre-allocate it and still can use it like a stack, am using it inside a loop so it's changinig size in every iteration and that makes my code run slow:
that's an example : ( array in question is "points_reg")
points_reg=[points_reg;(i+vx(k)) (j+vy(k)) ];
point=[points_reg(1,1) points_reg(1,2)];
points_reg(1,:)=[];
4 commentaires
Uday Pradhan
le 15 Nov 2020
So, I think at any iteration of the loop, after the horizontal concatenation, points_reg will be a 2 - by - 2 matrix. If this is the case, then we can simply do:
%initialise outside loop
points_reg = zeros(2,2);
%inside loop :
points_reg(2,:)=[(i+vx(k)) (j+vy(k))]; %add new entry in the second row
point=[points_reg(1,1) points_reg(1,2)]; %store the previous entry in point, this will get overwritten each time
points_reg(1,:)= points_reg(2,:); %replace the old entry with new one which will be chosen as "points" variable in the next iteration
chabani mohammed ali
le 15 Nov 2020
Modifié(e) : chabani mohammed ali
le 15 Nov 2020
Réponses (1)
Ameer Hamza
le 15 Nov 2020
Modifié(e) : Ameer Hamza
le 15 Nov 2020
The easiest and quickest (in terms of coding time, not efficiency) solution will be to use a cell array. Unlike numeric arrays, cell array does not require elements to be saved contiguously in memory and therefore tolerate the dynamic growth. Use each element in the cell array to store a 1x2 array. For the code in your question, something like this
points_reg{end+1}=[(i+vx(k)) (j+vy(k))];
point=points_reg{1};
points_reg(1)=[];
Here is time comparison for dynamic growth of a cell array. You can see there is no significant difference
x = {};
tic
for i = 1:1000000
x{i} = rand(1,2);
end
t1 = toc
y = {};
tic
for i = 1:1000000
y{end+1} = rand(1,2);
end
t2 = toc
For a million element, the output are
t1 =
1.1684
t2 =
1.8703
This should be an acceptable level of overhead in most cases.
1 commentaire
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!