MATLAB: Logical indexing to find index of different number in vector

logical indexingvectors

I have a vector like [5 5 5 5 2 5], I would like to use logical indexing to find the index of the number (in this case 2) which is different from all others.

Best Answer

If you're certain that the array A consists of numel(A)-1 instances of one number and 1 instance of another number in some order:
A = [5 5 5 5 2 5];
n = numel(A)-1;
locVector = (A ~= A(1));
% You should probably add a comment here explaining this if statement
% I leave that as an exercise to the reader
if nnz(locVector) == n
locVector = ~locVector;
end
disp(locVector)