将"for"循环转换为矩阵表达式? [英] Convert a 'for' loop into a matrix expression?

查看:142
本文介绍了将"for"循环转换为矩阵表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用矩阵形式在表达式中转换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的向量Eindices列表:

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]

我想将i0i1中包含的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