# Tag Info

55

Generally, you want the Trott-Strzebonski in-place evaluation technique: f[x_Real]:=x^2; Hold[{Hold[2.],Hold[3.]}]/.n_Real:>With[{eval = f[n]},eval/;True] (* Hold[{Hold[4.],Hold[9.]}] *) It will inject the evaluated r.h.s. into an arbitrarily deep location in the held expression, where the expression was found that matched the rule pattern. This is ...

51

Point #1 Part always wraps element sequences with the original head of the expression. expr = Hold[1 + 1, 2 + 2, 3 + 3, 4 + 4, 5 + 5]; expr[[{2, 3}]] Hold[2 + 2, 3 + 3] For this purpose a single part e.g. 1 is not a sequence but {1} and 1 ;; 1 are: expr[[1]] expr[[{1}]] expr[[1 ;; 1]] 2 Hold[1 + 1] Hold[1 + 1] This applies at every level ...

48

RuleCondition provides an undocumented, but very convenient, way to make replacements in held expressions. For example, if we want to square the odd integers in a held list: Hold[{1, 2, 3, 4, 5}] /. n_Integer :> RuleCondition[n^2, OddQ[n]] (* Hold[{1, 2, 9, 4, 25}] *) RuleCondition differs from Condition in that the replacement expression is evaluated ...

44

You can use custom transformation rules, for example: -11 - 2 x + x^2 - 4 y + y^2 - 6 z + z^2 //. (a : _ : 1)*s_Symbol^2 + (b : _ : 1)*s_ + rest__ :> a (s + b/(2 a))^2 - b^2/(4 a) + rest returns (* -25 + (-1 + x)^2 + (-2 + y)^2 + (-3 + z)^2 *) The above rule does not account for cases where b is zero, but those are easy to add too, if ...

41

These three functions are similar (speaking commonly), and in some applications any of them could be used, yet they have very different special applications. Rudimentarily: Map wraps (sub)expressions in a given Head, and returns the modified input Apply replaces Heads in (sub)expressions, and returns the modified input Scan "visits" (sub)expressions, ...

24

Ah well... this is not robust, but probably of educational value and useful as a starting point for other postprocessing needs on Graphics or Graphics3D expressions: p = Plot[Sin[x], {x, 0, 1}] col = Cases[p, _Hue, Infinity][[1]]; Show[p /. col -> Red] Update: As pointed out by matheorem, Version 10 switched from Hue to RGBColor, so the ...

24

Case #1 Observe: "anything" /. Plus[___] -> "match" "match" This is because Plus[___] evaluates to ___, and ___ matches anything. You can use HoldPattern: Sqrt[Plus[x, y]] /. HoldPattern[Plus[___]] -> u Sqrt[u] For this particular case you could also use the form _Plus, which matches any expression with head Plus but not Plus itself: ...

23

Although less magical, it can be done by ReplacePart expr = Hold[{2, 3, 4, 5}] pos = Position[expr, _Integer] newparts = Extract[expr, pos] /. n_Integer :> n^2 ReplacePart[expr, Thread[pos -> newparts]]

22

I already answered this question on StackOverflow but since old questions can no longer be migrated without undue trouble I shall reproduce my answer here. There are two different categories of graphical objects in a Plot output. The plotted lines of the functions (Sin[x], Cos[x]) and their styles are "hard coded" into Line objects, which Graphics can ...

20

