Tag Info

145

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

42

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", ... 38 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 ... 36 Maybe this ? ClearAll["Global*"] 34 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, ... 30 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 ... 30 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 ... 29 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 ... 24 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 = ... 24 An alternative that doesn't require protecting or using private contexts: Clear @@ DeleteCases[Names@"*", "b"]; 23 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 ... 22 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} ... 22 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 ... 21 You can explicitly define variables in the global context by prefixing their name with Global, for example, Globali = 3 or Globalf[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

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

20

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 ... 20 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 ... 19 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 ... 19 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. 19$ 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 ... 19 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 ... 18 In V10, another option is to use Association. par=<|"mu"->1,"sigma"->1,"lb"->0,"ub"->10|>; f[x_, p_Association:par] := PDF[LogNormalDistribution[p["mu"], p["sigma"]], x] Plot[f[x, ##], {x, #lb, #ub}] &@par Another form for Plot is: Plot[f[x, par], {x, par@"lb", par@"ub"}] And as @Mr.Wizard commented, you can use the default ... 17 Automatic way based on Names Here is a simple modification of the recent answer of @R.M, which is based on the definiton of a variable as a symbol which has an OwnValue defined: Clear @@ Select[ Names["Global*"], ToExpression[#, StandardForm, Function[sym, OwnValues[sym] =!= {}, HoldAll] ] & ] If your code is in ... 17 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; ... 17 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. ... 17 General considerations To my mind, the only robust way to do this is to build some custom object model in Mathematica, and in particular to restrict the way values can be changed to some well-defined route you can control. Because, as it follows from one of the discussions you linked to, there seems to be no reliable way to intercept arbitrary value changes ... 17 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: ... 16 You can't define an unassigned symbolic variable throught itself. You are trying to do something like that: x = F[x] This is not right for symbolic computations, because x evaluates to itself as a pure symbolic value. Your code in FullFrom is: Equal[v, List[Subscript[v, 1], Subscript[v, 2], Subscript[v, 3]]] So, you get the recursion. Try different ... 16 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 ...

16

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