logical indexing

조회 수: 14 (최근 30일)
Thijs
Thijs 2012년 3월 14일
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일
Use LOGICAL to do the type conversion:
a(logical(b))

추가 답변 (4개)

Aldin
Aldin 2012년 3월 14일
Here:
for i = 1:5
if b(i) == 1
disp(a(i))
end
end
:)
  댓글 수: 6
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일
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일
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일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by