Skip to main content
 首页 » 编程设计

函数的python矩阵

2025年01月19日8oomusou

给定两个矩阵 f 和 x:

def f11(x): return 1 
def f12(x): return x+1 
def f21(x): return np.log(x) 
def f22(x): return np.exp(x) 
 
 
f = np.matrix([[f11,f12],[f21,f22]]) 
x = np.matrix([[10,5],[3,8]]) 

如何按元素将矩阵运算符 f 应用于 x(考虑到函数可能更复杂,因此这只是一个示例)?

请您参考如下方法:

矩阵基本上不是为支持这些功能而设计的。相反,您可以使用一个接受数组并返回预期结果的函数。您应该使用数组而不是矩阵的原因是它们更灵活,更适合 python 操作,例如在本例中就地解包。

In [41]: def apply_f(matrix): 
    ...:     ((x, y), (z, t)) = matrix 
    ...:     return np.array([[1, y +1], [np.log(z), np.exp(t)]]) 
    ...:  
 
In [42]: x = np.array([[3, 5], [10, 8]]) 
 
In [43]: apply_f(x) 
Out[43]:  
array([[1.00000000e+00, 6.00000000e+00], 
       [2.30258509e+00, 2.98095799e+03]])