[英]Evaluating a constant anonymous function in MATLAB
In Matlab, I generally do things such as 在Matlab中,我通常会做诸如
f = @(x) x.^2;
xx = 0:.1:1;
ff = f(xx);
So that f is a function handle and both xx and ff are 1x11 vectors. 因此f是一个函数句柄,而xx和ff都是1x11向量。
However, if for some reason I need to define my function handle f like this 但是,如果由于某种原因我需要像这样定义函数句柄f
f = @(x) 1;
and do not change the code for xx and ff, then xx will still be a vector but ff will NOT: it will be a double. 并且不要更改xx和ff的代码,那么xx仍然是向量,而ff不会:它将是双精度。
This is annoying of course, because the sequel of my code assumes that ff is a 11x1 vector, so I would need to change my code any time f happens to be constant. 当然,这很烦人,因为我的代码续集假定ff是11x1向量,因此只要f恒定,我就需要更改代码。
So my first question is whether or not my code is sound to begin with. 所以我的第一个问题是,我的代码是否一开始就听起来不错。 If so, what should I do to make it work in the "constant f" case?
如果是这样,我应该怎么做才能使其在“常数f”情况下起作用? If not, how should I rewrite it?
如果没有,我应该如何重写?
This is admittedly similar to matlab constant anonymous function returns only one value instead of an array but I can't quite find an answer in that thread. 诚然,这类似于matlab常量匿名函数仅返回一个值而不是数组,但我在该线程中找不到答案。
A minor modification of the answer you linked will provide the required result: 对您链接的答案进行较小的修改将提供所需的结果:
f = @(x) ones(size(x));
The size of f(x)
will match the size of the input x
since f
outputs a vector of ones the same size as x
. f(x)
的大小将与输入x
的大小匹配,因为f
输出与x
大小相同的向量。
I found a better way of doing this. 我找到了一种更好的方法。 This shows how stupid Matlab is:
这显示了Matlab多么愚蠢:
f = @(x) (x-x)+1
Try it! 试试吧!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.