Matlab: adding row to cell

12,069

Solution 1

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.

Solution 2

The best way would be like so:

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

cell = row1;
cell = {cell{:}, row2{:}};
cell = {cell{:}, row3{:}}

Divakar's answer does not produce a cell as output.

Solution 3

Code

row=[];
for k=1:3

    %%// Use this if you want MATLAB to go through row1, row2, row3, etc. and concatenate
    evalc(strcat('cell1 = row',num2str(k))); 

    %cell1 = row1; %%// Use this if you want to manually insert rows as row1, row2, row3, etc.
    row=[row ; cell1(:)];

end
row = row'; %%// Final output is a row array

Output

row = 

    'foo1'    'foo2'    'foo3'    'foo1'    'foo2'    'foo3'    'foo4'    'foo1'    'foo2'
Share:
12,069
Karnivaurus
Author by

Karnivaurus

Updated on June 26, 2022

Comments

  • Karnivaurus
    Karnivaurus almost 2 years

    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.

  • ja.abell
    ja.abell about 10 years
    BTW. This was tested in Octave 3.6.4
  • Karnivaurus
    Karnivaurus about 10 years
    Thanks. Suppose I now want to find the number of strings in row1 or row2 - what is the syntax for that?
  • Luis Mendo
    Luis Mendo about 10 years
    @Karnivaurus numel(c{1}) or numel(c{2})