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.


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."
  • 1
    $\begingroup$ You have an extra _ in the right-hand side. Next, you can drop the x argument and evaluate you function as s[Cos[#] &, Sin[3 #] &, 5]. $\endgroup$ Nov 22, 2012 at 8:48
  • $\begingroup$ It actually worked, thanks! However, would be nice to find some guide on operators as such, google is not very helpful with those symbols. $\endgroup$
    – prazuber
    Nov 22, 2012 at 8:59
  • $\begingroup$ "some guide on operators" - see this, for starters... $\endgroup$ Nov 22, 2012 at 9:00
  • $\begingroup$ and this thread full of useful resources. $\endgroup$ Nov 22, 2012 at 9:02

1 Answer 1


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.)

  • $\begingroup$ Thank you, this is exactly what I needed! $\endgroup$
    – prazuber
    Nov 29, 2012 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.