Hot answers tagged

49

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


33

General usage Here is what I think Using strings and subsequently ToString - ToExpression just to generate variable names is pretty much unacceptable, or at the very least should be the last thing you try. I don't know of a single case where this couldn't be replaced with a better solution Using subscripts is also pretty bad and should be avoided, except ...


33

We can use the Ramer-Douglas-Peucker algorithm to reduce the number of points. This algorithm was originally devised for processing map data. reg = BoundaryDiscretizeGraphics[ Text[Style["S", FontFamily -> "Verdana", FontWeight -> Bold]], _Text] poly = First@reg["BoundaryPolygons"]; pts = SimplifyLine[First[poly], 0.02]; Graphics@{EdgeForm[...


29

So recently I've learned from John Fultz that RawBoxes are kind of verbatim indicator for MakeBoxes which is not well stressed out in documentation. This or I've missed the point but it doesn't matter, here we have handy way to do this: x = 5; ToExpression @ MakeBoxes[RawBoxes["x"] = 123]; x 123


29

An alternative that doesn't require protecting or using private contexts: Clear @@ DeleteCases[Names@"`*", "b"]; To keep a few (as suggested in comments) replace "b" with "b"|"g"|"h".


28

The answer is quite simple. Most people want to multiply numbers without having to use the * symbol, e.g. 3x vs 3*x. So given that this exists in Mathematica, using () for function arguments would introduce ambiguity. Is f(x + y) meant to be f[x + y] or f*(x + y)? This is actually a problem Wolfram|Alpha can face since we try to allow for all forms of ...


28

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

Executing Trace on an expression reveals what is actually happening: Trace[Remove@x; x = 1] (*{Remove[Removed[x]];Removed[x]=1,{Remove[Removed[x]],Null},{Removed[x]=1,1},1}*) "the Wolfram Language always reads in a complete input expression, and interprets the names in it, before it executes any part of the expression." (see: https://reference.wolfram.com/...


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 use String "keys" for indexed variables, as I did for A combination of Set::setraw and Set::shape errors. The strings can have spaces or any other characters you want to use: var["Degree of the First Polynomial"] = (* stuff *); You also have a wide range of characters, many of which can be used in Symbol names. Go to menu Palettes > Special ...


22

You are missing Unevaluated: SetAttributes[f, HoldFirst] f[x_] := {SymbolName[Unevaluated@x], x} because SymbolName does not hold its arguments, so you have to prevent evaluation also there. Generally, if you are passing some argument via a chain of function calls, and want to keep it unevaluated, you have to prevent it's evaluation at each stage (...


20

The short answer is don't do it. Really, it's just not a good idea. You can use other symbols, such as \[CapitalIota] which looks almost exactly like I and is entered with EscIEsc. If you're really determined you could substitute symbols using $PreRead and MakeBoxes but again I don't recommend it. For example: MakeBoxes[I, _] := "\[ImaginaryJ]" ...


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

I mentioned this in a comment, but I believe this might really be the correct answer to your specific inquiry about underscore. You can escape underscore (Esc+_+Esc or Ecs+ls+Esc), which will give you a \[LetterSpace], which looks like underscore but is slightly lighter. This is just treated like a regular old letter and you can therefore use it in variable ...


19

Max[StringLength@Names["System`*"]] 38 Select[ Names["System`*"], 38 == StringLength[#] &] {"MultivariateHypergeometricDistribution"} As far as I can say there is no limit for lengths of symbol names, besides that of the memory limitation.


19

You can use EntityValue to find out what symbols can be atomic: EntityValue[EntityClass["WolframLanguageSymbol", "Atomic"], "CanonicalName"] {"AggregationLayer", "Association", "Audio", "BasicRecurrentLayer", "BatchNormalizationLayer", "BooleanFunction", "BoundaryMeshRegion", "ByteArray", "CatenateLayer", "ColorProfileData", "Complex", "...


18

If you look at the generated code (CompilePrint, for example), the procedure is as follows: All the program's constants are placed into separate registers (regardless of their location in the program, they can be in the r.h.s.of variable initialization in scoping constructs, or they can be statements in their bodies. Actually, same constants found in ...


16

Although your question is stated clear, I'm still wondering whether you understood, that Subscript[\[Theta], 1] is not a symbol. It's a box-structure! Therefore, what you do when you assign it a value like is, that you don't assign a value to some indexed variable x. No, you assign a value (a DownValue) to Subscript Let's assume I can guess that you ...


16

No need to use *CharacterCode[] : letters[n_] := CharacterRange["a", "z"][[;; n]] letters[3] (* {"a", "b", "c"} *)


15

The definitions aren't being lost, they're being shadowed, as described in the tutorial on contexts. Mathematica doesn't warn you about this because it only warns when there is shadowing between contexts that are listed in the $ContextPath. Since Begin only changes $Context and not $ContextPath, you don't get a warning when the symbol that causes shadowing ...


14

Here is the formatting command that does this: pvB /: MakeBoxes[pvB[n1_, n2_, x_, s_, m0_, m1_], TraditionalForm] := RowBox[{SubscriptBox["B", RowBox[{Sequence @@ Riffle[Table["0", {n1}], "\[ThinSpace]"], "\[ThinSpace]", Sequence @@ Riffle[Table["1", {n2 - n1}], "\[ThinSpace]"]}]], "(", Sequence @@ Riffle[Map[ToBoxes, {x, s, m0, m1}...


14

Edit: method extended for multiple contexts and unlocking mehtod added. Let's protect whatever is a new symbol. In old answer I've manually excluded symbols matching name$digits but that wasn't necessary as according to $NewSymbol details: $NewSymbol is not applied to symbols automatically created by scoping constructs such as Module. BeginPackage["...


13

The * multiplication operator is rendered in InputForm: c = a b; c // InputForm a*b For producing/exporting strings: ExportString[c, "Text"] ToString[c, InputForm] "a*b" "a*b"


13

Extract all Greek letters from the documentation and make replacement rules: nb = Get @ FileNameJoin[{$InstallationDirectory, "Documentation", "English", "System", "Tutorials", "LettersAndLetterLikeForms.nb"}]; letters = Cases[nb, StyleBox[s_String, "TR"] :> s, {-2}]; letters = DeleteCases[letters, "π" | "∈"]; (* reserved Symbols *) names = ...


13

Cloud symbols are stored in cloud objects (under $CloudSymbolBase) and local symbols are stored in local objects (under $LocalSymbolBase), which can be addressed using CloudObject and LocalObject respectively. DeleteFile can be used for both cloud and local objects, for example DeleteFile[CloudObject["MySolution", $CloudSymbolBase]] DeleteFile[...


13

It's a type of otherwise harmless bug that tends to come and go with versions. I would suggest to report it to Wolfram, but also not to worry about it. Notice that the symbols have no associated definitions, which means that they will not interfere with your code. A potential way in which such a situation can arise is the following. Imagine you put Sqr[x_] ...


13

This usually means you've exported a local symbol from the context in which it was localized. Consider: Module[{x}, x] (* x$24939 *) Your results may vary. The Module localizes x to avoid conflicting with any previous definition. x$24939 is just another symbol similar to x, but with $24939 added to its name to insure that there's no confusion with any ...


12

The problem is that WhenEvent has the attribute HoldAll, so var is never translated to y. Here's a standard trick to inject the actual value of var into the code: var = y; Reap[NDSolve[{y''[x] == -y[x], y[0] == 1, y'[0] == 0, WhenEvent[Round[#[x], 0.1] == 1, Sow[x]]}, y, {x, 0, 10}]]&[var] (* Out: {{{y->InterpolatingFunction[{{0.,10.}},<>...


12

In Mathematica version 10, you can also use Inactive to allow the Symbol to be created before doing the assignment. Here is an example: Clear["x"]; Activate[Inactive[Set][Symbol["x"], 3]] (* ==> 3 *) x (* ==> 3 *)


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