2

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?

1
  • 4
    this is very bad practice in terms of memory allocation. Please consider pre-allocating. Commented May 22, 2014 at 11:47

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 ];

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.