[Numpy-discussion] Need some explanations on assigning/incrementing values in Numpy
Loïc BERTHE
berthe.loic at gmail.com
Sat Nov 22 14:19:36 EST 2008
I've encoutered an error during an ipython's session that I fail to understand :
In [12]: n = 4
In [13]: K = mat(diag(arange(2*n)))
In [14]: print K
[[0 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 0 2 0 0 0 0 0]
[0 0 0 3 0 0 0 0]
[0 0 0 0 4 0 0 0]
[0 0 0 0 0 5 0 0]
[0 0 0 0 0 0 6 0]
[0 0 0 0 0 0 0 7]]
In [15]: o = 2*arange(n)
In [16]: kc = 10 + arange(n)
In [17]: K[ r_[o-1, o], r_[o, o-1] ] = r_[kc, kc]
In [18]: print K
[[ 0 0 0 0 0 0 0 10]
[ 0 1 11 0 0 0 0 0]
[ 0 11 2 0 0 0 0 0]
[ 0 0 0 3 12 0 0 0]
[ 0 0 0 12 4 0 0 0]
[ 0 0 0 0 0 5 13 0]
[ 0 0 0 0 0 13 6 0]
[10 0 0 0 0 0 0 7]]
In [19]: K[ r_[o-1, o], r_[o, o-1]] += 10*r_[kc, kc]
---------------------------------------------------------------------------
<type 'exceptions.ValueError'> Traceback (most recent call last)
/home/loic/Python/numpy/<ipython console> in <module>()
<type 'exceptions.ValueError'>: array is not broadcastable to correct shape
In [20]: print K[ r_[o-1, o], r_[o, o-1]].shape, r_[kc, kc].shape
(1, 8) (8,)
In [21]: print K[ r_[o-1, o], r_[o, o-1]].shape, r_[kc, kc][newaxis, :].shape
(1, 8) (1, 8)
In [22]: K[ r_[o-1, o], r_[o, o-1]] += 10*r_[kc, kc][newaxis, :]
---------------------------------------------------------------------------
<type 'exceptions.ValueError'> Traceback (most recent call last)
/home/loic/Python/numpy/<ipython console> in <module>()
<type 'exceptions.ValueError'>: array is not broadcastable to correct shape
Could you explain me :
- Why do an assignment at line 17 works where an increment raises an
error (line 19) ?
More information about the NumPy-Discussion
mailing list