Tag Info

Hot answers tagged

40

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


34

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


33

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


25

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


17

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


17

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


14

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] Case #2 You must understand that pattern matching is done on something close to the FullForm of an expression, rather than the ...


14

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


12

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


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

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


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

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


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


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

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


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


8

For the first puzzle, I can only guess. The idea is that Function with named variables is a true lexical scoping construct, in that it cares about the possible name collisions inside the inner scoping constructs, including another Function-s (this is where it is different from Slot- based functions, which are not like that. The price to pay is that ...


8

Please let me know if this is moving in the right direction: expr = a + b*3*c + d; Replace[expr, h_[x___] :> {x}, {0, -1}] {a, {3, b, c}, d} Given that heads are lost here, perhaps you want something like: Replace[expr, h_[x___] :> {h, x}, {0, -1}] {Plus, a, {Times, 3, b, c}, d} If this is close to what you a related question that you ...


8

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]


7

Here is one possibility. Comparing patterns is a special case of comparing trees in general, so we need some specialized version of diff of Mathematica expressions. One way to build such a diff is to "serialize" expression into atomic elements and then compare the serialized forms. I will use slightly more complex patterns as examples: a = ...


7

Two variants: (* left-associative *) Hold[a, Times, b, Plus, c, Subtract, f] //. f_[a_, p_, b_, c___] :> f[p[a, b], c] (* Hold[(a b + c) - f] *) (* right-associative *) Hold[a, Times, b, Plus, c, Subtract, f] //. f_[c___, a_, p_, b_] :> f[c, p[a, b]] (* Hold[a (b + (c - f))] *) after which one can apply ReleaseHold[]...


7

As of version 9 this has changed http://reference.wolfram.com/mathematica/Compatibility/tutorial/Utilities/FilterOptions.html So this package needs to use FilterRules. I Downloaded this package, and changed Summa.m according to the above, and now it loads ok. Changed every place it said FilterOptions to Sequence@@FilterRules. Run few tests from the ...


7

Convert Maple expressions to Mathematica: Through latex: Through free form input:


7

You can forcely specify the condition to be True: Solve[x^2 + y^2 + x == 1, y, Reals] /. ConditionalExpression[e_, _] :> ConditionalExpression[e, True] {{y -> -Sqrt[1 - x - x^2]}, {y -> Sqrt[1 - x - x^2]}} But you should always keep it in mind that this is not an identical transformation.


7

E.g. using Cases: Cases[expr, _F, Infinity] {F[0, 0], F[0, 1], F[2, 0]} Note that the 3rd argument is the levelspec. See e.g. expr//FullForm why it's needed EDIT (I wasn't careful!) Note that this does not work for expr = F[0,0] as by default, Cases does not match the whole expression (it starts at level 1). If that could be the case, you can ...



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