Can anyone explain how the following code:
Y(Y==0) = -1
sets all values of 0 to -1. For example for:
Y = [1 1 1 0 0 0 1]
we get:
Y = [1 1 1 -1 -1 -1 1]
What is confusing me is that Y==0
does not return a vector of indices.
An if I try to use the vector Y==0
directly I get the error:
Y([0 0 0 1 1 1 0]) = -1
error: subscript indices must be either positive integers or logicals
I would have naturally opted for:
Y(find(Y==0)) = -1
and would like to know why the above does not use find
TIA
This is called logical indexing. There is some documentation on gnu.org (see 4.6 Logical Values), but the best place to find info about it is probably in the MATLAB documentation.
Your example does not work because you are using an array of doubles, instead of a logical array, to index into Y
. Consider the following (using Octave 3.6.2):
>> Y = [1 1 1 0 0 0 1]
Y =
1 1 1 0 0 0 1
>> idx = Y==0
idx =
0 0 0 1 1 1 0
>> idx_not_logical = [0 0 0 1 1 1 0]
idx_not_logical =
0 0 0 1 1 1 0
>> whos
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
Y 1x7 56 double
ans 1x7 7 logical
cmd_path 1x489 489 char
gs_path 1x16 16 char
idx 1x7 7 logical
idx_not_logical 1x7 56 double
Total is 533 elements using 631 bytes
>> Y(idx_not_logical)=-1
error: subscript indices must be either positive integers or logicals
>> Y(idx)=-1
Y =
1 1 1 -1 -1 -1 1
Y==0
returns a bool matrix
as shown by:
> typeinfo(Y==0)
ans = bool matrix
That's why you can't index directly with [0 0 0 1 1 1 0]
, which is a matrix
:
> typeinfo([0 0 0 1 1 1 0])
ans = matrix
If you wish to convert to boolean, use logical()
:
> typeinfo(logical([0 0 0 1 1 1 0]))
ans = bool matrix