在R中编程方波和锯齿波

Programming square wave & sawtooth wave in R

我正在尝试在 R 中构建一个函数,该函数代表 [0,1] 范围内 100Hz 的方波和锯齿波。我试过这个:

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

为什么这不起作用?

一开始我错了,想更新。

除非它被正确矢量化,否则您不能绘制原始函数而需要绘制函数的输出。下面是使用您的特定函数执行此操作的简单方法。

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

您需要将矢量化函数传递给 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