You can actually Delete the head of the expression, which is part 0: Delete[#, 0] & /@ {Cos[a], Sin[b], Tan[c]} {a, b, c} With version 10 operator forms: Delete[0] /@ {Cos[a], Sin[b], Tan[c]} {a, b, c} One case of interest may be held expressions. If our expression is: expr = HoldComplete[2 + 2]; And the head we wish to remove is Plus, ...

19

I thought of this question while on the train but the solution appeared in my brain as soon as I got into work. All you need to do is create a ComplexityFunction that includes a side effect f[x_] := (Print[x]; LeafCount[x]) Simplify[TrigExpand[Tan[x + y]], ComplexityFunction -> f] This gives the following output (Cos[y] Sin[x])/(Cos[x] Cos[y]-Sin[...

19

One way would be to redirect all messages issued by ToExpression to a string-stream. Here is an example of that approach, with minimal error-checking: Needs["Developer"] interpret[str_String] := Module[{s = StreamToString[], r, m} , Block[{\$Messages = {s}}, r = ToExpression[str, InputForm, HoldComplete]] ; m = StringFromStream[s] ; Close[s] ; &...

18

That's an interesting first question. Welcome. :-) From a simplistic perspective this should work, but as you observe there are evaluation properties that are more complex. Here is a reference for most (but not all) behavior: The Standard Evaluation Sequence Let's follow those steps for your example. Heads are evaluated first Evaluate the head h of ...

17

Implementation The following implementation is based on expression serialization and SequenceAlignment built-in function. The idea is to break expressions into constituent parts, then align these part sequences, and then determine the positions where the expressions are different. The auxiliary heads we will need are inert heads diff and myHold, the latter ...

17

I assume you have Maple to use. If so, Simply open Maple and type the Mathematica command itself directly into Maple using the FromMma package built-into Maple, like this: restart; with(MmaTranslator); #load the package (*[FromMma, FromMmaNotebook, Mma, MmaToMaple]*) and now can use it FromMma(Integrate[Cos[x],x]); One can also use Maple convert ...

17

The following seems to work, however I think it's not general enough: At a clean nb, enter: For[i = 0, i < 4, i++, Print[{i, {33, i}}]] For[i = 0, i < 4, i++, Print[Graphics[Circle[], ImageSize -> 20]]] And then retrieve the Print[ ] output as: c = Cases[NotebookRead /@ Cells[GeneratedCell -> True], Cell[___, "Print", ___]]; ToExpression /...

15

Assuming you don't have any built-in symbols in that list, you could simply do: DeleteDuplicates@Cases[Leff, _Symbol, Infinity] (* {da, ma, dm, mc, La, h, R} *) If you do have symbols from built-in contexts or packages, you can simply pick out only those that are in the Global context with: With[{globalQ = Context@# === "Global`" &}, ...

15

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

14

You may try for example something like: f[e_] := 100 Count[e, _Pochhammer, {0, Infinity}] + LeafCount[e]; FullSimplify[Pochhammer[k, n], ComplexityFunction -> f] (* ->Gamma[k + n]/Gamma[k] *)

14

Perhaps only the developers (or Leonid) can answer #1 and #3 and "why". The quick answer to #2 is Apply, remembering that List is a Head like any other: List @@ (a + b + c) {a, b, c} On #3, I can't explain why ;; syntax gives 0 when (a + b + c)[[Range[0, 3]]] gives a + b + c + Plus So you could try List @@ ((a + b + c)[[Range[0, 3]]]) ...

14

#1 Trott-Strzebonski in-place evaluation: hf = HoldForm[1 - 1^2/2 + 1^3/3 - 1^4/4 + 1^5/5 - 1^6/6] hf /. x_Times :> With[{eval = x}, eval /; True] 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 Replace[hf, x_ :> With[{eval = x}, eval /; True], {2}] 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 One may simplify this method using the undocumented function ...

14

Distribute @ Sum[-2 Subscript[x, i] (-a Subscript[x, i] - b + Subscript[y, i]) // Expand, {i, n}] == 0

14

Yes. It turns out that Normal accepts an undocumented second parameter which may be a Symbol or a list of Symbols and it will only affect those forms. Plain application converts all these forms (and more): abby = { SparseArray[{3 -> "a", 5 -> "b"}], <|1 -> "a", 2 -> "b", 3 -> "c"|>, Series[Exp[x], {x, 0, 5}], Quantity[1, "...

13

Here's one way to count the number of multiplications in an expression (equal to or greater than the number of Times in the expression). It should also work for several other binary operators, Listable or not (although I haven't tested it on them). t[x_, oper_: Times] := Tr @ ((Length[#] - 1) & /@ (Extract[x, {Sequence @@ Drop[#, ...

13

You can use Normal, ConditionalExpression is not explicitly mentioned there but documentation says it deals with special forms. p1 = y /. {First[Solve[x^2 + y^2 + x == 1, y, Reals]]} // First ConditionalExpression[-Sqrt[1 - x - x^2], 1/2 (-1 - Sqrt[5]) < x < 1/2 (-1 + Sqrt[5])] Normal @ p1 -Sqrt[1 - x - x^2]

13

As far as I know, there is no easy, general way to handle this kind of algebra with Sum expressions. What follows is an attempt to use replacement rules to handle a wider range of cases than chris's example. I don't consider it to be the canonical answer that is required, but perhaps someone might be able to use it as a starting point. I use Inactive on ...

13

UPDATE: quite interesting parallel discussion and solutions (see Emerson Willard answer) can be found HERE. Maybe this is not exactly what you are looking for, but at least this gives you a very close guess and it is easy to figure out the rest. dis = ProbabilityDistribution[ 1/(2*E^((-m + Log[5])^2/8)*Sqrt[2*Pi]), {m, -Infinity, Infinity}]; PDF[dis, ...

13

You can use Series to specify the order of approximation. When an expression involving the output of Series, which is a SeriesData object, is evaluated, the calculus is done for you. sol = Solve[x^2 + (b + Epsilon)*x + c == 0, x] approx = sol /. Epsilon -> Series[Epsilon, {Epsilon, 0, 1}] // Normal Alternatively, you could apply Series to the ...

11

Preamble After seeing no use of Mathematica (Code Jam Language Stats) in previous contests, I realized Mathematica is not allowed because there is no free version This is only to some point correct. Matlab is allowed too and is of course not free and very expensive. I was helping a friend of mine in round 2 and we weren't even close to good. Partly ...

11

This is a rather simple-minded approach, but maybe it will be useful to you: ClearAll[opCount]; opCount[h_, expr_] := Cases[ Hold[expr], HoldPattern@h[args : _ ~Repeated~ {2, Infinity}] :> Length@Hold[args] - 1, -2 ] // Total; SetAttributes[opCount, HoldRest]; Let's try: opCount[Times, 1*2*3*4*5 + 6*7*8] (* -> 6 *) opCount[Plus, 1*2*3*4*5 + ...

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