使用“曲线”,可以使用绘制函数:棘手的表达式? [英] Using "curve" to plot a function: a tricky expression?
问题描述
我的问题涉及应该相当简单的内容,但我无法使其正常工作。我的意思是,您可以计算 x
和 y
,然后使用 plot
函数。但这可以使用曲线
函数完成吗?
My question concerns something that should be fairly simple, but I can't make it work. What I mean is you can calculate x
and y
and then plot them with the plot
function. But can this be done using the curve
function?
我想绘制以下 R
函数 f2
:
n <- 1
m <- 2
f2 <- function(x) min(x^n, x^(-m))
但是此代码失败:
curve(f2, 0, 10)
有任何建议吗?
推荐答案
如前所述,调用曲线
失败的主要原因是因为曲线
需要向量化函数(在这种情况下,输入结果向量,并得出结果向量),而f2()函数仅输入和输出标量。您可以使用 Vectorize
As has been hinted at, the main reason why the call to curve
fails is because curve
requires a vectorized function (in this case feed in a vector of results and get out a vector of results), while your f2() function only inputs and outputs a scalar. You can vectorize your f2 on the fly with Vectorize
n <- 1
m <- 2
f2 <- function(x) min(x^n, x^(-m))
curve(Vectorize(f2)(x), 0, 10)
这篇关于使用“曲线”,可以使用绘制函数:棘手的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!