Reputation: 50
Trying to understand matrix indexing.
A = [2 3 0 0 5; 3 0 0 0 0];
B = [1 1 0 0 1; 1 0 0 0 0];
When I run
A(1, B(1, :))
I was expecting
[2 3 5]
But instead, I get the error:
error: subscript indices must be either positive integers or logicals.
Upvotes: 0
Views: 60
Reputation: 30579
Convert to logical
:
>> A(1, logical(B(1, :)))
ans =
2 3 5
Since B
is actually a double
array, it thinks you are trying to index element 0
, which causes the error.
Or, if you prefer double negation, do A(1, ~~B(1, :))
. Personally, I think that looks ugly. Or simply test: A(1, B(1, :)==1)
, A(1, B(1, :)~=0)
, A(1, B(1, :)>0)
, etc.
The other solution is to use find
to satisfy the "positive integers" part of the error:
>> A(1, find(B(1, :)))
ans =
2 3 5
Upvotes: 2