Hot answers tagged syntax
20
In addition to Brett's counter-example, it might be helpful to view this from Mathematica's philosophy, which is "everything is an expression". In this framework, you're not really indexing a 1D/2D array, but you're extracting a Part from an expression.
Indeed, you can use the ⟦ ⟧ notation on any expression, not just lists/matrices. For example:
Sin[x + ...
20
It is a good habit to get into because you can often get tripped up by precedence rules (no one remembers everything!). For instance, PatternTest binds very tightly. See the difference between these two definitions:
Clear@f
f[_?(# == 2 &)] := Print@"foo"
f[_] := Print@"bar"
f[2]
(* "foo" *)
Clear@g
g[_?# == 2 &] := Print@"foo"
g[_] := Print@"bar"
...
17
To programmatically find the internal representation of the shortforms, you can use MakeExpression, which gives the result wrapped in HoldComplete. Here's an example:
MakeExpression@"?name"
(* HoldComplete[Information["name", LongForm -> False]] *)
MakeExpression@"??name"
(* HoldComplete[Information["name", LongForm -> True]] *)
17
It is probably debatable to what extent it has built-in object oriented features.
In any case, this answer is not intended to lead you to try to emulate object oriented programming, which is in general a bad idea. (see @Leonid 's answer)
However, it is not debatable that Mathematica is tremendously flexible (as to style and notation at least, the evaluation ...
16
No.
For example, functions do not have to be atomic. It can be possible to extract parts from them (although it's generally not recommended.)
In[1]:= if=Interpolation[Range[10]^2]
Out[1]= InterpolatingFunction[{{1,10}},<>]
In[2]:= if[3]
Out[2]= 9
In[3]:= if[[3]]
Out[3]= {{1,2,3,4,5,6,7,8,9,10}}
16
I like to use Ctrl+. to discover how it's grouped. For example, in this example:
Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ColorFunction -> Hue[#] &]
Putting your cursor position after & and pressing Ctrl+. two times, you will get all expression ColorFunction -> Hue[#] marked, so it's wrong, and you need to put () like this:
Plot3D[Sin[x y], ...
15
A second list argument to Flatten serves two purposes. First, it specifies the order in which indices will be iterated when gathering elements. Second, it describes list flattening in the final result. Let's look at each of these capabilities in turn.
Iteration Order
Consider the following matrix:
$m = Array[Subscript[m, Row[{##}]]&, {4, 3, 2}];
$m ...
15
As explained by Michael Pilat you cannot create your own compound operators with custom precedence. (You could conceivably write your own parser as Leonid has worked on, or attempt to coerce the Box form with CellEvaluationFunction.)
You can however use an existing operator with the desired precedence. Looking at the table Colon appears to be a good ...
15
At the risk of repeating myself, I would like to stress that one has to be critical towards the superficial flexibility offered by Mathematica, when (particularly mutable) data structures are concerned. Using mutable data structures assumes a programming style for which Mathematica is not optimized. It can emulate it, yes, and we have seen a number of such ...
14
OK, the verbal description isn't very easy, but I'll try:
This is a simulation showing how the attractive forces between 21 spheres cause them to aggregate. Instead of simulating the equations of motion, the Dynamic approximates the physics of the attractive force and the repulsive core in the somewhat artificial body of Function[{x}, ...].
Its argument x ...
12
The reason is that the notation base^^digits is interpreted at parsing time, not evaluation time. I explained the difference in this answer.
You can use FromDigits instead:
fromBaseTwo = FromDigits[#, 2]&
fromBaseTwo["10011"]
Note that I used a string as input. FromDigits works both with strings and lists of digits.
12
The solution using SetDirectory / ResetDirectory, given by @celtschk, is perfectly valid. However, personally I try to avoid this method, since you have to be sure that no other piece of code resets the directory during your operations.
Here is an alternative method. There are two cases we can distinguish here:
You are talking about various .m files, into ...
11
Look at CompoundExpression :
Button["Click Here", Print[10!]; Print[11!]]
"Click Here"
when clicked it performs two actions
3628800
39916800
11
R.M chose PatternTest as an example but I find that subtly misleading. PatternTest is highly unusual because it binds tighter than [ ], meaning x_?head[arg] parses as (x_?head)[arg], but even without this behavior the parentheses would be needed.
In your own example the parentheses are unnecessary and, being a fan of terse coding, I suggest you leave them ...
11
The short answer is that Sequence[] expands already inside the If[ ... ] because If does not have the SequenceHold attribute. If[False, <<something>>] (i.e. missing third argument) will evaluate to Null.
Just use
Table[If[PrimeQ[k], k^2, Unevaluated@Sequence[]], {k, 1, 20}]
11
The reason can be learned by inputting the following:
?func
This outputs the values currently assigned to your function func:
Global`func
func[1]=Null
func[2]=Null
func[y_]:=func[y]=Print[Hello world !!!]
When a function is evaluated that only prints, it assigns it a value of Null which is remembered by the memoization. The documentation covers ...
11
In some languages Print behaves like the identity function. But as noted, Print in Mathematica returns Null.
I want to make clear what is going on with the memoization idiom, for those who might be confused by it. I know I didn't really understand it at first.
func[y_] := func[y] = Print["Hello world !!!"];
This is clearer if it's written like this:
...
11
# is a placeholder for an expression.
If you want to define a function, $y(x)=x^2$, you just could do:
f = #^2 &
The & "pumps in" the expression into the # sign. That is important for pairing & and # when you have nested functions.
f[2]
(* 4 *)
If you have a function operating on two variables, you could do:
f = #1 + #2 &
So ...
11
It is of course possible to redefine functions within loops in Mathematica. You are actually just missing a semicolon at the right place for your code to work as intendend:
For[i = 1, i <= 5, i++,
f[x_] := Sin[x]^2;
Print[{i, f[i]}]
]
It's probably worth noting (as Jacob did in his comment) that the semicolon is just a shortcut for a ...
10
The reason is that since version 6 of Mathematica, the Plot returns its output just like any other function. It does not print is as a side effect. Do is meant to be used with operations that have side effects and simply discards the output, so you never see the plot.
You can either use Table, which collects the values in a list:
Note how you get a ...
10
References and intro
First, let me point out that = is shorthand for Set and := for SetDelayed; this facilitates searching the docs. Also, as Simon Woods points out in a comment to the question, there is a tutorial on this.
Explanation
The basic distinction is this: y[x_]=expr means evaluate expr, then whenever you see y[something] evaluate evaluate what ...
9
You're not committing a blasphemy. In fact, you're defining an upvalue to your own symbol, so you're in the safe zone.
I think your idea of using upvalues was a good one.
Alternatives are, to define your own parsing function such as
SetAttributes[it, HoldFirst];
it[Table[expr_, {var_, start_, end_, num_Integer}]]:=
Table[expr, Evaluate@{var, start, ...
9
Actually, there is one way to make mesh lines with variable colors: if you specify lists with equal number of elements for both, MeshFunctions and MeshStyle, then each of the styles in MeshStyle gets applied to the corresponding mesh lines specified in MeshFunctions.
This fact can be used in a multitude of ways, and specifically for this question we can get ...
9
You can get the syntax highlighting that you desire by modifying your UnicodeCharacters.tr file, though I don't know how advisable this practice is.
For example, adding:
0x20B0 \[PennyOp] ($penny$) Infix 155 None 5 5
I can use EscpennyEsc to enter:
I am not aware of documentation of the format of this file but as ...
9
I think you only forgot a comma. Try:
For[i = 1, i <= 5, i++, {f[x_] := Sin[x]^2, Print[{i, f[i]}]}]
this gives your desired output.
If I were you, I would not define a function in a For Loop (can be time consuming). And, if possible, I would work with a Table because this works faster too.
So do something like:
f[x_] := Sin[x]^2;
Table[{i, f[i]}, ...
8
As often happens here, the comment provides the answer, but here's the answer from Stephen Wolfram's book about Mathematica (the second edition of "Mathematica, a System for Doing Mathematics by Computer" which I bought for £0.01 on Amazon):
Mathematica uses both upper- and lower-case letters. There is a convention that built-in Mathematica objects ...
8
This is not really ideal, but it gets you most of the way there:
SetAttributes[makeSuperscript, HoldAllComplete];
makeSuperscript[sym_Symbol] := (
sym /: MakeBoxes[sym, form_] = With[{name = SymbolName[sym]},
InterpretationBox[SuperscriptBox[name, "\[Prime]"], sym]
];
sym
);
makeSuperscript[q]
(* -> InterpretationBox[SuperscriptBox["q", ...
8
While the tutorial will undoubtedly explain better that I could the entire topic of pure functions, which is what Slot, or # has to do with, I'll answer the specific question at hand.
The Slot is treated as the argument in an anonymous function. Specifically, the code
#^2 & // FullForm
Reveals that what is actually going on is ...
8
Sequence means more or less "no head". What you want to do is to remove the head List from an inner list. Or, put in another way, you want to replace this head with "no head". The operation that changes one head to another is Apply. Therefore, what you really want is
f[a, b, c, d, Sequence @@ array]
where @@ stands for Apply.
8
Your python idiom can be implemented in Mathematica using Part and Span as:
Range[10][[-1;;1;;-1]]
(* {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} *)
which is very similar to your python command, and doesn't require you to unprotect either Span or Part.
Only top voted, non community-wiki answers of a minimum length are eligible


