Maybe your mean:
b = cat(2, [ 7;6;5;4;4;3;2;1;20;19;18;17;16;20;21;22;23], ...
[30;29;28;27;8;9;10;11;8;12;13;14;15;27;26;25;24]);
a = [20; 21; 22; 23];
[~, Result] = ismember(a, b(:, 1), 'legacy');
if ~any(Result)
[~, Result] = ismember(a, b(:, 2), 'legacy');
end
But I detest the 'legacy' flag. Even the documentation is vague about its meaning:
preserves the behavior of the ismember function from R2012b and prior
releases using any of the input arguments in previous syntaxes.
Without knowing what the prior (to what?!) releases did, this description is useless. There is no way to let unique search for 'stable' and 'last' at the same time.
Therefore I'd prefer:
b = cat(2, [ 7;6;5;4;4;3;2;1;20;19;18;17;16;20;21;22;23], ...
[30;29;28;27;8;9;10;11;8;12;13;14;15;27;26;25;24]);
[B1, Index1] = uniqueStableLast(b);
[B2, Index2] = uniqueStableLast(b);
[~, loc] = ismember(a, B1);
if any(loc)
Result = Index1(loc);
else
[~, loc] = ismember(a, B2);
Result = Index2(loc);
end
With:
function [B, AI, BI] = uniqueStableLast(A)
nA = numel(A);
if nA
[As, SV] = sort(A(:), 'descend');
As = As(nA:-1:1);
SV = SV(nA:-1:1);
if nargout == 1
UV(SV) = [false; diff(As) ~= 0];
B = A(UV);
else
UV = [false; diff(As)] ~= 0];
UVs(SV) = UV;
AI = find(UVs);
B = A(UVs);
if nargout == 3
v = zeros(1, nA);
v(AI) = 1:length(AI);
vs = v(SV);
vf = vs(vs ~= 0);
BI(SV) = vf(cumsum(UV));
end
end
else
B = [];
AI = [];
BI = [];
end
By the way: This is even faster than Matlab's unique('stable').
Best Answer