What is the most efficient way to create a logical index from values in a matrix?

4 views (last 30 days)
I have a vector of values that I want to be 1s in a logical vector of a given size. Is there any way to do this in one line of code?
Here is how I am currently doing it:
%given information
given_size = 15;
chosen_values = [2 4 5 10];
%get index - can this be done in one line?
chosen_cells_index = false(1,given_size);
chosen_cells_index(chosen_values) = 1;

Accepted Answer

Star Strider
Star Strider on 15 Dec 2018
I use three lines here for the complete illustration. If you have already assigned the first two lines, the third is all that is necessary.
Example —
v = randi(15, 1, 20);
chosen_values = [2 4 5 10];
chosen_cells_index = ismember(v, chosen_values)
The ‘chosen_cells_index’ vector will be what you want.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!