Indexing a column based on another column's values

I am trying to create an index that marks all cells in a clloumn that are equal to the values of a shorter collumn. ie if column a=(1,3,44,6,8,9,15) and column b=(3, 8) i would get an index c=(2,5). Anyone know how to do this?

 Accepted Answer

One approach is to use ismember (or ismembertol for floating-point numbers) —
a = [1,3,44,6,8,9,15];
b = [3, 8];
c = find(ismember(a,b))
c = 1×2
2 5
.

4 Comments

What could I do if I was trying to find the values in a closest to the values in b? The numbers that I am working with have a lot of decimal places so I'm not sure if there would be an exact match. Is indexing even possible?
Use the ismembertol function for floating-point numbers. It has a slightly different syntax (for example replacing 'rows' with 'ByRows'), however it behaves similarly and produces similar results. It returns a logical vector for the first output, so the find call is necessary to get numeric (as opposed to logical) results from it.
See the documentation for a full explanation of all the options and outputs the function has.
.
As always, my pleasure!
.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!