Using a built-in symbol as a variable

14

5

I want to produce a Mathematica Computable Document in which N appears as a variable in my formulae. But N is a reserved word in the Mathematica language. Is there a way round this other than using a different symbol? It seems a severe limitation if you cannot use Mathematica to generate papers in which N is employed as a variable.

Marc Widdowson

Posted 2012-06-22T10:32:24.893

Reputation: 141

Input and Output are different matters as far as I know. You might and should use defintions starting with a lowercase letter to be on the safe side regarding conflicts but that does not hinder you to format any output like you want it to appear? – gwr – 2012-06-22T10:37:22.990

1Writing up the paper and writing code to do the computations are two different things ... surely the name of the variable can't be that big an issue? Even in a CDF, the visual presentation doesn't need to match the underlying code. You can label stuff using $N$ even if in the code it's represented using a variable of a different name. – Szabolcs – 2012-06-22T10:44:52.337

2You can use \[FormalCapitalN] instead of N. It looks almost like N. – Artes – 2012-06-22T10:46:42.507

3...or \[ScriptCapitalN], or \[CapitalNu], or... why do you need $N$ to be a variable anyway? How sure are you that your paper won't need the actual functionality of N[]? – J. M.'s ennui – 2012-06-22T10:59:05.930

Here I'm giving you a gun to shoot your self. This is a bad idea. But of course everything is possible: Unprotect[N]; N=5; N*3 – Ajasja – 2012-06-22T11:06:03.147

2If you want to display an equation, you could work with n in intermediate steps and in the final display step do a replacement. /.n->"N" should be save – Sjoerd C. de Vries – 2012-06-22T11:13:53.963

7@Ajasja That's not a gun, that's a land mine. At least a gun has a safety catch. – Heike – 2012-06-22T11:32:50.287

1I think this question could be the flagship of all the similar questions about modifying built-in symbols, as it is rather concise and straightforward. There are other ways (like locally redefine symbols) which might worth a mentioning here. – István Zachar – 2012-06-22T12:11:57.520

Thank you very much to all the commenters for their very helpful suggestions. It's true, I don't need to use N as the variable name, but it is quite a common choice to stand for the number of something, e.g. the number of molecules in the kinetic theory of gases. The question applies if I wanted to give a formula incorporating the natural-seeming "N" as might be found in conventional textbooks, while also using Mathematica to differentiate it, plot it, etc. In the past, I have worked around by using a different symbol, but I wondered if there was another way. – Marc Widdowson – 2012-06-22T13:41:48.397

Related: (117)

– Mr.Wizard – 2016-09-06T20:17:51.250

Answers

23

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.

Nu

DavidC

Posted 2012-06-22T10:32:24.893

Reputation: 15 949

@J.M. Oops. I only read the comments after submitting my answer. Sorry. – DavidC – 2012-06-22T12:30:23.107

No apologies necessary; I upvoted your fine answer after all. :D – J. M.'s ennui – 2012-06-22T12:42:56.950

17

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 it is displayed could be completely different. You can use Format for example to give a specific formatting whenever n is printed:

Clear[n];
n[x_] := N[x/5];
Format[n] := Style["N", Red, Italic, Bold];

n

Mathematica graphics

n[12]

2.4

(Note, that since Format does not have attribute HoldFirst or HoldAll, n should not have any OwnValues, otherwise the assignment won't happen.)

István Zachar

Posted 2012-06-22T10:32:24.893

Reputation: 44 135

2I think for something this simple, where all that matters is the way something looks on output, Format is the best way to go. Though certainly several of the other suggestions are also viable. – Daniel Lichtblau – 2012-06-22T17:43:47.920

I would have used n /: MakeBoxes[n, form_] := With[{boxes = MakeBoxes[N, form]}, InterpretationBox[boxes, n]], personally. Bad experiences with Format. – Oleksandr R. – 2013-06-27T00:29:40.407

11

The methods suggested by David and István already do the job perfectly, but one could add something to the collection:

As described in the documentation on Operators without Built-in Meanings, there are some two-dimensional forms such as Subscript and UnderBar which can be re-defined to your liking. This is particularly useful if you need the 'N' with additional decorations anyway, such as $\text{N}_1$, $\text{N}_\text{total}$ or $\underline{\text{N}}$.

For these kinds of symbols you don't re-define N directly, but instead add a definition that is associated with the two-dimensional form in which the symbol appears. For example, I can set the following (note that the form Subscript["N", 0] can be entered more conveniently using keyboard shortcuts, but that wouldn't display so nicely here):

ClearAll[Subscript];

Subscript["N", 0] = 6

(* ==> 6 *)

7 Subscript["N", 0]

(* ==> 42 *)

DownValues[Subscript]

(* ==> {HoldPattern[Subscript["N", 0]] :> 6} *)

The last line shows how the definition is stored as a definition associated with DownValues[Subscript]. The fact that we get 42 from the multiplication shows that the definition of the subscript works as expected.

To erase the definition, I can either use ClearAll[Subscript] or more specifically

Subscript["N", 0] =.

The shortcut to input the subscript is to type "N" followed by Ctrl- and then 0.

You can also use strings in the subscript, instead of numbers. That allows you to get a "variable" that displays as $N$ without decoration by entering

Subscript["N", ""]

