# Tag Info

## New answers tagged functions

6

This is pitched at the "how to understand" level, not the "how is it implemented" level. I've basically presented how I think of these things, without really caring about how Mathematica carries them out. The object h[2][x] is just another expression-with-head. The head is h[2], which just happens to have a more complicated form than is perhaps usual. In ...

1

Here are the modifications that need to be done on your plots h1 and h2 in order to flip them over the line y == x. If you look "under the hood" at the structure of these two plots by executing, for instance, FullForm@Normal@h1 you find that really there are only two objects, a Line and a Polygon. Both of these Heads take inputs which are lists of {x, y} ...

14

There are subtle differences between #& and Identity. If you pass more than one argument, Identity will complain and remain unevaluated, #& will just return the first argument. Identity[x, y] (* Identity::argx: Identity called with 2 arguments; 1 argument is expected. >> *) (* Identity[x, y] *) #&[x, y] (* x *) Also Identity is ...

6

To get the polynomial, the easiest way is res = M /. Rationalize@Solve[a == 0, M]; poly = res[[1, 1]][M] 900 + 14400 M^5 + M^4 (50400 - 8944 z) - 1909 z + M^3 (65700 - 27760 z - 14612 z^2) + M (9900 - 13690 z + 98 z^2) + M^2 (38700 - 30597 z - 14514 z^2 + 147 z^3) Now I don't know what Solve does, but I did the following. Take the numerator ...

7

I have used a method similar to your "dirty code" myself and I don't see an apparent alternative as Pattern requires a true Symbol for its first parameter. I will note that your Unique Symbols should be made Temporary, or you can generate them with Module to add this attribute automatically. And since you are trying things for fun you could use Map in ...

6

