سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top