1
$\begingroup$

I would like to evaluate the following function

q[beta_, gamma_] := Sum[R[[n, 3]]], {n, 3}];
q[Pi/3, Pi/4]

Over the matrix

R= {{Cos[beta] Cos[gamma], -Sin[gamma], 
    Sin[beta] Cos[gamma]}, {Cos[beta] Sin[gamma], Cos[gamma], 
    Sin[beta] Sin[gamma]}, {-Sin[beta], 0, Cos[gamma]}};

This above method, however, does not give any results. I then tried it (besed on Define Function with Sum over a list):

q[beta_, gamma_, R_] := Sum[R[[n, 3]], {n, 1, Length@R}];
q[Pi/3, Pi/4, {R}]

that also did not work. How do I do this?

$\endgroup$

1 Answer 1

1
$\begingroup$

Why this isn't working

I believe your problem is that beta and gamma don't appear on the right hand side (rhs) explicitly in your definition of q, but only through R. This is a problem here because you're using :=, which does not evaluate its rhs until the function being defined is called.

After defining q as you have, evaluate ?q—this will give you the definitions for q, and you'll see that R appears as a symbol there, not as something involving beta and gamma. So, q[Pi/3, Pi/4] gets replaced with Sum[R[[n, 3]], {n, 3}], and Pi/3 and Pi/4 are thrown away. Then R is expanded into its definition.

How to fix it

There are a couple ways to fix this.

  1. Make R a function: R[beta_, gamma_] := <insert matrix here>. Then use q[beta_, gamma_] := Sum[R[beta, gamma][[n, 3]], {n, 3}].

  2. Use = instead of :=. Unlike :=, = evaluates its rhs first. This is generally riskier and not recommended, since the arguments are not bound; if you have external definitions for the arguments, they'll be substituted in before the definition is created! So for example, x = 3; f[x_] = x + 1 will make f always return 4. This is not the case for f[x_] = x + 1 when x has no prior definition, even if x is defined later, e.g. f[x_] = x + 1; x = 3 produces an f that works as expected. So good variable hygiene is important.

  3. Or, like, 2 but safer, inline the whole of R.

$\endgroup$
2
  • $\begingroup$ Your first suggestion works. Thanks! $\endgroup$ Commented Mar 15, 2021 at 0:41
  • 2
    $\begingroup$ Or q[b_, g_] := Sum[R[[n, 3]], {n, 3}] /. {beta :> b, gamma :> g} $\endgroup$ Commented Mar 15, 2021 at 0:48

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.