8

I want to define a function that would symbolically look like

$$ t(s,\underline{a})=\pi s + \sum_{n=1}^{n_{max}}a_n\sin(n \pi s) $$

(something like a finite Fourier series). Here $s\in [0,1]$ and $\underline a$ is a vector with $n_{max}$ entries $a=(a_1,...,a_i,...,a_{n_{max}})$.

Is there a short way to define such a function without having to name all the single $a_i$ in the function definition but take a vector as the input variable? My try was to define it just straightforward like

t[s_?NumericQ, a1_?NumericQ, a2_?NumericQ, a3_?NumericQ, a4_?NumericQ,
a5_?NumericQ, ...] := ...

but that gets really confusing for higher $n_{max}$.

So many thanks for any trick to handle it better :)

Malte
  • 81
  • 2

4 Answers4

7

You can effectively use Dot as a sum

t[s_, a_List] := π s + a.Sin[π s Range@Length@a]

t[1/3, {4, 7, 3, 4}]
(* (7 Sqrt[3])/2 + π/3 *)

Or

t[s_, a__] := π s + {a}. Sin[π s Range@Length@{a}]

t[1/3, 4, 7, 3, 4]
(* (7 Sqrt[3])/2 + π/3 *)

I suppose you use NumericQ to deal with this issue. If so, s_?NumericQ in the first argument is enough.

ybeltukov
  • 43,673
  • 5
  • 108
  • 212
4

You could use something along the lines of

t[s_, a_]:=π s + Sum[a[[n]] Sin[π n s], {n,1,Length@a}]

used like this:

t[1/3, {4, 7, 3, 4}]

giving you (for that case): (7 Sqrt[3])/2 + π/3.

Maybe of interest: In Mathematica, function arguments are not limited just to simple values like numbers, but can take quite anything, if you do not explicitly limit their type, which is what you did by giving ?NumericQ.

The code example above essentially does the following:

  1. a[[n]] gets the nth entry from the function argument a.
  2. Sum provides the iterator via {n,1,Length@a}, while
  3. Length@a gets the length of the list a, so n runs from $1$ to $n_{max}$ as desired.
Jinxed
  • 3,753
  • 10
  • 24
1

If you are new to Mathematica a first step could be:

t[a_, s_] := π*s + a.Table[Sin[n*π*s], {n, 1, Length@a}]

So the input is a vector a (Mathematica a list of numbers) is processed properly. But there are many, many other ways to do this. A bit closer to Mathematica is

π s + a.(Sin[# *π*s] & /@ Range[Length@a])

but this are only two rather straightforward examples ;-)

xyz
  • 605
  • 4
  • 38
  • 117
mgamer
  • 5,593
  • 18
  • 26
0

Just another variant:

f[s_, a__] := Total@MapIndexed[#1 Sin[First@#2 Pi s] &, {a}] + Pi s

So,f[s, 1, 2, 3] yields:

(*\[Pi] s + Sin[\[Pi] s] + 2 Sin[2 \[Pi] s] + 3 Sin[3 \[Pi] s]*)
ubpdqn
  • 60,617
  • 3
  • 59
  • 148