MATLAB Answers

problems with matrix splitting

2 views (last 30 days)
Hello everyone, I want to split the matrix in such a way that when elements of 1st column are equal, the correspnding elements can be splitted into another matrix. For example, i have the following matrix.
A = [ 1 2; 1 3; 1 4; 2 1; 2 4].
i want to get the following 2 matrices as the resulting matrices.
a1 = [2;3;4] and a2= [1;4]
i have just started learning the looping in MATLAB, your coperation will be highly appreciated.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 22 Aug 2016
Edited: Azzi Abdelmalek on 22 Aug 2016
A = [ 1 2; 1 3; 1 4; 2 1; 2 4]
Azzi Abdelmalek
Azzi Abdelmalek on 22 Aug 2016
I mean your question is not clear, why do you need a for loop, when accumarray can do the job?

Sign in to comment.

More Answers (1)

Stephen Cobeldick
Stephen Cobeldick on 22 Aug 2016
Use accumarray:
out = accumarray(A(:,1),A(:,2),[],@(v){v})
  1 Comment
pradeep kumar
pradeep kumar on 22 Aug 2016
Thanks Stephen. That was a great help indeed. but , please note that in my actual problem A is a huge matrix of order (100 X 2). Is there anyway to use the accumarray inside a loop ? kindly help me.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!