Carven
Carven

Reputation: 15638

How can I create an expandable array in Matlab?

How can I create an expandable array in Matlab?

I can create a fixed length array with myArray = zeros(1,2); But I need one that I can keep pushing new elements onto the list. How should I run the command to do this?

Upvotes: 1

Views: 599

Answers (2)

gevang
gevang

Reputation: 5014

MATLAB arrays/matrices are dynamic by construction. myArray = []; will create a dynamic array. From there on you can assign and extend (by appending or concatenation). Some examples:

myArray = zeros(1,2);
myArray(:,end+1) = 1;
myArray(end+1,:) = ones(1,3);
myArray = [myArray 2*myArray];

An interesting analysis on the efficiency of different array resizing options in MATLAB, if pre-allocation is not an option, can be found here: Array resizing performance.

You can also check this SO post: Matrix of unknown length in MATLAB.

Upvotes: 3

Zero
Zero

Reputation: 76917

You can assign the value to the item.

myArray = zeros(1,2);
myArray(1,3)=3; % item assignment

myArray will be of dimension (1,3) now.

Upvotes: 3

Related Questions