我想创建一个元胞数组,其中每一行都是一个字符串数组。这些行的长度不同。假设我将这些行存储为单元格本身,例如:
row1 = {'foo1', 'foo2', 'foo3'}
row2 = {'foo1', 'foo2', 'foo3', 'foo4'}
row3 = {'foo1', 'foo2'}
Run Code Online (Sandbox Code Playgroud)
如何将这些连接到一个单元格中?像这样的东西:
cell = row1
cell = [cell; row2]
cell = [cell; row3]
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误:
Error using vertcat. Dimensions of matrices being concatenated are not consistent.
Run Code Online (Sandbox Code Playgroud)
我想在循环中执行此操作,以便在每次交互时,将另一行添加到单元格中。
我怎样才能做到这一点?谢谢。
你不能使用
c = row1;
c = [cell; row2]
Run Code Online (Sandbox Code Playgroud)
因为两行中的列数不匹配。在元胞数组中,所有行的列数必须相同。出于同样的原因,你也不能使用它(它是等效的):
c = row1;
c(end+1,:) = row2
Run Code Online (Sandbox Code Playgroud)
如果您需要不同数量的“每行中的列”(或“锯齿状数组”),则需要两个级别:对行使用(第一级)单元格数组,并在每行中存储一个(第二级)单元格列的数组。例如:
c = {row1};
c = [c; {row2}]; %// or c(end+1) = {row2};
Run Code Online (Sandbox Code Playgroud)
现在c
是元胞数组的元胞数组:
c =
{1x3 cell}
{1x4 cell}
Run Code Online (Sandbox Code Playgroud)
您可以使用“链式”索引,如下所示:例如,c{2}{4}
给出字符串。'foo4'