Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: adding row to cell

I want to create a cell array, where each row is an array of strings. The rows are of different lengths. Suppose that I have these rows stored as cells themselves, e.g.:

row1 = {'foo1', 'foo2', 'foo3'}
row2 = {'foo1', 'foo2', 'foo3', 'foo4'}
row3 = {'foo1', 'foo2'}

How do I concatenate these into one cell? Something like this:

cell = row1
cell = [cell; row2]
cell = [cell; row3]

But this gives me an error:

Error using vertcat. Dimensions of matrices being concatenated are not consistent.

I want to do this in a loop, such that on each interation, another row is added to the cell.

How can I do this? Thanks.

like image 621
Karnivaurus Avatar asked Jan 22 '26 12:01

Karnivaurus


1 Answers

You can't use

c = row1;
c = [cell; row2]

because the numbers of columns in the two rows don't match. In a cell array, the number of columns has to be the same for all rows. For the same reason, you can't use this either (it would be equivalent):

c = row1;
c(end+1,:) = row2

If you need different numbers of "columns in each row" (or a "jagged array") you need two levels: use a (first-level) cell array for the rows, and in each row store a (second-level) cell array for the columns. For example:

c = {row1};
c = [c; {row2}]; %// or c(end+1) = {row2};

Now c is a cell array of cell arrays:

c = 
    {1x3 cell}
    {1x4 cell}

and you can use "chained" indexing like this: c{2}{4} gives the string 'foo4', for example.

like image 189
Luis Mendo Avatar answered Jan 26 '26 01:01

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!