Problem 55210. Determine whether one vector is a subset of another

While bumbling through a pair of problems in the Number Theory group, I wrote code to determine whether a vector is a subset of another vector. I thought the function ismember might work, but it does not account for repeated elements in a way necessary to check for a subset.
For example, if a = [1 2 1 3 3] and b = [3 2 1 1 5 4], [lia, locb] = ismember(a,b) returns lia = [1 1 1 1 1] and locb = [3 2 3 1 1]. In other words, the first vector indicates whether each element in a appears in b at least once, and the second vector gives the index of the first occurrence of the element of a in b. The command all(lia) would return true, but a is not a subset of b.
Write a function to determine whether one vector is a subset of another. The function will return two arguments: a logical tf that indicates whether a is a subset of b and a vector locb that gives unique indices into b where the elements of a occur. For repeating elements, the indices should increase, and for elements of a not in b, return zero. For the example of a and b above, tf is false and locb = [3 2 4 1 0].
I could not find either a MATLAB function or Cody problem that addresses this task, but I would not be too surprised if there is an elegant or built-in solution that I missed.

Solution Stats

38.71% Correct | 61.29% Incorrect
Last Solution submitted on May 18, 2023

Problem Comments

Solution Comments

Show comments

Problem Recent Solvers10

Suggested Problems

More from this Author244

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!