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?

前端 未结 1 1211
[愿得一人]
[愿得一人] 2021-01-29 00:40

So for example I have

1st column | 2nd column

1             1
1             3
1             9
2             4
2             7

I wan

相关标签:
1条回答
  • 2021-01-29 00:47

    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
    
    0 讨论(0)
提交回复
热议问题