Convert Logical into Sequential Index Vector
165 views (last 30 days)
Show older comments
John R.
on 2 Feb 2016
Moved: Star Strider
on 29 Jan 2023 at 20:00
Hello,
I am looking for a simple way to convert a logical vector in a sequential vector of doubles whose values are the indices of true in the logical vector. For example, let's say x is a 1x8 logical vector:
x = [0 1 0 0 1 1 1 0]
The result I am looking for would be y:
y = [2 5 6 7]
I know this can be done with a for loop, but was curious if there is a clever one-liner.
Thank you.
0 Comments
Accepted Answer
Star Strider
on 2 Feb 2016
Us e the find function:
x = [0 1 0 0 1 1 1 0];
y = find(x)
y =
2 5 6 7
2 Comments
Star Strider
on 25 Jun 2021
Moved: Star Strider
on 29 Jan 2023 at 20:00
That can be significantly simplified:
y = [2 5 6 7]
x(y) = true
If ‘x’ is already longer than 7 elements (for example to reconstitute the original 8-element vector):
x = zeros(1,8)
x(y) = true
.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!