给出矩阵:
A = {{a11, a12, a13, a14},
{a21, a22, a23, a24},
{a31, a32, a33, a34}};
B = {{b11, b12, b13},
{b21, b22, b23},
{b31, b32, b33}};
通过计算:
Transpose[A].B.A
很明显,获得的4x4矩阵的第一个条目是:
a11 (a11 b11 + a21 b21 + a31 b31) +
a21 (a11 b12 + a21 b22 + a31 b32) +
a31 (a11 b13 + a21 b23 + a31 b33)
我的目标是为周期编写一系列嵌套的 以获得该矩阵的4x4条目。
经过多次失败的尝试后,我在这里问是否有人可以帮我或者拿些书给我,我可以找到编写的算法。
谢谢!
答案 0 :(得分:2)
如果您只想使用for循环进行计算,则算法为:
for i = 1..4
for j = 1..4
v := 0
for p = 1..3
t := 0
for q = 1..3
t := t + a[q, i] * b[q, p]
v := v + a[p, j] * t
c[i, j] := v
c
是4x4输出矩阵。
这是Python的演示:
import numpy as np
# Make input matrices
a = np.arange(12).reshape(3, 4)
b = np.arange(12, 21).reshape(3, 3)
# Compute result with matrix products
c = a.T @ b @ a
# Compute result with loops
c2 = np.empty([4, 4], dtype=a.dtype)
for i in range(a.shape[1]):
for j in range(a.shape[1]):
v = 0
for p in range(a.shape[0]):
t = 0
for q in range(a.shape[0]):
t += a[q, i] * b[q, p]
v += a[p, j] * t
c2[i, j] = v
# Check result
print((c == c2).all())
# True