需要帮助将矩阵公式转换为Python代码

时间:2019-01-16 12:50:25

标签: python math matrix

我是Python的新手,我需要一些帮助将以下公式转换为Python代码:

enter image description here

enter image description here

我目前正在用numpy解决,但是进展甚微。任何参考资料将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是一种可能性。评论中包含一些假设。当然,还有其他方法可以做到这一点。第二个公式的分母中的集合大小可以更简单地作为集合或列表的长度来完成,但是我的方法避免了使用集合/列表的内存,并且与分子更加一致。

def formula1(X, n, a, b):
    """Return the first formula for matrix X, size n, and indices a and b.
    """
    return sum(X[a][t] - X[b][t] for t in range(1, n+1)) / n

def formula2(X, n, i, j, x, y, a, P):
    """Return the second formula for matrix X, size n, indices i, j, x, and y,
    array or mapping a, array or mapping of sets P.
    """
    numer = sum(abs(X[i][t] - X[j][t])
                for t in range(1, n+1)
                if a[t] in P[x] or a[t] in P[y])
    denom = sum(1
                for t in range(1, n+1)
                if a[t] in P[x] or a[t] in P[y])
    return numer / denom
相关问题