2

Is there any built in Matlab function that can compare arrays in the following manner?

function comparison = elementcompare(array1,array2)

comparison=logical(true);
for i=1:length(array1)
    if ~any(array1(i)==array2)
        comparison=logical(false);
    end
end

This comparison, which returns true if every element of array1 can be found in array2, seems pretty basic but I was not able to find it.

Thanks!

1 Answer 1

5

The most straightforward way is to use ismember:

comparison = all(ismember(array1(:), array2(:)));

It can also be done with setdiff:

comparison = isempty(setdiff(array1(:), array2(:)));

As usual, bsxfun can do the job:

comparison = all(any(bsxfun(@eq, array1(:).', array2(:))));

Or even unique:

comparison = numel(unique([array1(:); array2(:)]))==numel(unique(array2(:)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.