212

You will find a lot of information in this answer. I will add a few personal notes. Module Use Module when you want to localize variables inside your function's body, and those variables will potentially acquire and/or change their values during the computation. Basic use For example: f[x_]:=Module[{y=x^2},y=y+x;{x,y}] Here, a local mutable variable (...


85

Maybe this ? ClearAll["Global`*"]


82

The differences between Module, Block and With are nicely summarized by the results of the following expressions: x = "global"; f[] := x Module[{x = "local"}, {x, f[], Hold[x]}] Block[{x = "local"}, {x, f[], Hold[x]}] With[{x = "local"}, {x, f[], Hold[x]}] which returns: {"local", "global", Hold[x$123]} (* Module *) {"local", "local", Hold[x]} ...


48

An ugly hack, look at all things in Global context, keep in table if Dimensions didn't return {} Grid[Select[{#, Dimensions[ToExpression@#]} & /@ Names["Global`*"], #[[2]] != {} &], Alignment -> Left] For this to be helpful it needs to be updated dynamically and preferably be in a palette to avoid scrolling up all the time. Instead of ...


40

I'll cover a few typical uses of Block, neither of which is possible using Module or With. Temporarily removing definitions When you do Block[ {a = x}, ... ] the original definition of a is effectively replaced by whatever new definition is given in the first argument of Block, for the duration of the evaluation of Block only. If we give no definition, ...


39

In the days when computers were slower, and the kernel took a long time to start up (in wall time), a little package was made to help with cleaning up without having to restart the kernel. This package is still included with Mathematica, and is found in AddOns\ExtraPackages\Utilities\CleanSlate.m (within the Mathematica installation directory). It is more ...


39

Here is the simplest answer: sum[n_] := Sum[i x[i], {i, 1, n}] x /: D[x[i_], x[j_], NonConstants -> {x}] := KroneckerDelta[i, j] D[sum[n], x[2], NonConstants -> x] $\begin{cases} 2 & n>1 \\ 1-n & \text{True} \end{cases}$ The trick here is the use of the NonConstants option of the derivative operator. This then has to be combined ...


37

Rather than answering your question as posed, let me instead save you the effort of writing such a function and at the same time demonstrate how it can be done by posting some code that I've already written for this purpose: BeginPackage["CovariancePropagation`"]; Unprotect[var, cov]; ClearAll[var, cov]; SetAttributes[var, HoldAll]; SetAttributes[cov, {...


32

