# Tag Info

74

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

28

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

27

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

22

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

20

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

19

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

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

17

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

17

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.

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

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

16

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 ... 15 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 ... 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 ... 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 ... 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 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 ... 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 ... 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 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 As Leonid already pointed out in comments, it only seems that you set a variable t' here, but your assumption is wrong. Never use ' appended to a variable to define another distinguishable variable! The ' has the built-in meaning: It expresses the derivative of t. You can see this by using FullForm which gives you the full Mathematica expression used ... 12 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 ... 12 Perhaps what you're looking for is something like this: Module[{x, a, b}, x[1] = 1; x[2] = 10; a + b/x[2] + x[1] ]$\text{a$\$$3026}+\frac{\text{b\$$3026}}{10}+1$ Here I defined a single additional local variable x but then refer to "indexed" variables sharing the same name and differing only in the index x[1] and x[2] etc. These indices are ...

12

This seems to be a very easy way to bite yourself in the foot (non-flexible programmers this is not for you). I also have the habit of doing those blocked set-based definitions. It's probably time to change the habit now. It seems to me that SaveDefinition extracts the definitions of the symbols required by the Manipulate, as you entered them. If you used ...

11

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

11

Here are some options: Lists of Rules A simple option would be to return a list of rules: $someone = {"name" -> "Fred", "gender" -> "Male", "age" -> 25}; Fields can then be extracted thus: "name" /.$someone (* "Fred" *) "age" /. \$someone (* 25 *) Wrapper Patterns A variation on this theme would be to define a pattern that represents a new ...

11

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

10

You could also use something like OverVector, since OverVector[v] = {Subscript[v,1],Subscript[v,2],Subscript[v,3]} isn't recursive, and so won't cause problems. This takes a bit more effort to input Type Ctrl+& and then Esc vec Esc to enter directly but if you're interested in the typeset forms it might be worth it.

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