# NOT RUN {
fs <- 256
secs <- 10
freq <- 30
ampl <- 1
t <- seq(0, secs, length.out = fs * secs)
x <- ampl * cos(freq * 2 * pi * t) + runif(length(t))
Pxx <- pwelch(x, fs = fs) # no plot
pwelch(x, fs = fs) # plot
# 90 degrees phase shift with with respect to x
y <- ampl * sin(freq * 2 * pi * t) + runif(length(t))
Pxy <- pwelch(cbind(x, y), fs = fs)
plot(Pxy, yscale = "dB")
plot(Pxy, plot.type = "phase")
# note the phase shift around 30 Hz is pi/2
plot(Pxy, plot.type = "coherence")
# Transfer function estimate example
fs <- 1000 # Sampling frequency
t <- (0:fs) / fs # One second worth of samples
A <- c(1, 2) # Sinusoid amplitudes
f <- c(150, 140) # Sinusoid frequencies
xn <- A[1] * sin(2 * pi * f[1] * t) +
A[2] * sin(2 * pi * f[2] * t) + 0.1 * runif(length(t))
h <- Ma(rep(1L, 10) / 10) # Moving average filter
yn <- filter(h, xn)
atfm <- freqz(h, fs = fs)
etfm <- pwelch(cbind(xn, yn), fs = fs)
op <- par(mfrow = c(2, 1))
xl <- "Frequency (Hz)"; yl <- "Magnitude"
plot(atfm$w, abs(atfm$h), type = "l", main = "Actual", xlab = xl, ylab = yl)
plot(etfm$freq, abs(etfm$trans), type = "l", main = "Estimated",
xlab = xl, ylab = yl)
par(op)
# }
Run the code above in your browser using DataLab