The values โ€‹โ€‹of groups in different rows at the index of the first column

This question is the result of MatLab (or any other language) to convert a matrix or csv to put the values โ€‹โ€‹of the second column in one row, if the value of the 1st column is the same?

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 run

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

will show me a mistake

  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 pillar | 5th col | 6th column | 7th col

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

I know how to do this using for and if, but it spends too much time on big data.

How can i do this?

Thank you in advance!

+4
source share
1 answer

You are not using accumarray in the solution provided to your previous question. The first parameter iu is the index vector, and the second parameter should be a vector of values โ€‹โ€‹of the same length. Here you specify the matrix as the second parameter, which actually has twice as many values โ€‹โ€‹as the indices in iu .

What you need to do to make it work is to create an index vector for both the second column and the third column (they are the same index, and not by chance!) And specify the corresponding column vector of values, like this:

 [U, ix, iu] = unique(A(:,1)); vals = reshape(A(:, 2:end).', [], 1); %'// Columnize values subs = reshape(iu(:, ones(size(A, 2) - 1, 1)).', [], 1); %'// Replicate indices r = accumarray(subs, vals, [], @(x){x'}); 

This solution is generalized to any number of columns that you want to pass to accumarray .

+2
source

Source: https://habr.com/ru/post/1489472/


All Articles