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?
Asked
Active
Viewed 4,393 times
2
-
4this is **very bad practice** in terms of memory allocation. Please consider pre-allocating. – Shai May 22 '14 at 11:47
3 Answers
6
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.
4
You can just define an empty array like this:
A = [];
To "push" a column element:
A = [ A 42 ];
To "push" a row element:
A = [ A ; 42 ];

Paul R
- 208,748
- 37
- 389
- 560
4
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);

Community
- 1
- 1

Stewie Griffin
- 14,889
- 11
- 39
- 70