I wan to declare an array in MATLAB without specifying the size, rather like std::vector in C++, and then I want to "push" elements to the array. How can I declare this array and push to it?
-
4this is very bad practice in terms of memory allocation. Please consider pre-allocating.Shai– Shai2014-05-22 11:47:41 +00:00Commented May 22, 2014 at 11:47
3 Answers
Altough the answer of Paul R is correct, it is a very bad practice to let an array grow in Matlab without pre-allocation. Note that even std::vector has the option to reserve() memory to avoid repeated re-allocations of memory.
You might want to consider pre-allocating a certain amount of memeory and then resize to fit the actual needed size.
You can read more on pre-allocation here.
Comments
As Shai pointed out, pushing elements onto a vector is not a good approach in MATLAB. I'm assuming you're doing this in a loop. In that case, this would be better approach:
A = NaN(max_row, 1);
it = 0;
while condition
it = it + 1;
A(it) = value;
end
A = A(1:it);
If you don't know the maximum dimension, you may try something like this:
stack_size = 100;
A = NaN(stack_size,1);
it = 0;
while some_condition
it = it + 1;
if mod(it, stack_size) == 0
A = [A; NaN(stack_size,1)];
end
A(it) = value;
end
A = A(1:it);