Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

matlab - Group values in different rows by their first-column index

This question is an outgrowth of 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?

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

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

How can I do this?

Thank you in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're misusing accumarray in the solution provided to your previous question. The first parameter iu is the vector of indices and the second parameter should be a vector of values, of the same length. What you did here is specify a matrix as the second parameter, which in fact has twice more values than indices in iu.

What you need to do in order to make it work is create a vector of indices both for the second column and for the third column (they are the same indices, not coincidentally!) and specify a matching column vector of values, like so:

[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 for any number of columns that you want to pass to accumarray.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...