Search code examples
arraysmatlabindexingunique

Find specific union of two arrays with different length in MATLAB


I have a coding problem in Matlab, where I try to find a solution without too many for-loops slowing down the process.

I have an array that looks like:

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

Another that looks like:

B = [0,1,0,1,1]

In B there's always as many elements as their are unique elements in A and the value corresponds to the unique element in A, in other words:

length(unique(A)) = length(B)

I want to compute a result that tells me the index where B == 0 (C) and B == 1 (D) in A.

C = [1,2,3,9,10,11,12]
D = [4,5,6,7,8,13,14,15,16,17,18]

Solution

  • Here is my approach: first "calculate" Au as unique vector of A. In the next step use B for logical indexing of Au: Au( logical(B) ) - this gets the values to be found in A. Then check which values are member of this group and then get their indices. There may be a simpler approach though.

    A = [1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,4,5]
    Au = unique( A );
    B = [0,1,0,1,1];
    
    C = find( ismember( A, Au(  logical(B) ) ) )
    D = find( ismember( A, Au( ~logical(B) ) ) )