Hot answers tagged

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


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


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


11

y = a[b, c][d]; y[[0, 0]] = w; y (* w[b, c][d] *)


11

For arbitrarily nested heads I would use recursion and pattern matching, like this: ClearAll[replaceFirstHead] replaceFirstHead[head_[body___], newHead_] := replaceFirstHead[head, newHead][body] replaceFirstHead[head_, newHead_] := newHead replaceFirstHead[a[1][2][3][4, 5, 6], x] (* x[1][2][3][4, 5, 6] *) There is no need to test for _Symbol or _?AtomQ ...


11

The two examples in this question relate to two different aspects of pattern matching. I will start with the simpler to understand and intentional aspect, which is the second example. g[2] /. g[ 1 + (1|other) ] -> post (* g[2] *) In the above, the pattern doesn't match, and it can never match. g[2] has one argument. Since Plus is OneIdentity, 2 ...


11

My offering: And @@ Or @@@ Outer[Equal, {x, y, z, m}, {2, 3, 4}]


10

f[m_] = 1/(2*E^((-m + Log[5])^2/8)*Sqrt[2*Pi]); Integrate[f[m], {m, -Infinity, Infinity}] 1 dist = ProbabilityDistribution[f[m], {m, -Infinity, Infinity}]; Since the integral of f[m] is unity, f[m] does not have to be scaled to be a distribution. A candidate distribution will probably have two parameters and must be defined on the interval {-...


10

ClearAll[a, b]; a := 1 + 1 b = Sqrt Is this acceptable? foo = # /. Join @@ Cases[#, s_Symbol :> OwnValues[s], ∞, Heads->True] &; foo @ Hold[a + b[c]] Hold[(1 + 1) + Sqrt[c]] Update As OP has noticed I've missed the fact that ReadProtected symbols won't show its OwnValues. We could do something like s_Symbol /; FreeQ[ Attributes[s], ...


9

I think you've found a bug in pattern matcher. This problem can be reduced to matching sequence of length one with named BlankSequence patterns in Orderless functions, it stopped working in v10.1. In previous versions your replacement rule works (as noted by belisarius). Minimal example of this behavior is: ClearAll[f, a] SetAttributes[f, {Orderless}] $...


9

Well, the following meets your formal requirements evenFunction[f_][args__] := f[Abs /@ Unevaluated[args]] evenFunction[even][a, b, c] even[Abs[a], Abs[b], Abs[c]] But is it really better than evenFunction[f_][args__] := f @@ Abs[{args}] I, myself, would choose the 2nd version over the 1st. Update It is not necessary to set the attribute ...


9

This is a bug I fixed in 10.4.0. Sorry for the inconvenience! To work around it in earlier versions, evaluate the following block of code: InactiveDump`assembleInactiveSumProduct[{args_, disp_, interp_, char_, tag_, tooltip_, fmt_}] := TemplateBox[args, tag, DisplayFunction -> Function[disp], InterpretationFunction -> Function[interp], ...


8

I think an acceptable solution is to Thread over Alternatives: Basic solution: SetAttributes[f, Flat]; f[a, b, c] /. Thread[f[a, f[b, c] | other], Alternatives] -> post post Though, it won't be very helpful in more complex situations: f[a | b, f[b, c | h]]. General solution (experimental) tupplesOver[ f[a | g, f[b, c | h] | other], ...


8

This question is closely related to: How to remove redundant {} from a nested list of lists? How to completely delete the head of a function expression If you wish to strip the brackets from a single expression in a nontrivial case please consider Delete as described in my answer to the second referenced question above. Unlike using Apply (e.g. # & ...


7

There seems to be a subtlety in the way delayed rules are used. Have a look at the following: {a,a,a} /. a/;(Print["lhs evaluated"];True) :>(Print["rhs valuated"]; RandomReal[]) (*lhs evaluated lhs evaluated lhs evaluated rhs evaluated rhs evaluated rhs evaluated *) (* {0.797753,0.567294,0.91182} *) This shows that when we use a delayed ...


7

I believe this is what $PrePrint is for, since you only want to affect how the expression looks, and I'm guessing you want it to happen automatically for every input. Using $PrePrint thus allows you to use Out[n] without worrying about the held expressions. This seems to work (but I would like to find a better way to take care of the signs between terms in ...


7

In this example, I am assuming that the structure of your expressions will always be similar to your input: input = a*b*c + Cos[x - y]; The method below is not exactly general. First remove the outer-most Plus: list = List @@ Expand[input] (* {a b c, Cos[x - y]} *) We then Map Apply over the list while being careful to avoid those expressions which ...


7

This is related to the Orderless attribute of Times and Plus. These attributes could be removed permanently with some hacks, but that would break Mathematica. If you only want to display the result in a certain way, but not do calculations with it, it may be safe to remove those attributes temporarily using Block. Block[{Plus, Times}, With[{result = Z.B.A}...


7

What I think you want: S = {s1, s2, s3}; x = {1, 2, 4, s1, y}; Intersection[x, S] Outputs: {s1} As for # see http://reference.wolfram.com/language/tutorial/PureFunctions.html For your edited question: set = {s1, s2, s3}; x = {1, 2, 4, s1, y, f1[s1], f2[s2]} p = Alternatives @@ set; Cases[x, p | _[p]] {s1, f1[s1], f2[s2]} Reference ...


6

The following appears to be what you want. repl[expr_, max_] := With[{largest = Max[Cases[expr, C[n_] :> n, Infinity]]}, If[largest <= max, expr /. (R[C[largest], anything__] :> R[C[largest], anything].(II + R[C[largest + 1], C[largest]])) // repl, expr] ] repl[myExpr, 7] Alternative formulation if recursion doesn't float ...


6

Update In the interest of simplifying the code somewhat, I've modified one of the replacements. For instance, we can do expr2 = Thread[expr1, Plus] /. Plus -> Times or epxr2 = expr1 /. expT[Plus[a__]] :> Times @@ expT /@ a rather than expr2 = expr1 //. {expT[a_ + b_] :> expT[a] expT[b]} So: f[expr_] := Thread[expr /. Power[E, a_] :> ...


6

You don't say explicitly how you want to handle terms of order zero. Assuming that these are also to be discarded expr = a x^3 + b x^2 + c x + d; minOrder = 2; coefList = CoefficientList[expr, x]; lenCoefList = Length[coefList]; Expand[(Expand[x*expr] /. ((x^n_ /; n > minOrder) -> $t^n) /. {x -> 0, $t -> x})/x] (* b x^2 + a x^3 *) ...


6

One can use Operate[] with Apply[]: Operate[w @@ # &, a[b, c][d]] w[b, c][d]


6

It is not completely clear to me what form the output is intended to take. Recommend that you always give examples of both inputs and corresponding outputs. S = {s1, s2, s3}; x = {1, 2, 4, s1, y, f1[s1], f2[s2], f1[s1 + s2], f2[f1[s1] + s3]}; DeleteCases[x, _?(FreeQ[#, Alternatives @@ S] &)] (* {s1, f1[s1], f2[s2], f1[s1 + s2], f2[s3 + f1[s1]]} *)


6

As it was mentioned in the question and in the comments this is fairly easy to program. eqs = {Y == a + b X, Z == 1/X + Y}; edges = Flatten@ Map[Outer[Rule, Cases[{#[[2]]}, s_Symbol /; Not@NumericQ[s], \[Infinity]], Cases[{#[[1]]}, s_Symbol /; Not@NumericQ[s], \[Infinity]]] &, eqs] (* {a -> Y, b -> Y, X -> Y, X -> Z, Y -&...


5

You can executive the code in mma 10 or above version EntityClass["WolframLanguageSymbol", "Atomic"]//EntityList But is not all atomic function,as I know.


5

This is indeed somewhat confusing when you are new to Mathematica. In Mathematica, == stands for mathematical equality. Thus a == 0 does not evaluate to either True or to False until a is replaced by a numerical value. a is considered to be a variable that may or may not be zero. A pattern like x_ /; condition will only match if condition is explicitly ...


5

Defining a function like Clear[FactorByVariable] FactorByVariable[p_,c_]:=c Expand[p/c] will be one of the simpler options. The argument p is the polynomial you wish to factor from and c is the variable you wish to factor out. I think the reason you can't get your desired result with something like FactorTerms[a x + b x^2 + c x^3,{a,c,x}] is because ...


5

One possibility that comes to mind is using UpValues (nice SE post explaining it). If I understand you right, you basically want this: phi /: phi[a__] * phi[b__] = psi[a, b] phi /: phi[a__]^2 = psi[a, a] where you basically tell Mathematica that if phi appears anywhere, it should look in what context it is -- i.e., in a product or a square -- and ...


5

Your misunderstanding of how Part works has nothing to do with comma, which is simply a delimiter (arguably the only delimiter Mathematica has). The documentation is correct when it says "expr[[i, j, ... ]] or Part[expr, i, j, ...] is equivalent to expr[[i]][[j]]... " providing the indices i, j, .. all represent integers. In Part, the position of the indices ...



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