[英]How a Matlab anonymous function evaluate a matrix?
Given the following matlab code: 给出以下matlab代码:
A = reshape (1:9 ,[3 3]);
f = @(x) x^2;
f(A)
the output is: 输出为:
A =
1 4 7
2 5 8
3 6 9
ans =
30 66 102
36 81 126
42 96 150
Can you please explain to me how this output is calculated? 能否请您解释一下该输出是如何计算的? how the anonymous function is invoked? 如何调用匿名函数?
I want to write the same program in python. 我想用python编写相同的程序。
Is there any compatible function in python which lets me implement this? python中有任何兼容的函数可以让我实现吗?
An anonymous function with a matrix as an input behaves just as the contents normally would if executed from the command line. 使用矩阵作为输入的匿名函数的行为与从命令行执行时的正常内容相同。 It does nothing special. 没什么特别的。
The issue is that you're using ^
which is the matrix power ( mpower
) and I believe you are looking for the element-wise power ( power
) which is .^
which in your case would square each element individually. 问题是您使用的是^
,它是矩阵乘方( mpower
) ,我相信您正在寻找的元素方乘方 ( power
)是.^
,在您的情况下,它将单独对每个元素求平方。
f = @(x)x.^2;
B = f(A);
If you want to do the same in Python, you can do exactly this with numpy
如果要在Python中执行相同的操作,则可以使用numpy
import numpy as np
A = np.arange(1, 10).reshape(3, 3).T
B = np.power(A, 2)
If you want to encaptulate this operation, it's best pratice to put it into it's own function 如果要对此操作进行概括,最好将其放入自己的函数中
def f(x):
return np.power(x, 2)
B = f(A)
If you named lambda
(anonymous) function ( this isn't recommended ) you can do: 如果您将lambda
(匿名)函数命名为( 不推荐使用 )函数, 则可以执行以下操作:
f = lambda x: np.power(x, 2)
B = f(A)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.