# Tag Info

25

In Some Notes on Internal Implementation especially in Algebra and Calculus one finds interesting subtleties and differences between these two functions, e.g. The code for Solve and related functions is about 500 pages long. Reduce and related functions use about 350 pages of Mathematica code and 1400 pages of C code. There is much more than a ...

25

Not really a concise syntax, but you can also do this using Switch, which removes the need for writting the checking, and also allows patterns: fun[num_Integer] := Switch[num, 1, "Red", 2, "Orange", 3, "Yellow", _?PrimeQ, "Purple", _, "LightGray"] I used strings just to make the output nicer to verify the behavior. Naturally you would switch ...

24

Since version 8, Solve and Reduce share a great deal of code. In fact, by Specifying Method -> Reduce in Solve, Solve will use Reduce behind the scenes to produce an answer. Off the top of my head, the key differences are as follows: 1) Reduce simplifies logical statements, while Solve solves equations. This means that given a logical statement ...

23

For example you may do something like f[i_] := {Red,Orange,Yellow}[[i]] Edit You can easily add some robustness: f[l_List, i_Integer ] := l[[i]] /; 1 <= i <= Length@l; ll = {Red, Orange, Blue}; f[ll, 3]

21

Internal`InheritedBlock (IIB) is similar to Block, except that it preserves the original definition of the function being passed to it. The function can then be modified as we wish inside the IIB without affecting the external definition. Let's see how Block works first: f[x_] := x Block[{f}, Print@DownValues[f]; f[x_, y_] := x y; ...

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

20

Head can return any head. There is no predefined list. expr = myArbitraryHead[1, 2, 3]; Head[expr] myArbitraryHead A head does not even need to be a Symbol: expr2 = (2 Pi)[x, y, z]; Head[expr2] 2 π Most heads are shown explicitly in the FullForm of the expression: FullForm[{"a" + "b", 1/3}] Head /@ {"a" + "b", 1/3} List[Plus["a", "b"], ...

19

Do you mean CtrlShiftK? After typing Plo, press the key combination CtrlShiftK and a window will appear with possible options: As pointed by Yves，CtrlK will also work，but CtrlShiftK will work differently if you finish the function name. For an example, Type Plot3D; Use CtrlShiftK; Mathematica will show:

19

Taking a limit depends on the path used to approach that limit. Consider the function in the question: f[x_, y_] := Piecewise[{{x y / (x^2 + y^2), x != 0 && y != 0}}, 0]; base = Plot3D[f[x, y], {x, -1, 1}, {y, -1, 1}, MeshStyle->Opacity[0.2], PlotStyle->Opacity[0.5]] (A plot of its graph, saved here as base, appears in subsequent figures.) ...

18

Intro I will treat your question in a somewhat broader context of parameter-passing semantics in Mathematica in general. Many points of confusion here come from analogies and comparisons with more traditional languages, and it is important to realize that Mathematica uses entirely different (from most other languages) mechanisms for parameter-passing. ...

17

I assume that you have numeric values. A much more efficient way would be -Total[UnitStep[data] - 1]] or Total[1-UnitStep[data]] Note: While the second notation is certainly a bit more compact, it is about 35% slower than the double-minus notation. I have no idea why. On my system, it takes on average 0.22 sec vs 0.30 sec. Compare timings between the ...

17

Answer: Fixed in 9.0.1. 9.0.1 is a free upgrade for registered 9.0.0 users, and is available for download from the Wolfram User Portal. Explanation as to why/how it was busted. This is not something I would typically post at all. Not because I'm afraid to show how the sausage is made (for those who have the stomach), but more because it seems off-topic ...

16

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

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

16

Scoping constructs, lexical scoping and variable renamings It pays off to understand a bit deeper how the scoping constructs work and what happens behind the scenes when you execute one. In addition to the documentation, this was discussed in part here, but let us present some summary. When the lexical scoping construct Sc[vars, body] executes (where Sc ...

15

Due to insistent public demand: If, in a sequence of iterates $\{x,f(x),f(f(x)),\dots\}$, one only needs every $k$-th iterate (say, for $k=3$, you want $\{x,f(f(f(x))),f(f(f(f(f(f(x)))))),\dots\}$), then one can cleverly combine Nest[] and NestList[] like so: NestList[Nest[f, #, k] &, start, n] which yields a list containing the zeroth, $k$-th, ...

15

If you have a domain, you can often find a range using Interval. Examples: In[1]:= Sin@Interval[{0, 2 Pi}] Out[1]= Interval[{-1, 1}] In[2]:= Sin@Interval[{0, Pi}] Out[2]= Interval[{0, 1}]

15

The differences between using _Integer and _?IntegerQ as to efficiency, robustness and cleanliness in my view are: Efficiency _Integer is more efficient. It belongs to what @LeonidShiffrin calls syntactic patterns and the evaluator doesn't need to be called to check if the pattern fits. On the other hand, ? and /; require a call to the evaluator ...

15

I like more : MapThread[ And, {{True, True, False}, {True, False, False}}] {True, False, False} Edit We should test efficiency of various methods for a few different lists. Definitions Argento[l_] := (And @@ # & /@ Transpose[l]; // AbsoluteTiming // First) Brett[l_] := (And @@@ Transpose[l]; // AbsoluteTiming // First) Artes[l_] := ...

15

As belisarius already wrote, your problem is that you use the function before you define it. However I think there should be some further explanation. In most programming languages, function declarations are a compile-time feature. That is, during compilation (and yes, even languages like Perl or Python have a compilation step, it's just done right before ...

15

Best place is to make a package. But if you do not feel like it, you can put the definitions in the init.m file using init.m see http://reference.wolfram.com/mathematica/ref/file/init.m.html for more information on using init.m. From the above: "Possible locations for init.m files include the following:" \$BaseDirectory/Kernel kernel initialization code ...

14

I think this question admits an elegant solution. Here is my attempt: define a special wrapper: ClearAll[sortFun]; sortFun /: SortBy[expr_, sortFun[funs_List, partFun_]] := SortBy[expr, Map[Composition[#, partFun] &, funs]]; Now, mySort := {StringTake[#, 1] &, ToExpression@StringDrop[#, 1] &} and SortBy[{"T3","T14","T1","E2"}, ...

14

As Heike mentions in the comments, FromContinuedFraction[] does what you want: FromContinuedFraction[{2, 2, 1, 7, 1, 2, 2, 16}] 6784/2891 If FromContinuedFraction[] had not been built-in, however, something like this could be done: (* backward recursion *) Fold[#2 + 1/#1 &, Infinity, Reverse[{2, 2, 1, 7, 1, 2, 2, 16}]] 6784/2891 or even (* forward ...

14

There is an old trick used by many LISP implementations to deal with circular lists. That trick is based upon Floyd's cycle-finding algorithm and could be adapted to the task at hand. Here is nestUntilCycle, a function similar to Nest except that it stops when it detects a value that has been seen before: nestUntilCycle[f_, x_] := Module[{fast = x, more ...

14

Use _?Negative: list = RandomInteger[{-9, 9}, 30] Count[list, _?Negative] Your pattern will match an object with an explicit negative sign: Count[{a, -b, c, a, -a, a, -b}, -_] 3 You could combine the patterns to match either: Count[{-1, -2, 3, 4, -a, b, -c}, -_ | _?Negative] 4 Since this has become a speed competition (which is fine ...

14

I like Artes' and kguler's answers, but I'd like to point out that in general f @@ # & /@ list can be more concisely written as f @@@ list For example: And @@@ Transpose[{{True, True, False}, {True, False, False}}] (* {True, False, False} *)

14

One way to deal with "multiple inputs" to a function like NestList is to express the many inputs as a single vector. For example: f[{x_, y_}] := {x + y, x - y}; NestList[f, {100, 75}, 5] does what you are looking for {{100, 75}, {175, 25}, {200, 150}, {350, 50}, {400, 300}, {700, 100}}

14

I believe that the difference is that the Hash in v7 was hashing the quotation marks around the string, but the Hash in v8 does not. For example, in M7: In[1]:= Hash["test", "MD5"] Out[1]= 64111166190477440563271147919838643147 and in M8: In[1]:= Hash["\"test\"", "MD5"] Out[1]= 64111166190477440563271147919838643147 Therefore, I'd say that the M8 ...

14

Use a dispatch table. It is an optimized element -> value lookup table that can be used to replace an element any time with its value. Now it does matching-and-finding every time, but if your list is not too big, this is pretty fast. dispatch = Dispatch[Thread[elements -> chemistry]]; ratio[elemA_, elemB_, disp_] := (elemA/elemB) /. disp; ratio[elemA_, ...

14

Have a look at this; http://reference.wolfram.com/mathematica/guide/MathLinkCLanguageFunctions.html I haven't used it in C/C++ but it works fine in C# and Java. Basically you create a connection to a Mathematica kernel and then pass it native data types. Works nicely. Here is some sample code in Java that I used when I first did this; import ...

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