Maffred
Maffred

Reputation: 107

R - creating a function f(x) as a sum indexed by n

Is it possible in R to write a function f(x) like

f(x) = a_0 + a_1*sin(x) + ... + a_n*sin(n*x)

for some n, or any other f_i(x) in place of sin(i*x) just varying on i? I tried a recursion like

f <- function(x) a_0
for(n in 1:N)
f <- function(x) f(x) + a_n*x^n

It seemed to work but when I used f(x) to make some computations R said there was too much nesting. I eventually wrote by hand a_0 + a_1*x + ... etc. Is there a proper way to do it in a compact way without using recursion?

Upvotes: 0

Views: 44

Answers (1)

MrFlick
MrFlick

Reputation: 206197

If you have the following values of a and x

a <- 1:5
x <- 3
a[1] + a[2]*sin(x*1) + a[3]*sin(x*2) + a[4]*sin(x*3) + a[5]*sin(x*4)
# [1] -0.5903971

Then you can get the same value using

f <- function(x) {
  a[1] + sum( a[-1] * sin((x * seq.int(length(a)-1) )))
}
f(x) 
#[1] -0.5903971

Note that arrays in R use 1-based indexing

Upvotes: 2

Related Questions