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
Problem Comments
Solution Comments
Show comments
Loading...
Problem Recent Solvers13
Suggested Problems
-
2522 Solvers
-
Square Digits Number Chain Terminal Value (Inspired by Project Euler Problem 92)
253 Solvers
-
The Answer to Life, the Universe, and Everything
576 Solvers
-
Area of an equilateral triangle
6778 Solvers
-
Write c^3 as sum of two squares a^2+b^2
327 Solvers
More from this Author321
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!