1

I want to write a function like the following:

s[u_, v_, x_, val_] := u[val]/NIntegrate[u'[x] v[x] + u'[x] v'[x], {x, 0, 1}]

So I can evaluate something like

s[Cos[x], Sin[3 x], x, 5]

I have a strong feeling that my approach is incorrect, however, I couldn't find the right one.

Update:

Thanks to b.gatessucks, who wrote the correct version of what I was trying to achieve. However, after that I tried to use that approach on lists:

r = {1, 2, 3, 4, 5};
u[x_, i_] := Sin[r[[i]] x];
A = Table[s[u[#, i] &, u[#, j] &, 5], {i, 5}, {j, 5}]

After this, I get a matrix, but I also get a bunch of errors, so I don't know if I can trust the output. The errors are:

Part::pspec: Part specification #2 is neither an integer nor a list of integers.
Part::pspec: Part specification #2 is neither an integer nor a list of integers.
Part::pspec: Part specification #2 is neither an integer nor a list of integers.
General::stop: "Further output of Part::pspec: will be suppressed during this calculation."
prazuber
  • 429
  • 1
  • 4
  • 10

1 Answers1

0

Despite some practice with Mathematica, I still consider myself a newbie. However, I have come to understand that a function and an expression are two different things, despite the fact that the documentation seems to use them indistinctly (if I am wrong, glad to hear the comment of an expert!)

So, what I did and that seems to work with s is to consider u and v as expression parameters - therefore the use of /. inside, with the symbol parameter x - and define the functions inside, so as to apply ' later on. The code is:

s[u_, v_, x_, val_] := Module[{f, g},
   f[t_] := u /. x -> t;
   g[t_] := v /. x -> t; 
   f[val]/NIntegrate[f'[t] g[t] + f'[t] g'[t], {t, 0, 1}]
   ];

which gives the output

In[9]:= s[Cos[x], Sin[3 x], x, 5]

Out[9]= 2.36249

Hope helps.

(By the way: I believe it is in these cases that you want to use HoldFirst, HoldAll and related evaluation attributes.)

carlosayam
  • 2,080
  • 16
  • 21