Using octave to map vector values

折月煮酒 提交于 2020-01-04 15:31:25

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/20354201/using-octave-to-map-vector-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!