3

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.

1
  • Those are row arrays, so how would you like your output to be? Row or column array? Commented Mar 17, 2014 at 19:41

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Suppose I now want to find the number of strings in row1 or row2 - what is the syntax for that?
@Karnivaurus numel(c{1}) or numel(c{2})
1

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.

1 Comment

BTW. This was tested in Octave 3.6.4
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.