You cannot make definitions with patterns on the left-hand side in the first argument of a scoping construct (such as Module). You need do that in the body of the Module. You should also use a different symbol for the internal function parameter. norm[x_] := Module[{fun1, fun2}, fun1[p_] := p^2 + p - 1; fun2[p_] := p^3 - p^2 + p + 1; Max[...


29

Your code reveals exactly why Clear complains: Subscript[x, r] is not a Symbol nor a String. When you assign a value to it, you're setting a DownValue not an OwnValue; in other words, you're setting the value of a function not a variable. To use $x_r$ as a symbol, use the Notation` package's function, Symbolize. I'd recommend using it from the palette ...


28

An alternative that doesn't require protecting or using private contexts: Clear @@ DeleteCases[Names@"`*", "b"]; To keep a few (as suggested in comments) replace "b" with "b"|"g"|"h".


27

Superscript is not interpreted as Power: Presumably you are referring to what happens when you enter a power in superscript notation using the key combination Ctrl+6. Mathematica is capable of representing both this power notation and a formatted plain Superscript. In my opinion it is a failing that the power notation appears in the Typesetting menu while ...


26

As the error message indicates Clear does not work that way. There are several assignment forms that automatically create a definition to something other than a raw symbol: x[5] = 1; Subscript[x, 1] = 2; x /: Subscript[x, 2] = 3; N[x] = 3.14159; DownValues[x] DownValues[Subscript] UpValues[x] NValues[x] {HoldPattern[x[5]] :> 1} {HoldPattern[Subscript[...


26

Here is the almost obligatory timing response, it probably doesn't generalise very broadly but perhaps is indicative in some respects: (* no variables *) f1[x_] := (x^2; x^3;) f2[x_] := Module[{}, x^2; x^3;] f3[x_] := Block[{}, x^2; x^3;] f4[x_] := With[{}, x^2; x^3;] (* With variable definition *) f2[x_] := Module[{y = 0}, x^2; x^3;] f3[x_] := Block[{y = ...


26

You are looking for $NewSymbol which is run every time a new symbol is created. For example, let say you only want x, y, and z as symbols, then declare them initially In[63]:= {x, y, z} (*Out[1]= {x, y, z}*) Then, set $NewSymbol to issue a message when it is used, e.g. In[2]:= $NewSymbol::undeclared = "`1` was not previously declared."; In[3]:= $NewSymbol ...


25

There will no doubt be plenty of answers for this one. However the short answer is: Use With for local constants that you don't have to change subsequently. Use Module for local variables that are local to that piece of code. Use Block for local variables that are local to that sequence of evaluation. This tutorial in the Mathematica documentation ...


25

Below is something posted on Mathgroup by Jason McKenzie Alexander. I made a few tiny changes and corresponded about this with Jason for a short while. He sent me his final version, which I post here with his permission. The original (linked above) is really only a few lines of code and can be studied to grasp the principle. The code below is a full package. ...


25

Basic proposal There are a number of options and their attractiveness will depend on the scenario for their use, therefore it is difficult to make any broad recommendations of best practice. I will say that generally it is not recommended to rely on global assignments as in your first example, because this method scales poorly and because it is easy to ...


23

You could use capital Nu, \[CapitalNu], from the Greek alphabet. It is visually almost identical to capital N from the Roman alphabet. But it has no predetermined assignment. \[CapitalNu] = 5 2 \[CapitalNu] The following shows how the input is displayed on screen.


22

I will leave the explanation of the difference between lexical and dynamic to those more qualified than myself (and to the documentation). One practical difference between Block and Module is this: Module[{x}, x] Block[{x}, x] (* -> x$1979 x *) That is, if you construct something inside a Block with a blocked variable and then return it, you may use ...


22

I use a shortcut key Ctrl+Q for Quit[], allowing rapid clearing of all sessions variables. Here is how you can add this to Mathematica: You will be editing KeyEventTranslations.tr. This is an important system file so be careful. Start by copying the file you are going to edit from the $InstallationDirectory to $UserBaseDirectory in the same tree. This ...


22

$ is probably the only non-alphanumeric ascii character without a special meaning in Mathematica and thus the only one you could use as a delimiter for various parts within a variable name. A warning is due: Because it is so unique, it is also used internally for the same purpose, e.g. Module and Unique will generate variable names ending in $+ an ...


22

Actually we have direct control over this via a System Option. Set: SetSystemOptions["DefinitionsReordering" -> "None"]; Then: Clear[f]; f[x_] := Sin[x]; f[x_?EvenQ] := x; f[x_?OddQ] := x^2; {f[1], f[2], f[3], f[4], f[3/2], f[Newton]} {Sin[1], Sin[2], Sin[3], Sin[4], Sin[3/2], Sin[Newton]} Restore the default behavior with: SetSystemOptions["...


22

General The definitions get reordered at definition-time by a part of the pattern matcher, that takes care of automatic rule reordering. It does so, based on relative generality of rules, as far as it is able to determine that. This is not always possible, so when it can't determine which of the two rules is more general, it appends the rules to DownValues (...


21

You can explicitly define variables in the global context by prefixing their name with Global`, for example, Global`i = 3 or Global`f[x_]:=x^2. However if you have set the notebook to have private context, you don't have Global` in your $ContextPath (in order to prevent interference from other notebooks with non-private context). Therefore in your notebooks ...


21

This is a fairly natural question and I feel it is worthy of attention. I am going to answer in two parts. First, I am going to show a method that is more appropriate for Mathematica programming and which I recommend you use instead. Then I will show how to force the action you are attempting. Better Alternatives The common way to accomplish ...


21

For a single code statement, this is probably an overkill. If you have two or more of them, you have to group them in any case. CompoundExpression is one obvious choice, such as f[x_]:= ( Print[x]; x^2 ) Instead, you could also do f[x_]:= Module[{}, Print[x]; x^2 ] which is what I personally often prefer. Apart from some stylistic ...


21

This has been discussed on comp.soft-sys.math.mathematica. The gist is that there are lots of Unicode characters you could use, e.g. \[LetterSpace] or \[UnderBracket] (you could consult https://reference.wolfram.com/language/tutorial/LettersAndLetterLikeForms.html for a long list), but I'd strongly urge you not to do that. Once you copy the code out of ...


21

You asked for a general explanation instead of just focusing on specific application examples, so here it goes ... The concepts of "pass by reference" and "pass by value" that you may know from languages like C do not apply very well to Mathematica. Do not try to think in this framework. The right question is not "how to pass by reference/value", but how ...


20

I did some computation of formal derivatives a while back which might be of interest in this context (though keep in mind that this is anything but bullet proof! it does work for the cases I bothered to check though). Clear[a]; Format[a[k_]] = Subscript[a, k] Let us say we have an objective function which is formally a function of the vector a[i] Q = ...


Only top voted, non community-wiki answers of a minimum length are eligible