The first thing I came up with was: Permutations[l] The second thing I came up with was an inductive answer: perms[l_] := Flatten[With[{p = perms[Rest@l]}, Function[{n}, Insert[#, First[l], n] & /@ p] /@ Range[Length[l]]], 1] perms[{a_}] := {{a}} I can't think of a pattern-based one at the moment, but I'm sure there's a clever one.

2

The original version works just fine: Through[(f + Composition[Power[#,2]&, g])[x]] or, for MMA ver. 10 and above, Through[(f + (Power[#,2]&) @* g)[x]] result in (* f[x] + g[x]^2 *) Alternatively, you could do, from the beginning, Through[(f + (g[#]^2 &))[x]] which is perhaps a little easier to parse since it doesn't use Composition. ...

8

It is sometimes beneficial to first work with functions (in mathematical sense) as symbols and apply to them some pointwise operations. Then, just at the end, convert resulting expression to pure function (in Mathematica sense) and pass some arguments. This can be automated using something like this: ClearAll[purify] Options[purify] = {"FunctionPattern" ...

4

I'm probably missing an important point, but what is wrong with (f[#] + g[#]^2)&[x] f[x]+g[x]^2

6

You can achieve this defining an UpValue for g: g/:Power[g,2]:=g[#]^2& Or more generally: g/:Power[g,n_Integer]:=g[#]^n& Using Through now works as wanted: Through[(f + g^2)[x]] (*Out=f[x]+g[x]^2*)

3

I think it is best to approach these kinds of problems with pure functions, which minimizes nasty surprises from variable scoping issues. Let's see how well this idea works out when applied to your problem. Generate test data. With[{u = Range[-180., 180., 6.] Degree}, data = With[{x = #[[1]], y = #[[2]]}, {x, y, Sin[x] Cos[ y]}] & /@ ...

2

I contacted wolfram and what I needed to do was make sure that all my code was within the Manipulate and after defining my changing variables the rest of my code lies within a Initialization command. You also must have the Enterprise edition to make CDFs with DatabaseLink.

0

The free CDF player can not import data. That can only be done by the CDF player pro. Did you try to use SaveDefinitions->True within Manipulate? That should store the needed data for Manipulate inside the CDF.

2

SolveAlways can find coordinates of a polynomial with respect to any given basis. You set up an equation, setting the given polynomial equal to a linear combination of your basis polynomials. This approach will work generally with any polynomial that is a linear combination of a given set of (linearly independent) polynomials. poly = 1 + x + 3 x^2 + 7 ...

3

You should correct the typo in your code. I'm not even sure how this can happen, when you copied the example from your notebook. Additionally, you shouldn't use $\psi$ for both, a function and a variable. Once this is fixed: energyFunctional[ψ_] := Integrate[ 1/2 (D[ψ[x], x])^2 + 1/2*x^2*(ψ[x])^2, {x, -∞, ∞}]; ψ1 = (1/π)^(1/4) Exp[-(#^2/2)] ...

16

What's happening This is not simple by any means. You have encountered another instance of a general situation with lexical scope leaks / emulation / over-protection by symbol renaming. The case at hand is pretty similar to the one discussed here, so you can read the detailed explanation of this behavior in my answer there. Roughly speaking, outer lexical ...

4

The given above answer is correct, however if you are not against using undocumented functions, then InternalStringToDouble["9.0E-03"] is much faster. To demonstrate the speedup, first generate some fake data heads = ToString /@ RandomReal[{1.0000, 9.9999}, 100000, WorkingPrecision -> 5] // Quiet; exp = ConstantArray["E-", 100000]; tails = ...

4

Everything in Mathematica has a precedence, including semicolon! That is similar to 3+4*5 meaning the multiplication is done before the addition. So the way you have it written above says the definition of your calc function ends with your first semicolon and then your second Module will calculate a result without waiting for you to later use your calc ...

2

Not exactly the same, but very closely related is BitLength. BitLength[n] gives the number of binary bits necessary to represent the integer n. For positive n, BitLength[n] is effectively an efficient version of Floor[Log[2,n]]+1. For negative n, it is equivalent to BitLength[BitNot[n]] When is it not equivalent to nextpow2? It works for ...

2

You can use your knowledge of other generating functions to construct a new one. $\frac{1}{1-x} =1 + x + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^{10}+...+$ $\frac{1}{1-x^2} = 1 + x^2 + x^4 + x^6 + x^8 + x^{10} +...+$ You just want to zero every even exponent in the first gf so subtraction is indicated. ...

3

Your code can be much simplified. The following rewrite of your code works. wlines = {427.397, 431.958, 450.235, 557.029, 587.092, 605.613, 645.629, 665.223, 669.923, 681.311, 690.468}; wcal = {4.1989123474370302*^02, -5.3957450948852408*^-02, 6.7152505835315814*^-04, -8.6698204011228679*^-07, 5.5523712684399200*^-10}; g[x_] = ...

1

In answer to the comment about more general combining functions... vars = {X1, X2, X3, X4}; g[x1_, x2_, x3_, x4_] := (x1*x2 + x3)^x4; f[t] := Evaluate[g @@ (#[t] & /@ vars)]; Where g is specific form of the general 'combining function'. This could all be done in place without defining vars and g... f[t] := Evaluate[((#1*#2 + #3)^#4) & @@ (#[t] ...

4

Here are a number of one-liners that will define f ci = {X1, X2, X3, X4}; This first one is perhaps the easiest for_Mathematica_ newcomers to understand. Clear[f, t]; f[t_] := Evaluate[Sum[ci[[i]][t], {i, Length[ci]}]]; Definition[f] This one is pretty easy to understand too. Clear[f, t]; f[t_] := Evaluate[Plus @@ Through[ci[t]]]; Definition[f] ...

15

fibSequences[n_?EvenQ] := Nest[Accumulate[Join[{1, 0}, #]] &, {}, n/2] fibSequences[n_?OddQ] := Most@Nest[Accumulate[Join[{1, 0}, #]] &, {}, (n + 1)/2] fibSequences[10] {1, 1, 2, 3, 5, 8, 13, 21, 34, 55} fibSequences[9] {1, 1, 2, 3, 5, 8, 13, 21, 34}

5

Well... I did use Accumulate! First /@ NestList[{Last@#, Last@*Accumulate@#} &, list, 10] {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55} EDIT Of course I forgot to mention that list = {0, 1}

4

There was a wrong bracket in F. Also do not use { as a normal bracket, and second you wrote Exp{[ which has to be either {Exp[ or (Exp[ . F[k1_, k2_, λ1_, λ2_, δ_, w1_, w2_] := (1 - Exp[-(w1/λ1)^k1]) (1 - Exp[-(w2/λ2)^k2]) (Exp[(1 - (1 - Exp[-(w1/λ1)^k1]))^(-δ) + (1 + (1 - Exp[-(w2/λ2)^k2]))^-δ]^(1/-δ))

4

I can illustrate what is going on with a simpler function than yours. Consider f[x_, y_] := Sum[y[[i]], {i, Length[x]} Then f[{"a", "b"}, {3, 4}] gives 7 as expected, but f[x, y] /. {x -> {"a", "b"}, y -> {3, 4}} gives 0, just as your function did. Now /. is infix operator version of ReplaceAll, so the above is equivalent of ReplaceAll[f[x, y], ...

2

I think what you want is something like this: Conjugate[f[x_, y_, z_]] ^:= cf[x, y, z] Derivative[d__][cf][x__] := Conjugate[Derivative[d][f][x]] D[Conjugate[f[x, y, z]], x] Conjugate[Derivative[1, 0, 0][f][x, y, z]] All I did here is to define the derivative of the function f to be another function cf which then can be given the property you want. ...

2

The answers received made me cogitate a lot these last two days and I came up with a solution based on Riffle: All the graphics directives are stored in a table, each entry in that table corresponding to a path of the figure drawn . These paths are in a table supplied to the unique built-in drawing the figure (ie Line, Polygon....) here BezierCurve. The ...

4

see comment below by OleskandrR If he posts I will up vote. Original post This is not ideal (and done with little time) but may motivate better answers. Note this manually (visually tries to minimize the discontinuity at "breakpoint") using Manipulate. The NonlinearModelFit treats the breakpoint as fixed so you can play and chose better way. I look forward ...

7

Similar comments on recursion. The expression you create looks like this: TreeForm[orig, VertexLabeling -> None] Building it, e.g., like this gives you a flat structure: new = Table[ Rotate[ Line[AnglePath[{{-0.7, -0.7}, (-Pi/6)}, {{2, (7 \[Pi])/8}, {2, \[Pi]/8}, {2, (7 \[Pi])/8}, {2, \[Pi]/8}}]], i*Pi/5, {0, 0}], {i, 10}]; Such ...

4

In your examples you choose one color to begin with and then you pass that color onwards to each of the following leaves through recursion. Just like you have to apply Rotate in each step to change the angle, you also have to apply an operator that changes the color. For example: next[{_, leaf_}] := {RandomColor[], Rotate[leaf, Pi/5, {0, 0}]} g1 = ...

0

Basically the thing i realized is that, as it was pointed out by Timothy: ArcTan[x+I y] != ArcTan[x, y] == Arg[x+I y] You can try it out with numerical values and you'll see 1!=2==3. N[1/(2 \[Pi]) ArcTan[1/2 + I Sqrt[3]/2]] N[1/(2 \[Pi]) ArcTan[1/2, Sqrt[3]/2]] N[1/(2 \[Pi]) Arg[1/2 + I Sqrt[3]/2]] and you get 0.125 + 0.1048 I 0.166667 ...

1

Another thing to look at is the difference between = and :=. For example, if you define your first function as f[a_, t_, c_] := Sum[c[[i]] Exp[-(a - t[[i]])^2], {i, 1, 3}] then you get no warnings and you can evaluate f[a, {t1, t2, t3}, {c1, c2, c3}] as you wish. You can also take derivatives D[f[a, {t1, t2, t3}, {c1, c2, c3}], a] without any ...

2

Here is some food for thought f[a_, t_List, c_List] /; Length @ t == Length @ c := Plus @@ MapThread[(#1 Exp[-(a - #2)^2]) &, {c, t}] f can be used as a numerical function or to generate symbolic expressions. The clause /; Length @ t == Length @ c enforces the constraint that the vectors t and c must have the same length. f[a, {t1, t2, t3}, {c1, ...

1

Use IntegerDigits to produce binary digits of some base 10 integer, 11 in the following example. IntegerDigits[11,2] (* {1,0,1,1} *) Then use rules to convert each digit to the corresponding matrix, and form the dot product. Apply[Dot,IntegerDigits[11,2]/.{0->e,1->d}] Alternatively, select the appropriate matrix from a list. ...

2

You may try "Putting constrains on patterns". Mathematica provides a general mechanism for specifying constraints on patterns. All you need do is to put /; condition at the end of a pattern to signify that it applies only when the specified condition is True. You can read the operator /; as "slash-semi", "whenever" or "provided that". Example: ...

5

Possibly you want the Import format "HeldExpressions": Import["test", "HeldExpressions"] {HoldComplete[A = {1, 2, 3, 4, 5}], HoldComplete[B = {1, 4, 9, 16, 25}], HoldComplete[Attributes[C] = {NHoldAll, Protected}]} The last expression may not be as you expect until you remember that C is a reserved System Symbol. Sorry, I overlooked the fact ...

4

The local i does not evaluate in the first table of functions; e.g. Table[# f[i] &, {i, 1, 10}] gives... {#1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &, #1 f[i] &} Use With to force the evaluation of i... Table[With[{i = i}, # f[i] &], {i, 1, 10}] to ...

10

Let's start by looking at the code for SequenceCases: << GeneralUtilities PrintDefinitions[SequenceCases] We can see in this code that three different conditions determine whether the expression will be evaluated by sequenceCasesSublist or sequenceCasesPattern. Let's evaluate the two tests that matter on {a_?PrimeQ, b_, c_?PrimeQ} and {a_?PrimeQ, ...

2

My one shot at answering this question: Attributes[convert] = {HoldFirst}; convert[def_Symbol?ValueQ] := With[{old = def, pats = Quiet[Sequence @@ Cases[Variables @ def, s_Symbol :> s_]]}, ClearAll[def]; def[pats] := old; ] Test: positionPayload = 2. x + 3. t^2; convert[positionPayload] ?? positionPayload Global`positionPayload ...

3

You might try something like this, which makes pure functions, which means the variables used int the expression to converted only have to be clear at time expToF is called. expToF[exp_, vars : {_Symbol ..}] := With[{body = exp /. Thread[Rule[vars, Slot /@ Range @ Length[vars]]]}, Function[body]] Clear[x,t] f = expToF[2. x + 3. t^2, {x, t}]; f[x,t] ...

4

Not that I would recommend this, but anyway: positionPayload = 2. x + 3. t^2; variableList = Variables[positionPayload]; positionPayload = Function[Evaluate@variableList, Evaluate@positionPayload]; positionPayload[q, r] (* 3. q^2 + 2. r *) Edit positionPayload = 2. x[1] + 3. t[3]^2; variableList = Variables[positionPayload]; ul = ...

2

positionPayload = 2. x + 3. t^2 (* 3. t^2 + 2. x *) variableList = DeleteDuplicates[Variables[positionPayload]] (* {t, x} *) temp = positionPayload; positionPayload =. Evaluate[positionPayload @@ (Pattern[#, Blank[]] & /@ variableList)] := Evaluate@temp Definition@positionPayload (* positionPayload[t_, x_] := 3. t^2 + 2. x *) positionPayload[q, r] (* ...

6

I notice no one is using an association to map to positions nor allowing the sort to use a one-element heap instead of building up an entire sorted array ... PositionIndex[#] @@ TakeSmallestBy[#, Times @@ # &, 1] & [ Transpose[{list1, Reverse@list2}] ] In the example, the result is {14}, the index of 15 in list1 that gets paired with 1 ...

7

First@Sort[{Times @@ #, #} & /@ Transpose[{list1, Reverse@list2}]] (* {15, {15, 1}} *) The first number is the minimum of the multiplications (15), which was obtained from multiplying (15) from list1 by (1) from list2. The following: Sort[{Times@##, ##} & @@@ Transpose[{list1, Reverse@list2}]] // First also performs the same thing. If you want ...

6

Here is a somewhat verbose and strange way of getting your answer: Function[{x}, {#, list1[[#]], x[[#]]} & @@ Ordering[x, 1]] @ Times[list1, Reverse@list2] Times[list1, Reverse@list2] gets your third list. This function: Function[{x}, {#, list1[[#]], x[[#]]} & @@ Ordering[x, 1]] takes Times[list1, Reverse@list2] as the argument x. Ordering[x, ...

1

Subtract @@ {a, b} (* a - b *)

Top 50 recent answers are included