Tag Info

Hot answers tagged

45

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


39

Generally, you want the Trott-Strzebonski in-place evaluation technique: In[47]:= f[x_Real]:=x^2; Hold[{Hold[2.],Hold[3.]}]/.n_Real:>With[{eval = f[n]},eval/;True] Out[48]= 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 ...


37

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


32

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: In[3]:= Hold[{1, 2, 3, 4, 5}] /. n_Integer :> RuleCondition[n^2, OddQ[n]] Out[3]= Hold[{1, 2, 9, 4, 25}] RuleCondition differs Condition in that the replacement expression is ...


22

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


18

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


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

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


16

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


16

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


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] *)


13

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


13

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


12

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


12

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


12

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


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

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`" &}, ...


11

You can convert any expression to string by using ToString. If you want to preserve the visual representation, you should use ToString[(*your expression*), StandardForm]. logo = Import["http://wolfram.com/favicon.ico", "Image"] logostr = ToString[logo, StandardForm] StringJoin["Mathematica", logostr] % // StringQ Edit: By checking the cell expression ...


10

One way to induce Mathematica to simplify to Tan functions is to introduce the arguments as inverse tangents, as in $x\equiv \arctan a$ and $y\equiv \arctan b$. Then you could write for example Simplify[ TrigExpand@Tan[ArcTan[a] + ArcTan[b]]] /. {a -> Tan[x], b -> Tan[y]} (* ==> (Tan[x] + Tan[y])/(1 - Tan[x] Tan[y]) *) or more generally with ...


10

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[#, ...


10

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]


9

Here is a way to separate your equation into different subparts. It uses Reap and Sow to tag parts of the expression as either "equation" or "conditions" or "constants". f = Which[FreeQ[#, x], Sow[#, "constants"], MemberQ[{Equal, Unequal, Greater, GreaterEqual, Less, LessEqual, And, Or}, Head[#]], Sow[#, "conditions"],True, Sow[#, ...


9

Just do the ComplexExpand after the Conjugate ComplexExpand[Conjugate[I Cos[z] Sin[y] + Sin[z] + A (Cos[z] - I Sin[y] Sin[z])]] (* A Cos[z] + Sin[z] - I (Cos[z] Sin[y] - A Sin[y] Sin[z]) *)


9

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


9

The following functions will load the expressions and erroneous cells from a notebook: notebookExpressions[path_, pattern_:_] := Cases[Import[path, "Notebook"] // First , c:Cell[_, "Input"|"Output"|"Print", ___] :> Module[{v = eval[c]}, v /; MatchQ[v, _$Failed | Hold[pattern]]] , Infinity ] eval[cell_] := Quiet @ Check[ ...


9

res1 = data /. Plus -> List {a, b c, -d e f} res1[[2]] /. Times -> List {b, c} As a function: explodeOp[expr_, op_] := expr /. op -> List Then: res1 = explodeOp[data, Plus]; explodeOp[res1[[2]], Times]


8

Since you get the result in terms of Piecewise, you can use things like Refine or Simplify, particularly when you want to get a result given some additional condition on your variables. In particular, Refine[PDF[LogNormalDistribution[1.75, 0.65], x], x > 0] (* ==> (0.613757 E^(-1.18343 (-1.75+Log[x])^2))/x *)


8

Perhaps you will find utility in Format and related functions? Unprotect[Pochhammer]; Format[Pochhammer[k_, n_]] := HoldForm[ Gamma[k + n]/Gamma[k] ] Protect[Pochhammer]; Pochhammer[a, b] Gamma[a + b]/Gamma[a] Similar things can be done with $PrePrint: $PrePrint = # /. Pochhammer[k_, n_] :> HoldForm[ Gamma[k + n]/Gamma[k] ] &; ...



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