【问题标题】:Extract data from cell array and include index of cell for identification从单元格数组中提取数据并包含单元格索引以进行识别
【发布时间】:2015-02-24 10:39:14
【问题描述】:

我有一个69x1cell 数组。每行包含 3 列 double 但行数可变。

每一行都有,例如;

4x3 双 13x3 双 ...等等。

我使用以下方法将元胞数组中的所有数据提取到一个矩阵中;

result = vertcat(data{:})

我想做的是根据从数据单元数组中提取的单元格来给他们一个标识。例如,从数据单元格数组的第一行中提取的 4 行将在它们前面有 1...所以我会得到类似的东西;

1,x,y,z
1,x,y,z
1,x,y,z
1,x,y,z (as row 1 in data has 4 rows)
2,x,y,z
2,x,y,z (for the 13 rows)

【问题讨论】:

    标签: arrays matlab


    【解决方案1】:

    这是一种方式:

    data = { rand(2,3);
             rand(5,3) }
    
    %// create identity vector
    out1 = cell2mat(arrayfun(@(x) x.*ones(1,size(data{x},1)), 1:numel(data),'uni',0)).' %'
    %// convert data from cell to double matrix
    out2 = cell2mat(data)
    
    %// concatenate output
    out = [ out1 , out2 ]
    

    或直接

    out = cell2mat([arrayfun(@(x)x.*ones(1,size(data{x},1)).',1:numel(data),'uni',0).',data])
    

    或者更花哨、更便宜的(未经测试):

    %// create identity vector
    A(cumsum([1; cellfun(@(x) size(x,1),data)])) = 1
    
    %// concatenate output
    out = [cumsum(A(1:end-1)).' cell2mat(data)]
    

    给予:

    data = 
        [2x3 double]
        [5x3 double]
    
    
    out =
                1      0.88441     0.018613      0.43851
                1      0.72086      0.67478      0.43782
                2      0.11704      0.37569      0.51537
                2      0.81468      0.54655      0.65753
                2      0.32486      0.56192      0.95092
                2      0.24623      0.39582      0.72235
                2      0.34271      0.39813      0.40008
    

    【讨论】:

    • 完美! @thewatwewalk 我刚刚测试了你的“未经测试”的方法,它也很完美。
    • @user3644826 "untested" 评论是关于 "a bit less costly" 声明:)
    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 2015-04-21
    • 2014-05-20
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    相关资源
    最近更新 更多