# Tag Info

62

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

27

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

23

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

21

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

18

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

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

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

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

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 ... 15 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} ... 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 ... 13 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 ... 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$ 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 ... 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 ... 11 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 ... 11 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 ... 11 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] <> ... 11 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. ... 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. 10 If we are the ones writing the package in question, then we could proceed as follows. First, we define a public version of the function that delegates all calls to a private version: ClearAll[publicFn] publicFn[args___] := privateFn[args] Then we define the functionality we desire on the private function: ClearAll[privateFn] privateFn[x_] /; x < 0 := ... 10 I don't think that there is any deeper reason for using Module[{},body] instead of just (body). Technically you are only adding overhead, as small as it might be. From the stylistic point of view I think it just adds complexity, increases what has to be read and -- as your question clearly indicates -- raises questions and adds uncertainty. I don't see any ... 10 As Rojo notes, defining f/: Subscript[f,1][x_] doesn't work as f is too deep in the expression, however you could define your function in two steps to avoid tying the definition to Subscript. f /: Subscript[f, n_] := subs[f, n] subs /: subs[f, n_][x_] := g[x] This has the problem that Subscript[f,1] for instance will turn up in output as subs[f,1] rather ... 10 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 ...

10

General considerations It often does make sense to use global variables inside your package. And sometimes, you simply can't avoid that. By global here I mean variables which are defined outside any function. There are two distinct cases here: A variable is defined in the Private subsection of the package and not exported as a part of the package's ...

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