Again you could assign things to this subscripted form as well. Another use for a string subscript would be (here I'll copy the two-dimensional form in box notation, it should look nicer when copied into the notebook):

\!\(\*SubscriptBox[\("\<N\>"\), \("\<total\>"\)]\) = 100

(* ==> 100 *)

Sum[i, {i, 
\!\(\*SubscriptBox[\("\<N\>"\), \("\<total\>"\)]\)}]

(* ==> 5050 *)

Of course one can use these re-defined operators as a substitute for Format as well. For example, here is some symbolic input and symbolic output:

nn = Subscript["N", ""]

$\text{N}$

Sum[i, {i, nn}]

$\frac{1}{2} \text{N}_{\text{}}\left(\text{N}_{\text{}}+1\right)$

You can then keep working with nn as the symbolic variable for computations but get the capital $\text{N}$ in the displayed output.

But you can also do numerical substitutions in the usual way, as here:

% /. Subscript["N", ""] -> 100

(* ==> 5050 *)

(again, all the expressions looking like Subscript above can be made to appear more naturally by using the two-dimensional keyboard input methods).

Finally, everything I said here about Subscript also applies to things like UnderBar["N"] which displays as $\underline{\text{N}}$.

The Subscript combined with strings can also be useful when defining a whole set of similarly named variables automatically using something like this:

normalVector = 
 Array[Subscript["N", {"x", "y", "z"}[[#]]] &, 3]

$\left\{\text{N}_{\text{x}},\text{N}_{\text{y}},\text{N}_{\text{z}}\right\}$

Norm[normalVector] /. {
\!\(\*SubscriptBox[\("\<N\>"\), \("\<x\>"\)]\) -> 1, 
\!\(\*SubscriptBox[\("\<N\>"\), \("\<y\>"\)]\) -> 0, 
\!\(\*SubscriptBox[\("\<N\>"\), \("\<z\>"\)]\) -> 0}

(* ==> 1 *)

For even better formatting, you could replace normalVector by "N" Ctrl'7' escvecesc which displays as $\vec{\text{N}}$.

Jens

Posted 2012-06-22T10:32:24.893

Reputation: 93 191

7

Ok, I'm late here, but the first thing I would have answered hasn't been answered already.

If it's a one-cell-er, you can use Module

Module[{N}, 
 N = 8;
 N + 3]

This can never bring you trouble with internal definitions since that N you see is not actually N.

If it comprises multiple cells, you can use contexts, and interpret the RED N as a reminder that you're doing weird things. You can always access the regular N function by System`N, and return to normal by either Remove[N], or $ContextPath=Rest@$ContextPath

prvt`N;
PrependTo[$ContextPath, "prvt`"];

Rojo

Posted 2012-06-22T10:32:24.893

Reputation: 40 993

I thought about adding this, but the approach was already mentioned briefly by @István in the comments (+1). – Jens – 2012-06-22T16:59:04.953

@Jens, weird he hasn't put it in his own answer... – Rojo – 2012-06-22T17:02:12.797

6

There is actually an easy way to achieve this (almost) perfectly. Just start the variable name with a none printing character. I use this technique to have variables for atomic orbitals that start with numbers e.g. 3d or 4f - also not allowed by Mathematica. I just write the name as \[Null]3d. Mathematica is now fine with this as a variable. It works for \[Null]N or any other "protected" name. The output looks fine because the Null character doesn't take up space.

A variation is \[LetterSpace] - an almost-invisible space treated as a letter, e.g. in a symbol name - but it has a very faint bar showing

Peter Gorry

Posted 2012-06-22T10:32:24.893

Reputation: 61

3

The question of reassigning build-in Symbols has come up a number of times. There is an approach not yet posted here, however it is not recommended. Nevertheless for the sake of completeness I shall illustrate it.

Because N is not Locked it is not the more difficult example, as one can (perilously) Unprotect and redefine it. Instead I shall use I as it is Locked, and redefinition comes up from time to time.(1)(2)

It is possible to change the Context of a System Symbol, even a Locked one. Therefore:

Context[I] = "foo`";
System`I = 3;

E^(I*Pi) + 1 // N
12392.6

The original Symbol is still usable with a qualified context:

E^(foo`I*Pi) + 1
0

Functions that return Complex values still work:

out = FactorInteger[Prime[100], GaussianIntegers -> True]
{{-I, 1}, {10 + 21 I, 1}, {21 + 10 I, 1}}

Note the InputForm and FullForm of that output:

out // InputForm
{{-foo`I, 1}, {10 + 21*foo`I, 1}, {21 + 10*foo`I, 1}}
out // FullForm
List[List[Complex[0,-1],1],List[Complex[10,21],1],List[Complex[21,10],1]]

I think messing with System Context Symbols in this manner is a Bad Idea apart from a few specific cases(3) but I also think users should be aware of the full set of tools at their disposal and make individual decisions.

Mr.Wizard

Posted 2012-06-22T10:32:24.893

Reputation: 259 163

3

To continue with Ajasja's land mine theme, it's not so problematic to use N as a symbol in equations like this:

Mathematica graphics

as long as you keep the following in mind:

  • Don't try to use it in an assignment (because you can't)
  • Don't use [...] in its neighborhood, nor #&@
  • Keep it far away from Map, Apply, Fold, Nest etc.

But frankly, this probably isn't the best idea to go for. Land mines may be safer.

Sjoerd C. de Vries

Posted 2012-06-22T10:32:24.893

Reputation: 63 549