フィルターのクリア

Convert Logical into Sequential Index Vector

100 ビュー (過去 30 日間)
John R.
John R. 2016 年 2 月 2 日
移動済み: Star Strider 2023 年 1 月 29 日
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.

採用された回答

Star Strider
Star Strider 2016 年 2 月 2 日
Us e the find function:
x = [0 1 0 0 1 1 1 0];
y = find(x)
y =
2 5 6 7
  2 件のコメント
Gabor
Gabor 2021 年 6 月 25 日
移動済み: Star Strider 2023 年 1 月 29 日
Hi,
What if we want to do the exact opposite?
We have y = [2 5 6 7] and we want to create x = [0 1 0 0 1 1 1] without loop?
x(ismember(1:max(y),y))=true
than we get our logical vector array without loop from a list of indexes
x =
1×7 logical array
0 1 0 0 1 1 1
I hope it helps someone, it took me sometime to figure this out.
Keywords: create logical vector from array of indexes, from index array, from idx, from vector of indexes.
Star Strider
Star Strider 2021 年 6 月 25 日
移動済み: Star Strider 2023 年 1 月 29 日
That can be significantly simplified:
y = [2 5 6 7]
y = 1×4
2 5 6 7
x(y) = true
x = 1×7 logical array
0 1 0 0 1 1 1
If ‘x’ is already longer than 7 elements (for example to reconstitute the original 8-element vector):
x = zeros(1,8)
x = 1×8
0 0 0 0 0 0 0 0
x(y) = true
x = 1×8
0 1 0 0 1 1 1 0
.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by