2015-05-07 39 views
1

我想在R中建立一个函数,它代表范围[0,1]范围内有100Hz的正方形和锯齿波。我尝试这样做:编程方波和锯齿波在R

squarewave <- function (t) { 

    # 0.01 == 100Hz(=2Pi) -> 1 Period of the Squarewave 
    # 0.005 == Pi   -> Half Period of the Squarewave 
    # if t smaller than a half period -> 1 
    # if t greater or equal than half a period -> 0 

    if ((t %% 0.01) < 0.005) 
    return (1) 
    else if ((t %% 0.01) >= 0.005) 
    return (0) 

} 

当我尝试绘图使用此功能:

plot(squarewave) 

我得到以下错误:

> plot(squarewave) 
Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab, : 
    'expr' has not been evaluated to an object of length 'n' 
In addition: Warning message: 
In if ((t%%0.01) < 0.005) return(1) else if ((t%%0.01) >= 0.005) return(0) : 
    the condition has length > 1 and only the first element will be used 

那么,为什么这不是工作?

+0

用英文发表您的错误,而不是德文。 – Naruto

+1

当您绘制它时,您没有将任何参数传递给'squarewave'。你不能直接绘制一个函数。 –

回答

2

您需要将向量化函数传递给plot。因此,请使用Vectorize自动执行此操作,或者使用ifelse而不是if

plot(Vectorize(squarewave)) 

squarewave2 <- function (t) { 

    # 0.01 == 100Hz(=2Pi) -> 1 Period of the Squarewave 
    # 0.005 == Pi   -> Half Period of the Squarewave 
    # if t smaller than a half period -> 1 
    # if t greater or equal than half a period -> 0 

    ifelse(((t %% 0.01) < 0.005),1,0) 
} 

plot(squarewave2) 

为了增加plot的分辨率,使用参数n,见?curve了解详情。

+0

对不起,我发现并删除了我的评论,然后才发现你已经回答了。无论如何,我按照你的建议打开了'n',它工作的很好。我以前不知道,所以今天我从你的答案中学到了一些东西。 – TARehman

+0

这就是要点! 使用ifelse-Statement时,函数显示为可以绘制的矢量化函数。接下来,情节就像一个空中飞人。为了让情节看起来像一个真正的方波,你必须增加函数图的n值。 感谢詹姆斯! – tbol

0

我最初错了,想更新。

除非它是正确的矢量化,你不能绘制一个原始函数,而需要改为绘制函数的输出。下面是使用您的特定功能完成此操作的简单方法。

sequence <- seq(from = 0,to = 0.01, by = 0.00001) 
plot(sapply(X = sequence,FUN = squarewave),type = "o") 
+0

这不是正确的: cos64hz < - 函数(t)的{ 返回(COS(2 * 64 * PI * t))的 } 工作很大具有: 情节(cos64hz,类型= “L”,XLIM = c(0,1/20),ylim = c(-1,1.5),col =“blue”,ylab =“Amplitude”,xlab =“Zeit [sec]”) – tbol

+0

您是否更具体?我用它制作了一个非常漂亮的方波。 – TARehman

+0

@AlexA。写入的函数不会接受向量作为参数,因此使用'sapply()'来获取向量。 – TARehman