foozhan
foozhan

Reputation: 85

How to declare an array without size in MATLAB?

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?

Upvotes: 2

Views: 4965

Answers (3)

Stewie Griffin
Stewie Griffin

Reputation: 14939

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

Upvotes: 4

Shai
Shai

Reputation: 114786

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.

Upvotes: 6

Paul R
Paul R

Reputation: 212949

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

Upvotes: 4

Related Questions