There are several constructs that can be used here, but it seems like the best for this construction would be With
:
f[x_] := With[{m = Msum[x]}, Table[m[[i, i]] + m[[i + 1, i + 1]], {i, 1, 2 N - 1, 2}]]
With
allows you to locally define constant values to be used inside of it, and since presumable Msum[x]
is in fact constant for any evaluation of x
, this makes it ideal.
Block
and Module
are similar constructs that have uses when you need to be able to change the value of the local variable. This is useful for temporary variables or other values which will change during evaluation, such as accumulator variables in loops. See the documentation and this answer for more information on them.
As mentioned by bill s and Carl Woll in the comments, you can also use CompoundExpression
(;
), but be aware that this provides no scope control by itself. Thus, this kind of construction:
f[x_] := (m = Msum[x]; Table[m[[i]] + m[[i + 1]], {i, 1, 2 N - 1, 2}])
While perfectly effective, may interfere with other uses of m
in your code. It may not, and it may be fine, but you should take it into consideration.
For the sake of understanding what's going on with the parentheses in that last example, note that ()
is being used in exactly the same sense that it would be used in a mathematical expression. That is, the parentheses are overriding the ordinary operator precedence rules. Ordinarily, Mathematica would split the expression around ;
before considering :=
, but by using the parentheses you can force the :=
to be established first and take the whole compound expression as its right hand side.
One other possibility is to simply chain the functions together:
f[x_] := Table[#[[i,i]] + #[[i+1,i+1]], {i,1,2 N - 1, 2}] & [Msum[x]]
This constructs a function which takes x
as the argument, calculates Msum[x]
, and passes it inside into a function which calculates the requested Table
. At this point it's equally simple to just create f
such that you'll always use it in conjunction with Msum
though.
;
that meansCompoundExpression
. The parentheses just control grouping. The default grouping is(f[x_] := m = Msum[x]); Table[m[[i]] + m[[i + 1]], {i, 1, 2 N - 1, 2}]
$\endgroup$