0

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?

Maffred
  • 107
  • 1
  • 9
  • Sorry, I can't load the image, can you express it with some words? – Peace Wang Jul 20 '21 at 01:23
  • You seem to be redefining the function `f` in a loop and I'm not sure that's what you want. What is some sample input to this function and what is the value you expect to be returned for that sample input. Is `f` a function of both `a` and `x`? – MrFlick Jul 20 '21 at 01:25
  • This `f <- function(x) a_0` makes no sense, it's necessary because it's just a constant. Is your purpose to calculate `f(x) = a_0 + a_1 * x + ... + a_n * x^n `? – Peace Wang Jul 20 '21 at 01:27
  • @PeaceWang I need to define a function like for example f(x) = a_0 + a_1*sin(x)+ ... + a_n*sin(n*x) for some n, so then I can compose it with other functions or integrate it etc. – Maffred Jul 20 '21 at 01:30
  • @MrFlick I guess my last comment explains better what I'm asking. – Maffred Jul 20 '21 at 01:31
  • So where are the values of `a` coming from? It seems like you can just do `sum(a*sin(x * seq_along(x))` assuming `a` is a vector the same length as `x`. And then just add the null term. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 20 '21 at 01:33
  • @MrFlick I'm confused! a is a given vector a_0, ... , a_N, but x is a variable in R. – Maffred Jul 20 '21 at 01:38

1 Answers1

2

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

MrFlick
  • 195,160
  • 17
  • 277
  • 295