logical indexing
4 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
更多回答(4 个)
Onomitra Ghosh
2012-3-14
Your "b" matrix is in double. You need to convert that to logical values for logical indexing:
>> a(boolean(b))
ans =
1 3 5
0 个评论
Aldin
2012-3-14
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!