【问题标题】:Cell array (different size cells) to matrix单元阵列(不同大小的单元)到矩阵
【发布时间】:2016-04-19 20:31:26
【问题描述】:

我正在尝试将单元格内容不同大小的单元格数组转换为矩阵。我尝试了以下代码(来自previous question):

tcell = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1], []};  %# Sample array
maxSize = max(cellfun(@numel,tcell));    %# Get the maximum vector size
fcn = @(x) [x nan(1,maxSize-numel(x))];  %# Create an anonymous function
rmat = cellfun(fcn,tcell,'UniformOutput',false);  %# Pad each cell with NaNs
rmat = vertcat(rmat{:})                  %# Vertically concatenate cells

我收到以下错误代码:

被连接的矩阵的维度不一致。

@(x)[x,nan(1,maxSize-numel(x))] 中的错误

我认为我的单元格数组与测试示例的内容不同(请参阅告诉):在 MATLAB 中查看时我的单元格数组(1x31 单元格)的内容是

30x1 cell    40x1 cell    37x1 cell 

我必须先对单元格数组进行另一次转换吗?如何将单元格数组转换为 tcell 的形式?

我已经搜索了一段时间,但我还不熟悉所有术语。解决方案可能很简单,但我还没有看到它的知识。欢迎所有输入!

【问题讨论】:

  • 你想如何连接它们?预期输出的大小是多少?
  • 您必须在单元格中转置您的内容。这段代码仅适用于线向量。
  • @marsei 有解决方案:您要么必须转置单元格,要么使用列向量输出 (@(x)[x; nan(...)]) 编写匿名函数。
  • vertcat(tcell{:}) 不起作用吗?
  • 很好,您可以发表您的评论作为答案并接受它!

标签: matlab matrix cell-array


【解决方案1】:

实际上,您的原始代码几乎是完美的,但对于线向量。对于单元格中的列向量,您错过了分号。

    maxSize = max(cellfun(@numel,tcell));    %# Get the maximum vector size
    fcn = @(x) [x ; nan(1,maxSize-numel(x))];  %# semicolon here                
    rmat = cellfun(fcn,tcell,'UniformOutput',false);  %# Pad each cell with NaNs

【讨论】:

    【解决方案2】:

    感谢评论员的投入,我找到了以下答案:

    A = cellfun(@transpose,Arad,'UniformOutput',false); %transpose the cell array
    maxSize = max(cellfun(@numel,A)); %# Get the maximum vector size 
    fcn = @(x) [x nan(1,maxSize-numel(x))]; %# Create an anonymous function rmat = cellfun(fcn,A,'UniformOutput',false); %# Pad each cell with NaNs 
    rmat = horzcat(rmat{:}) ; % concatenate horizontally 
    rmat = horzcat(rmat{:}) ; % concatenate horizontally again 
    rmat = reshape(rmat,maxSize, []);% reshape to m(=maxsize)x n(determined by total number of elements/number of rows(maxsize)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多