1

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?

Carven
  • 14,988
  • 29
  • 118
  • 161

2 Answers2

3

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.

Zero
  • 74,117
  • 18
  • 147
  • 154
  • Will the values in myArray remain when I reassign its dimension? – Carven Mar 24 '13 at 20:46
  • 1
    Yes. Basically, you're expanding the array by assigning a value at an item location. You can check out basics http://www.mathworks.in/help/matlab/math/matrix-indexing.html – Zero Mar 24 '13 at 20:49
3

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.

Community
  • 1
  • 1
gevang
  • 4,994
  • 25
  • 33