如何取消嵌套的单元格数组?

时间:2015-03-06 17:24:27

标签: arrays matlab conditional cell

您好我正在尝试创建一个看起来像这样的单元格数组。

'3/7/2014'  '209.167.128.156'   1037 
'3/13/2014' '204.205.57.137'    8
'3/18/2014' '209.167.128.156'   164
'3/27/2014' '216.178.43.209'    825

但问题是当我运行我的代码时,我得到一个看起来像这样的单元格

{1x3cell} {1x3 cell} {1x3 cell} {1x3 cell} {1x3 cell]

这是我的代码:

cell = {};
month = 'March';
[num text raw] = xlsread(sheet);
text(1,:)= [];
fanta = text(:,1);
[row col] = size(fanta);
a = 1;
for i = 1:row
    coke = fanta{i};
    [first rest] = strtok(coke, '/');
    if strcmp(first, '1') && strcmp(month, 'January')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '2') && strcmp(month, 'February')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '3') && strcmp(month, 'March')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '4') && strcmp(month, 'April')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '5') && strcmp(month, 'May')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '6') && strcmp(month, 'June')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '7') && strcmp(month, 'July')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '8') && strcmp(month, 'August')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '9') && strcmp(month, 'Sepetember')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '10') && strcmp(month, 'October')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '11') && strcmp(month, 'November')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '12') && strcmp(month, 'December')
        cell{i} = raw((a+i), :);
    end
end
cell = cell(~cellfun('isempty', cell))

我做错了什么,我该如何解决? 谢谢。

3 个答案:

答案 0 :(得分:1)

要折叠单元格数组,您可以尝试

  C = cell2mat(C); % <-- using cell as a var name is bad practice!

给它一个旋转,看它是否有效。例如(这是八度音,但应该在matlab中工作):

C =
{
  [1,1] =
  {
    [1,1] = 3/7/2014
    [1,2] = 209.167.128.156
    [1,3] =  1037
  }
  [2,1] =
  {
    [1,1] = 3/13/2014
    [1,2] = 204.205.57.137
    [1,3] =  8
  }
  [3,1] =
  {
    [1,1] = 3/18/2014
    [1,2] = 209.167.128.156
    [1,3] =  164
  }
  [4,1] =
  {
    [1,1] = 3/27/2014
    [1,2] = 216.178.43.209
    [1,3] =  825
  }
}

cell2mat(C)
ans =
{
  [1,1] = 3/7/2014
  [2,1] = 3/13/2014
  [3,1] = 3/18/2014
  [4,1] = 3/27/2014
  [1,2] = 209.167.128.156
  [2,2] = 204.205.57.137
  [3,2] = 209.167.128.156
  [4,2] = 216.178.43.209
  [1,3] =  1037
  [2,3] =  8
  [3,3] =  164
  [4,3] =  825
}

答案 1 :(得分:1)

首先,你应该从不调用变量cell,因为它是内置Matlab函数的名称。这很糟糕,你应该受到惩罚: - )

我们假设您已将所有cell替换为C。然后,您应该首先通过

定义C
C = cell(0,3);

并替换所有

C{i} = ...

通过

C(i,:) = ...

最后一点:最后一列将由字符串而非数字组成。如果您真的想在此列中包含数字,则可以考虑在代码中的某处使用函数str2double

最佳,

答案 2 :(得分:0)

似乎没有任何错误,如果你正在使用单元格,你基本上是在创建一个数组数组。如果您访问cell{i},它将返回一个包含3个项目的向量,这些项目是您显示的行。如前所述,您可以使用矩阵,但矩阵无法处理不同的数据类型(在您的情况下为字符串和整数),因此我将继续使用单元格。 而且,您可以创建多维。

所以,就像Crazy Rat所说的那样,我会替换

cell{i}

通过

cell{i,:}

是的,不要按小区打电话。