how to compare two 1d arrays and output the indices where array 1 has the same scalar value as array 2

Viewed 37

I'm trying to figure out how to take two 1d arrays, put it in a function so that every number in array 1 is compared to every number in array 2, and then the element numbers of the duplicate numbers found is displayed with respect to array 1

for example array 1 = [12,16,36,72,82] array 2= [16,53,72,12,40,71]

and the output would be elements= 1 2 4

I'm new to Matlab so I don't currently have all the skills to make This work I'm trying to figure it out but I don't know what exactly to do. it won't let me post the code because it doesn't make sense. im not sure how to post is on her otherwise.

1 Answers

[Edit2]

Best approach

The unreliable approach below works for the example given by the OP, with the restriction discussed below. The best approach is using MATLAB's ismember and find functions:

array1 = [12,16,36,72,82]; 
array2 = [16,53,72,12,40,71];

idc = find( ismember(array1, array2 ) )
  • ismember(array1, array2) returns a logical array indicating which elements of array1 are contained in array2.
  • find(...) converts the logical array to indices.

[Edit1]

Alternative approach

An approach without ismember would be:

array1 = [12,16,36,72,82]; 
array2 = [16,53,72,12,40,71];

findFcn = @(X) find( array1(:) == X )';
idcs = arrayfun(findFcn, array2(:), 'UniformOutput', false );
idcs = unique([idcs{:}])

Explanation:

  • findFun(X) gives the index of the value of X in array1.

  • findFun(X) is called by arrayfun with X being equal to each element of array2 and arrayfun stores the return values of the calls to the cell array idcs.

  • Finally, idcs = unique([idcs{:}]); converts the cell array idc to a double array and removes repetitions.

[First answer]

Unreliable approach

You can use the intersect function:

array1 = [12,16,36,72,82]; 
array2 = [16,53,72,12,40,71];
[ ~, x1 ] =  intersect( array1, array2 );

~ means that the first return value, which would be the intersection of array1 and array2, is discarded. x1 is then equal to the indices that the intersection's values have in array1.

If you also want to have the indices in array2 you could do

[ ~, x1, x2 ] =  intersect( array1, array2 );

to store them in x2.

Note: x1 and x2 only contain the indices of the first occurrence in array1 and array2, respectively.

Related