将"for"循环转换为矩阵表达式? [英] Convert a 'for' loop into a matrix expression?
问题描述
我需要使用矩阵形式在表达式中转换for
循环.我有一个矩阵C
:
I need to convert a for
loop in an expression using matrices form. I have a matrix C
:
矩阵C
:
array([[0, 1, 1],
[1, 0, 0],
[1, 0, 0]])
向量delta_E
:
array([ 4., 2., 4., 1.])
A
是尺寸为C
的零矩阵,长度为3的向量E
和indices
列表:
A
is a matrix of of zeros with the dimension of C
, a vector E
of length 3, and a list of indices
:
indices = [1, 1, 0, 1]
我找到了C
的列索引:
i0, i1 = np.where(C[indices] == 1)
它们是:
i0 = [0, 1, 2, 3]
i1 = [0, 0, 1, 0]
我想将i0
和i1
中包含的A
索引增加1,并且将i1
中包含的E
索引增加delta_E
:
I want to increment the A
indices contained in i0
and i1
by one and increment the E
indices contained in i1
by delta_E
:
for k, i, j in enumerate(indices[i0], i1):
A[i,j] += 1
A[j,i] += 1
E[i] += delta_E[k]
结果是:
矩阵A
:
Matrix A
:
array([[0, 4, 1],
[4, 0, 0],
[1, 0, 0]])
矩阵E
:
Matrix E
:
array([4, 7, 0])
是否可以将上面的for
循环转换为矩阵表达式?
Is possible to convert the for
loop above into a matrix expression?
推荐答案
In [182]: for k,(i,j) in enumerate(zip(indices[i0], i1)):
...: print(k,i,j)
...:
...:
0 1 0
1 1 0
2 0 1
3 0 2
4 1 0
虽然k
是唯一的,但i,j
索引具有重复项.用全数组计算替换+=
步骤将需要使用add.at
,这是A[i] += b
的无缓冲替代方案.
While k
is unique, the i,j
indices have duplicates. Replacing the +=
steps with a whole-array calculation will require using add.at
, an unbuffered alternative to A[i] += b
.
In [190]: A = np.zeros_like(C)
In [191]: np.add.at(A,(indices[i0],i1),1)
In [192]: np.add.at(A,(i1,indices[i0]),1)
In [193]: A
Out[193]:
array([[0, 4, 1],
[4, 0, 0],
[1, 0, 0]])
对于E
,我无法复制您的值,但是我可以复制循环
For E
, I can't replicate your value, but I can replicate the loop
In [200]: delta_E = np.array([4,2,4,1,0])
In [204]: E = np.zeros(3,int)
In [205]: for k,i in enumerate(indices[i0]): # your loop
...: E[i] += delta_E[k]
...:
In [206]: E
Out[206]: array([5, 6, 0])
In [207]: E = np.zeros(3,int)
In [208]: np.add.at(E,indices[i0],delta_E)
In [209]: E
Out[209]: array([5, 6, 0])
这篇关于将"for"循环转换为矩阵表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!