简体   繁体   English

关于python中的numpy矩阵的简单问题

[英]Simple question about numpy matrix in python

Let's suppose I have a numpy matrix variable called MATRIX with 3 coordinates: (x, y, z). 假设我有一个名为MATRIX的numpy矩阵变量,具有3个坐标:(x,y,z)。

Is acessing the matrix's value through the following code 通过以下代码访问矩阵的值

myVar = MATRIX[0,0,0]

equal to 等于

myVar = MATRIX[0,0][0]

or 要么

myVar = MATRIX[0][0,0]

?

What about if I have the following code? 如果我有以下代码怎么办?

myTuple = (0,0)
myScalar = 0
myVar = MATRIX[myTuple, myScalar]

Is the last line equivalent to doing 最后一行等于

myVar = MATRIX[myTuple[0], myTuple[1], myScalar]

I have done simple tests and it seems so, but maybe that is not so in all the cases. 我已经完成了简单的测试,似乎是这样,但也许并非在所有情况下都如此。 How do square brackets work in python with numpy matrices? 方括号如何在带有numpy矩阵的python中工作? Since day one I felt confused as how they work. 从第一天开始,我对它们的工作方式感到困惑。

Thanks 谢谢

I assume you have a array instance rather than a matrix , since the latter only can have two dimensions. 我假设您有一个array实例,而不是一个matrix ,因为后者只能具有两个维度。

m[0, 0, 0] gets the element at position (0, 0, 0). m[0, 0, 0]获取元素在位置(0,0,0)。 m[0, 0] gets a whole subarray (a slice), which is itself a array . m[0, 0]得到一个整个子array (一个切片),它本身就是一个array You can get the first element of this subarray like this: m[0, 0][0] , which is why both syntaxes work (even though m[i, j, k] is preferred because it doesn't have the unnecessary intermediate step). 您可以像下面这样子数组的第一个元素: m[0, 0][0] ,这就是为什么两种语法都可以工作的原因(尽管首选m[i, j, k]是因为它没有不必要的中间变量)步)。

Take a look at this ipython session: 看一下这个ipython会话:

rbonvall@andy:~$ ipython
Python 2.5.4 (r254:67916, Sep 26 2009, 08:19:36) 
[...]

In [1]: import numpy.random

In [2]: m = numpy.random.random(size=(3, 3, 3))

In [3]: m
Out[3]: 
array([[[ 0.68853531,  0.8815277 ,  0.53613676],
        [ 0.9985735 ,  0.56409085,  0.03887982],
        [ 0.12083102,  0.0301229 ,  0.51331851]],

       [[ 0.73868543,  0.24904349,  0.24035031],
        [ 0.15458694,  0.35570177,  0.22097202],
        [ 0.81639051,  0.55742805,  0.5866573 ]],

       [[ 0.90302482,  0.29878548,  0.90705737],
        [ 0.68582033,  0.1988247 ,  0.9308886 ],
        [ 0.88956484,  0.25112987,  0.69732309]]])

In [4]: m[0, 0]
Out[4]: array([ 0.68853531,  0.8815277 ,  0.53613676])

In [5]: m[0, 0][0]
Out[5]: 0.6885353066709865

It only works like this for numpy array s. 它仅对numpy array像这样工作。 Python built-in tuples and lists are not indexable by tuples, just by integers. Python内置的元组和列表不能由元组索引,而只能由整数索引。

无法用另一个元组索引一个元组,因此该代码均无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM