pre-allocation of array used like a FIFO stack
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Uday Pradhan
2020 年 11 月 15 日
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
回答 (1 件)
Ameer Hamza
2020 年 11 月 15 日
編集済み: Ameer Hamza
2020 年 11 月 15 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!