bzak
bzak

Reputation: 563

Extracting a cell from two matrix and a particular condtion

M = [1007  1007  4044  1007  4044  1007  5002;
      552   552   300   552   300   552   431;
     2010  2010  1113  2010  1113  2010  1100;
        7    12    25    15    12    30     2]  

N = [1007  4044  5002;
      552   300   431;
     2010  1113  1100;
      1.2     5  2.14;
      5.3   2.1  2.03]

N(1:3,:) = unique(M(1:3,:)','rows')'

my goal is to put all values of M(4,:) corresponding to N(1:3,i), i=1,2,3 in one vector of a cell A if abs(N(4,i)-N(5,i))>0.2*N(5,i)

A is a cell to build

For my example:

A = {[7 12 15 30],[25 12]}

[7 12 15 30] correspond to N(1:3,1)

[25 12] correspond to N(1:3,2)

2nd example:

M = [1007  1007  4044  1007  4044  1007  5002 5002 5002 622 622;
      552   552   300   552   300   552   431  431  431 124 124 ; 
     2010  2010  1113  2010  1113  2010  1100 1100 1100  88  88;
        7    12    25    15    12    30     2   10   55  32  12];

N = [1007 4044 5002 622;
      552  300  431 124;
     2010 1113 1100  88;
       -1    2   -3   4;
      1.5  1.9  2.9 4.1];

A = {[7 12 15 30],[2 10 55]}

Upvotes: 1

Views: 74

Answers (1)

Divakar
Divakar

Reputation: 221514

Something like this using the third output argument from unique -

%// Find unique IDs for each column
[~,~,idx] = unique(M(1:3,:)','rows')          %//'

%// Accumulate elements from the fourth row of M based on the IDs
A = accumarray(idx(:),M(4,:).',[],@(x) {x})   %//'

%// Use mask corresponding to abs(N(4,i)-N(5,i))>0.2*N(5,i) and
%// filter out some of the cells from the output
A = A(abs(N(4,:)-N(5,:))>0.2*N(5,:))

For the given input, we get -

>> celldisp(A)
A{1} =
    12
    30
    15
     7
A{2} =
    12
    25

If you are looking for 'Stable' output, you can use accumarrayStable instead from here, giving us -

>> celldisp(A)
A{1} =
     7
    12
    15
    30
A{2} =
    25
    12

Upvotes: 2

Related Questions