Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create groups of sub-matrices according to one column

I would like to know how to create groups of matrices starting from a Matrix in Matlab.

I have this Matrix :

A= [  1     1     2
     1     2     3
     1     3     4
     2     1     3
     2     2     4
     2     3     5
     3     1     4
     3     2     5
     3     3     6]

Now I would like to create several new matrices in which the elements, of each new matrix, are the first two columns of each row in A that have the third column of A in common.

For this case will be :

Af1=[1 1] % elements in common '2' (third column of A)
Af2= [1 2
      2 1] % elements in common '3' (third column of A)

and so on.

Thanks in advance

like image 643
ftrash Avatar asked Dec 08 '25 06:12

ftrash


2 Answers

Here's another approach:

B = sortrows(A, size(A,2)); %// sort rows acording to last column
gs = diff(find(diff([inf; B(:,3); inf])~=0)); %// sizes of groups determined by last col
result = mat2cell(B(:,1:end-1), gs); %// split according to those group sizes
like image 172
Luis Mendo Avatar answered Dec 11 '25 11:12

Luis Mendo


This is a job for accumarray:

[ofGroup,~,subs] = unique(A(:,3));
values  = accumarray(subs,1:size(A,1),[],@(x) {A(x,[1,2])});

out = [ofGroup values]

enter image description here

For accessing the result you could use the approach proposed by Divakar using deal. But I'd rather rethink and use the cell array out directly:

>> out{3,2}

ans =

     1     3
     2     2
     3     1
like image 38
Robert Seifert Avatar answered Dec 11 '25 10:12

Robert Seifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!