0

I have unknown vector which are produced by a loop. Every time one is created, I want to add it to a matrix.

For example, let's say I have my variable containing them being p.

On first turn I have vector [ 1 2 3 ]

then I want p to be

[ 1 2 3 ]

then I produce vector [ 4 4 5 6 6 ]

Then I want be to contains

[ 1 2 3 ]
[ 4 4 5 6 6 ]

So I can do something like p(1) to access first vector, and p(2) for second.

What is the closest representation I could use?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Cher
  • 2,789
  • 10
  • 37
  • 64
  • You need a [cell array](http://www.mathworks.com/help/matlab/cell-arrays.html), not a matrix. – EBH Sep 25 '16 at 18:41

1 Answers1

3

A matrix needs to be rectangular, since MATLAB doesn't like Swiss cheese. The closest you can get to that representation is cells:

p{1} = [1 2 3];
p{2} = [ 4 4 5 6 6 ];

Cells are a tad more cumbersome to work with than matrices, due to their allowance of irregular shaped matrices and even non-uniform datatypes across their elements, but at least they do what you want.

The other option would be zero padding I'd say:

p = [1 2 3];
newvec = [ 4 4 5 6 6 ];
if length(newvec)>length(p)
    p = [p zeros(size(newvec)-size(p))];
    else
        newvec = [newvec zeros(size(p)-size(newvec))];
end
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • And you should also preallocate `p` with the number of cells to be filed. – EBH Sep 25 '16 at 18:43
  • I know, I just wanted to make this clear for the OP, in case he did not pay attention for that. – EBH Sep 25 '16 at 18:51