50

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


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


38

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


34

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


32

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


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

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


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

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


24

You can also use Refine with Element : Refine[Sqrt[2] Conjugate[Sqrt[1/L]] Sin[(Pi* Conjugate[n x])/Conjugate[L]], {Element[L, Reals], Element[n, Integers]}] gives and if you add that L>0: Refine[Sqrt[2] Conjugate[Sqrt[1/L]] Sin[(Pi* Conjugate[n x])/Conjugate[L]], {Element[L, Reals], Element[n, Integers], L > 0}] Other simple examples : 1. ...


23

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


23

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


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


21

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


21

I think the documentation needs to be more clear on this; the order of definitions is important: Remove[plus] Attributes[plus] = {Orderless}; plus[x__Integer, y__Real] := x + y plus[2.5, 3] 5.5 So the Orderless attribute must be active at the time the definition is created. Noteworthy is that definitions made before setting the attribute can cohabit ...


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


20

You can use any built in operator modified with subscripts, superscripts, etc, and retain its precedence, for your own purposes. For example, say you want a general Apply operator like @@ that could work at any level. One could use create the operator @@ with a number subscripted for the level of Apply seems appropriate MakeExpression[RowBox[{fun_, ...


20

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


20

In general, it is good practice to include i among the local variables. Table does not localize its variable (or, as some say, it only localizes the value but not the variable). It is relatively safe to leave i unlocalized when variables only have numeric values, like in fun. But the same is not true when variables can have symbolic values, e.g.: fun2[x_]...


20

Why is this happening The explanation was basically given by ciao in comments. You can also find a lot of information on this in this great answer of Mr.Wizard. I will perhaps try to view it from a somewhat different perspective. To understand what happens, one should go back and consider what happens when we enter and execute some code. The steps are ...


19

You almost have found a simple solution: try x[i] instead of x[[i]] Solve[{x[1] + x[2] == 2, x[1] - x[2] == 1}, {x[1], x[2]}] {{x[1] -> 3/2, x[2] -> 1/2}} List of this variables: Array[x,2] {x[1], x[2]}


19

If you wrap your definitions in Once then their results will be remembered across sessions: f[0] = Once[Print["a"]; {10, 20, 30}, "Local"] Here the printing and the numbers {10, 20, 30} are used instead of a lengthy calculation that you only want to do once and whose result you want to remember in the next session. On the first execution, the above code ...


18

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

I think that "elegant" should be syntax as close to the normal handling of symbols as possible. I shall define a function, unimaginatively named bump, that has a syntax similar to Part but which allows operations on symbols by way of Unevaluated and UpSet. If you will consider other storage formats besides Hold[v1, v2, ...] e.g. Hold @ {v1, v2, ...} this ...


17

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.


17

Use Symbol to convert a string into a symbol... Table[Symbol["$x" <> ToString@i], {i, 5}] {$x1, $x2, $x3, $x4, $x5} One word of caution. I tend to keep programmatically generated variables prepended with a $ to avoid any collisions with any other variables I might've defined. Just from experience.


16

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


16

According to the documentation of Clear or ClearAll it is possible to provide symbols in form of regular expression (limited), in particular as string with exact symbol name. Clear @@ {"width", "long", "line", "distance"} Let's say there is no possibility to do that, one way would be: Map[Clear, ToExpression[{"width", "long", "line", "distance"}, ...


16

I will make no attempt to defend the fact that Mathematica simulates scoping by means of variable renaming. However, the behaviour that we see is consistent with the principles under which Mathematica does operate. Whenever Mathematica tries to interpret a symbol name, it first checks to see whether a symbol with that name already exists in a package in ...


15

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


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