ISMEMBER() modified result desired
Show older comments
[lia,locb]=ismember(A,B);
returns the first/last matching location in B of the elements in A that occur in B depending on which optional parameters one chooses. That's fine for many cases, but...
If it is desired to do a 1:1 matching of elements in A to their corresponding mates in B, a modified behavior would be a desirable option if there are repeated elements -- locB could return the next match after the previous for those elements that may not be unique in either array.
This can be done in a loop, of course, by making a search for each element in A in turn, either keeping an indexing variable as to last location for each element previously located or, conversely, marking the location in B with a missing value or somesuch.
That's the problem, the question is --
Is there some function which already does this that I'm not aware of/can't find or a "more cleverer" way to make the match?
5 Comments
dpb
on 19 Jan 2019
Rik
on 20 Jan 2019
Maybe the second output of sort could help out here. It would even solve the tolerance thing.
If I'm not understanding you correctly, could you post a small example?
dpb
on 21 Jan 2019
Jan
on 21 Jan 2019
What about a small example?
A = [1, 2, 3, 1, 2, 3];
B = [2, 2, 2, 3, 3];
Is the wanted output this:
lia = [0, 1, 1, 0, 1, 1] % as logical
locb = [0, 1, 4, 0, 2, 5]
% ^ ^ would be 1 and 4 for standard ISMEMBER
dpb
on 21 Jan 2019
Answers (2)
Do you mean something like this:
function [lia, locb] = ismemberNext(A, B)
lia = false(size(A));
locb = zeros(size(A));
for iA = 1:numel(A)
match = (A(iA) == B);
if any(match)
lia(iA) = true;
index = find(match, 1);
locb(iA) = index;
B(index) = NaN; % Mask first match for following calls
end
end
end
Guillaume
on 21 Jan 2019
Maybe I misunderstood the problem, but ismembertol already has the option to return all matching indices in B:
[found, where] = ismembertol(A, B, 'OutputAllIndices', true)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!