imagine you have a two matrixes:
a=[1 2 3 4 5 6 7 8 9];
b=[1 0 1 0 1];
how do i use the b matrix as a logical index? I'd expect:
a(b)
ans =
[1 3 5]
but instead i get the error: "Subscript indices must either be real positive integers or logicals."
if I try
a(~b)
ans =
[2 4]
now I could use a(~~b) which does what i want but this seems inelegant. Can anyone suggest a better solution?

 採用された回答

Jacob Halbrooks
Jacob Halbrooks 2012 年 3 月 14 日

2 投票

Use LOGICAL to do the type conversion:
a(logical(b))

その他の回答 (4 件)

Aldin
Aldin 2012 年 3 月 14 日

0 投票

Here:
for i = 1:5
if b(i) == 1
disp(a(i))
end
end
:)

6 件のコメント

Aldin
Aldin 2012 年 3 月 14 日
If you want i can put the result 1,3,5 in an array ???
Thijs
Thijs 2012 年 3 月 14 日
using a for loop seems even MORE inelegant
Aldin
Aldin 2012 年 3 月 14 日
Thanks
Aldin
Aldin 2012 年 3 月 14 日
index = 0;
for i = 1:length(b)
if b(i) == 1
index = index + 1;
result(index) = a(i);
end
end
Aldin
Aldin 2012 年 3 月 14 日
result =
1 3 5
Aldin
Aldin 2012 年 3 月 14 日
Here is another solution:
a(b(1:5)==1)

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

Thijs
Thijs 2012 年 3 月 14 日

0 投票

a(logical(b)) does what I want. In case anyone else is wondering

2 件のコメント

Aldin
Aldin 2012 年 3 月 14 日
See above it's similiar with my solution :)
Thijs
Thijs 2012 年 3 月 14 日
true, thanks

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

Onomitra Ghosh
Onomitra Ghosh 2012 年 3 月 14 日

0 投票

Your "b" matrix is in double. You need to convert that to logical values for logical indexing:
>> a(boolean(b))
ans =
1 3 5
Aldin
Aldin 2012 年 3 月 14 日

0 投票

but what if you haven't only '1' and '0' in b array. I think it's better my first solution or second &Onomitra Ghosh his code with logical work correctly

カテゴリ

ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by