1
A = [5    10    16    22    28    32    36    44    49    56]
B = [2     1     1     2     1     2     1     2     2     2]

How to get this?

C1 = [10 16 28 36]
C2 = [5 22 32 44 49 56]

C1 needs to get the values from A, only in the positions in which B is 1 C2 needs to get the values from A, only in the positions in which B is 2

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147

2 Answers2

3

You can do this this way :

C1 = A(B==1);
C2 = A(B==2);

B==1 gives a logical array : [ 0 1 1 0 1 0 1 0 0 0 ].

A(logicalArray) returns elements for which the value of logicalArray is true (it is termed logical indexing). A and logicalArray must of course have the same size.

It is probably the fastest way of doing this operation in matlab.

For more information on indexing, see matlab documentation.

beesleep
  • 1,322
  • 8
  • 18
2

To achieve this with an arbitrary number of groups (not just two as in your example), use accumarray with an a anoynmous function to collect the values in each group into a cell. To preserve order, B needs to be sorted first (and the same order needs to be applied to A):

[B_sort, ind_sort] = sort(B);
C = accumarray(B_sort.', A(ind_sort).', [], @(x){x.'});

This gives the result in a cell array:

>> C{1}
ans =
    10    16    28    36
>> C{2}
ans =
     5    22    32    44    49    56
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147