0
votes

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
Can you elaborate on the logic between the conversions, please? Your input has only one 3, while the output has two. Which element is supposed to end up where?Schorsch
Can you show us your current code? I'm not sure if you can do it in Matlab without a for loop, but we may be able to help improve what you have.David K
@Schorsch Shai made a big step. But I want to make the output as a one matrix. How can I merge r{1} and r{2} to a matrix B? I tried B = [r{1} ; r{2}] but failed. Maybe filling the empty cell as some number which is very very unlikely to exist in other cells such as "55555555555" will work? Then after exporting to xlsx I can mass-replace using MS excel. How can I fill those empty cells as 555555555 and make the r{1}, r{2}... as one big matrix?user1849133

1 Answers

2
votes

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