Tag Info

Hot answers tagged

101

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


29

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


28

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


26

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


24

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


23

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


21

Maybe this ? ClearAll["Global`*"]


20

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


20

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


20

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


18

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


18

An alternative that doesn't require protecting or using private contexts: Clear @@ DeleteCases[Names@"`*", "b"];


18

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.


17

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


17

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


17

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


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

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


15

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


15

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


15

For reading you can just use SetDelayed (:=). For writing you can define an UpValue for Set thus: mydata = {3, 14, 15, 92, 65} alice := mydata[[1]] alice /: Set[alice, value_] := mydata[[1]] = value Then for most purposes this will work as I expect you want it to: alice = alice*2; mydata {6, 14, 15, 92, 65} Even though it's already rather ...


15

You can give the function one of the Hold Attributes. SetAttributes[fun, HoldFirst] Then as Leonid suggested fun[var_] := SymbolName[Unevaluated@var] Without the hold attribute, this will not work.


14

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


14

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


13

I will suggest a solution for DownValues - based definitions, but it may be generalized to other types of definitions as well. I will only consider a case of a single symbol, but again, the generalization is rather straightforward. You will also have to execute your code in a special dynamic environment. A first ingredient of my suggestion is a (slightly ...


13

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


13

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


12

Does the following work as needed? CreateDialog[ TabView[ {"General" -> Column[{Row[{"Project Name:", InputField[Dynamic[project]]}], Row[{"Number Of Wells:", InputField[Dynamic[num]], Button["Set", DialogReturn[num]]}]}], "Row Selection" -> Dynamic@Column[ Table[Row[{"Well " <> ToString[i] <> ...


12

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


12

As it is often voiced here, modifying built-in variables is not a good idea most of the times, especially in case of such fundamental symbols as N. It is used heavily through millions of underlying code lines, and you will never know where your change can (and will) cause any mischief (or catastrophe). On the other hand, the name of the variable and the way ...



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