本文介绍了MatLab(或任何其他语言)转换矩阵或csv以将第二列的值放到同一行(如果第一列的值相同)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有

1             1
1             3
1             9
2             4
2             7

我想将其转换为

1             1           3           9
2             4           7           3

(3,4)元素应该为空.

The (3,4) element should be empty.

Matlab可以使用for和if来做到这一点,但是要花费大量时间处理海量数据,因此我需要一个更优雅,更出色的想法.

I can do it by Matlab using for and if but it takes too much time for huge data, so I need a more elegant and brilliant idea.

我更喜欢Matlab,但其他语言也可以. (如果该语言可以解决我的问题,我可以将矩阵导出到csv或xlsx或txt并使用其他语言.)

I prefer Matlab but other languages are ok. (I can export the matrix to csv or xlsx or txt and use the other languages, if that language can solve my problem.)

提前谢谢!

[更新]

如果

      A = [2 3 234 ; 2 44 33; 2 12 22; 3 123 99; 3 1232 45; 5 224 57]

第一栏|第二栏|第三栏

2             3          234
2             44         33
2             12         22
3             123        99
3             1232       45
5             224        57

然后跑步

    [U ix iu] = unique(A(:,1) ); r= accumarray( iu, A(:,2:3), [], @(x) {x'} )

将显示错误

    Error using accumarray
    Second input VAL must be a vector with one element for each row in SUBS, or a
    scalar.

我想做

2         3        234       44        33        12        22
3         123      99        1232      45
5         224      57

我该怎么做?预先谢谢你!

How can I do this? Thank you in advance!

推荐答案

accumarray与自定义函数一起使用

Use accumarray with a custom function

>> r = accumarray( A(:,1), A(:,2), [], @(x) {x'} ); %//'
 r = 
  [1x3 double]
  [1x2 double]
>> r{1}
 ans =
  1     3     9
>> r{2}
 ans =
  4     7

更新:
将单元格r转换为矩阵B(可容纳注释中的其他请求):

Update:
Converting cell r to a matrix B (accomodating further requests in comments):

>> [U ix iu] = unique( A(:,1) ); % see EitantT's comment
>> r = accumarray( iu, A(:,2), [], @(x) {x'} ); 
>> n = cellfun( @numel, r ); % fund num elements in each row - need for max
>> mx = max(n);
>> pad = 555555; % padding value
>> r = cellfun( @(x) [x pad*ones(1,mx - numel(x))], r, 'uni', 0 );
>> B = vertcat( r{:} ); % construct B from padded rows of r

这篇关于MatLab(或任何其他语言)转换矩阵或csv以将第二列的值放到同一行(如果第一列的值相同)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 09:40