【问题标题】:MatLab to convert a matrix with respect to 1st colMatLab 相对于第 1 列转换矩阵
【发布时间】:2013-07-16 02:53:09
【问题描述】:

这个问题是MatLab (or any other language) to convert a matrix or a csv to put 2nd column values to the same row if 1st column value is the same?Group values in different rows by their first-column index 的产物

如果

      A = [2 3 234 ; 2 44 99999; 2 99999 99999; 3 123 99; 3 1232 45; 5 99999 57]

1st column |  2nd column | 3rd column
--------------------------------------
2             3          234
2             44         99999
2             99999      99999
3             123        99
3             1232       45
5             99999        57

我想做

1st col |  2nd col | 3rd col | 4th col | 5th col | 6th col| 7th col
--------------------------------------------------------------------
2         3        234       44       
3         123      99        1232      45
5         57

也就是说,对于 A 的第 1 列中的每个数字,我想输入除“99999”之外的数字

如果我们忽略“99999除外”部分,我们可以编码为Group values in different rows by their first-column index

[U, ix, iu] = unique(A(:,1));
vals = reshape(A(:, 2:end).', [], 1);                    %'// Columnize values
subs = reshape(iu(:, ones(size(A, 2) - 1, 1)).', [], 1); %'// Replicate indices
r = accumarray(subs, vals, [], @(x){x'});

但显然这段代码不会忽略 99999。

我想有两种方法

1. first make r, and then remove 99999
2. remove 99999 first, and then make r

不管怎样,我只想要更快的。

提前谢谢你!

【问题讨论】:

    标签: matlab


    【解决方案1】:

    我认为选项 1 更好,即先制作 r,然后删除 99999。有了 r,你可以删除 99999,如下所示:

    r2 = {}; % new cell array without 99999
    
    for i = 1:numel(r)    
        rCell = r{i};
        whereIs9999 = rCell == 99999; 
        rCell(whereIs9999) = []; % remove 99999
        r2{i} = rCell;
    end
    

    或者更花哨的方式:

    r2= cellfun(@(c) {c(c~=99999)}, r);
    

    【讨论】:

    • 您没有在循环之前预分配,因此这可能会对大型元胞数组产生性能问题。相反,您宁愿就地删除值:for k = 1:numel(r), r{k}(r{k} ~= 99999) = []; end。另外,您忘记将'UniformOutput', false 放入cellfun...
    • @EitanT UniformOutput 在这种情况下不需要,因为我返回单元格并且输出中的单元格数量与输入中的单元格数量相同。但预分配总是好的性能是一个因素。
    • 我认为 'UniformOutput', false 在这里是必需的,因为您返回的是元胞数组而不是矩阵。
    • @EtianT 在这种情况下,匿名函数的每个输出都是一个元胞数组。在这种情况下不需要flase
    • 啊,我没看到匿名函数里的花括号。
    猜你喜欢
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多