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?

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

So for example I have

1st column | 2nd column

1             1 1             3 1             9 2             4 2             7 

I want to convert it to

1st column | 2nd column | 3rd column | 4th column

1             1           3           9 2             4           7           3 

The (3,4) element should be empty.

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.

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.)

Thank you in advance!

[Updates]

If

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

1st column | 2nd column | 3rd column

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

then running

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

will show me the error

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

I want to make

1st col | 2nd col | 3rd col | 4th col | 5th col | 6th col| 7th col

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

How can I do this? Thank you in advance!

回答1:

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 

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!