[英]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?
So for example I have 所以我举个例子
1 1
1 3
1 9
2 4
2 7
I want to convert it to 我想把它转换成
1 1 3 9
2 4 7 3
The (3,4) element should be empty. (3,4)元素应为空。
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使用for和if来实现它,但是它需要太多时间来处理大量数据,所以我需要一个更优雅和更棒的想法。
I prefer Matlab but other languages are ok. 我更喜欢Matlab,但其他语言还可以。 (I can export the matrix to csv or xlsx or txt and use the other languages, if that language can solve my problem.)
(我可以将矩阵导出到csv或xlsx或txt并使用其他语言,如果该语言可以解决我的问题。)
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]
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 我要实现
2 3 234 44 33 12 22
3 123 99 1232 45
5 224 57
How can I do this? 我怎样才能做到这一点? Thank you in advance!
先感谢您!
Use accumarray
with a custom function 使用自定义函数的
accumarray
>> 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): 将单元格
r
转换为矩阵B
(在评论中容纳更多请求):
>> [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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.