Hot answers tagged function-construction
11
It is of course possible to redefine functions within loops in Mathematica. You are actually just missing a semicolon at the right place for your code to work as intendend:
For[i = 1, i <= 5, i++,
f[x_] := Sin[x]^2;
Print[{i, f[i]}]
]
It's probably worth noting (as Jacob did in his comment) that the semicolon is just a shortcut for a ...
10
A little bit more. Still not fully diagnosed, but the problem isn't due to DSolve
... :
s1 = DSolve[{x'[t] == f*x[t] (1 - (x[t]/b)) - l x[t]}, x[t], t];
s2 = DSolve[{x'[t] == e*x[t] (1 - (x[t]/b)) - l x[t]}, x[t], t];
And the problem shows up when matching the initial condition:
Solve[(x[t] /. s2[[1]] /. t -> 0) == 4/10, C[1]]
(*
{{C[1] -> ...
9
Something along the lines of Rotate[Line[pts], angle, Mean[pts]]:
g = Graphics[Line[{{1, 1}, {2, 2}}]];
rot = l : Line[pts_] :> Rotate[l, Pi/2, Mean[pts]];
Show[g, g /. rot]
I believe that Rotate and family are Graphics/Graphics3D directives which are only processed when they are rendered. If you need to access actual rotated values of the points, ...
9
I think you only forgot a comma. Try:
For[i = 1, i <= 5, i++, {f[x_] := Sin[x]^2, Print[{i, f[i]}]}]
this gives your desired output.
If I were you, I would not define a function in a For Loop (can be time consuming). And, if possible, I would work with a Table because this works faster too.
So do something like:
f[x_] := Sin[x]^2;
Table[{i, f[i]}, ...
8
This is perhaps a place to start:
position[expr_, level_: 1] :=
With[{positionData =
SortBy[
#[[1, 1]] -> #[[All, 2]] & /@
GatherBy[Extract[expr, #, Verbatim] -> # & /@ Position[expr, _, level], First],
Min[Length /@ #[[2]]] &
] // Dispatch},
Replace[#, positionData] &
]
The second argument controls the ...
7
This is a case for injector pattern:
PassByOption[opts : OptionsPattern[]] :=
OptionValue["List"] /. Hold[l_] :> CheckboxBar[Dynamic[l], Range@Length@l]
You can check that this works with this change.
As an alternative, you can by-pass the use of Hold and clever tricks like the above, by using the longer form of OptionValue:
...
6
In those more complicated cases consisting of multiple steps, using Composition clears things up for me while still retaining a pure functional style. In your example of calculating the distance between two points in 2D i would write:
u = {-3, 3}; v = {1, 5};
Composition[Sqrt, #.# &, Subtract][u, v]
(* 2 Sqrt[5] *)
or as rm -rf pointed out you can ...
6
Here's another way to proceed, using Derivative[], and sidestepping the use of a dummy variable:
LogDerivative[f_] := Derivative[1][Composition[Log, f]]
Test:
LogDerivative[Sin][x]
Cot[x]
LogDerivative[Gamma][x]
PolyGamma[0, x]
LogDerivative[#^3 &][x]
3/x
6
Your operator must depend on both function and variable - in analogy to D function:
logD[f_, x_] := D[f, x]/f
or an alternative definition:
logD[f_, x_] := D[Log[f], x]
Of course your variables of differentiation and in the function must agree. Test it:
logD[f[x], x]
Derivative[1][f][x]/f[x]
logD[Sin[x], x]
Cot[x]
f = x^2; logD[f, x]
...
6
The problem can be reduced to the DSolve expressions:
DSolve[{x'[t] == a*x[t]*(1 - (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], t]
DSolve[{x'[t] == h*x[t]*(1 - (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], t]
One can see that alphabetical order appears important:
With[{a = Symbol@#},
Shallow @ DSolve[{x'[t] == a*x[t]*(1 - (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], ...
5
If you have an array of polynomial coefficients, you can use FromDigits[] in a most unconventional role:
coeffs = Range[10];
g[x_] = Expand[FromDigits[coeffs, x]]
10 + 9 x + 8 x^2 + 7 x^3 + 6 x^4 + 5 x^5 + 4 x^6 + 3 x^7 + 2 x^8 + x^9
You could also use Fold[] to implement Horner's method, if you wish:
g[x_] = Expand[Fold[(#1 x + #2) &, 0, coeffs]]
...
5
data = RandomReal[1, {5, 2}]
Whole rotation
Graphics[{Line[data], {Red, Rotate[Line[data], Pi/2]}}]
Single segment rotation
Graphics[{Line[data], {Red, Rotate[Line[#], Pi/2]} & /@ Partition[data, 2, 1]}]
5
You can always define the recursive function yourself and use memoizing to speed up computation:
g[n_, 0] := g[n, 0] = n;
g[n_, 1] := g[n, 1] = n^2;
g[n_, k_] := g[n, k] = g[n + 1, k - 1] + g[n + 2, k - 2];
Table[g[n, k], {k, 0, 10}, {n, 0, 10}] // TableForm
5
Indeed, Nest and NestList do not support functions with Hold attributes (as well as Fold and FoldList, etc). There were discussions of this in the past. I was able to find one such.
As far as I can tell, this is by design. What happens is that NestList (for example) maintains an internal list of intermediate results, the last of which is used in the next ...
4
Suppose your data is formatted as following:
data = Table[{x[t], y[t]}, {t, 0, 1, .2}]
{{x[0.], y[0.]}, {x[0.2], y[0.2]}, {x[0.4], y[0.4]}, {x[0.6], y[0.6]}, {x[0.8], y[0.8]}, {x[1.], y[1.]}}
You can use this symbolic "data" to peep into the FindFit to see what does the NormFunction take as its argument (as J.M. said (and the documentation), it's the ...
4
Note, this can be solved in general form. Start as
RSolve[{G[n, k] == G[n + 1, k - 1] + G[n + 2, k - 2]}, G[n, k], {n, k}]
You have two unknown functions C(1)[x] and C(2)[x] that you can find using your boundary conditions.
Apply your initial conditions G[n,0]:
A[n_] = C[1][n] /.
Solve[n == (-(1/2) - Sqrt[5]/2)^n C[1][n] + (-(1/2) + Sqrt[5]/2)^
...
4
If the question is about converting general math-book expressions to pure functions, you could use something like
SetAttributes[convert, HoldAll];
convert[expr_, vars_List] :=
With[{variables = Unevaluated@vars},
Block[variables,
Evaluate@(Hold[expr] /. Thread[vars -> Slot /@ Range@Length@vars]) & // ReleaseHold
]]
To apply,
...
4
I know for me, I spent years using Matlab (or should I say, a toolbox-based computational system), where there is a trick called vectorization: you turn almost everything (ifs, ands, sums, products...) into simple vector commands. Doing this with your function is pretty natural since you've already defined the entries in terms of two vectors. You take the ...
4
A bit more succint syntax you can reach with Dot, first define an array :
n = 10; (*choose the length of array if not defined*)
coeffArr = RandomInteger[10, n]
{2, 3, 10, 10, 9, 4, 9, 4, 6, 10}
and the result (since Power is Listable)
x^Range[0, n - 1].coeffArr
2 + 3 x + 10 x^2 + 10 x^3 + 9 x^4 + 4 x^5 + 9 x^6 + 4 x^7 + 6 x^8 + 10 x^9
...
4
Pick[#, Sign[(#1 - #4)] + Sign[(#4 - #7)] +
#1/(10.0 #2 + #3) + #4/(10.0 #5 + #6) +#7/(10.0 #8 + #9) & @@
Transpose@#, 1. - 2] &@ Permutations@Range@9 // Timing
(*{1.138807, {{5, 3, 4, 7, 6, 8, 9, 1, 2}}}*)
More faster version (Thanks @Michael E2):
Pick[#, Function[{a, b, c, d, e, f, g, h, i},
Evaluate[ Sign[a - d] + Sign[d - g] +
...
3
One way to speed things up is to use internally fast functions ("vectorized" ones).
Another consideration is that machine-size integer arithmetic is faster than exact rational arithmetic. If we clear denominators in the second criteria it turns out to be faster.
pickCriteria = Compile[{{perms, _Integer, 2}},
#[[1]] #[[5]] #[[6]] + #[[2]] #[[4]] #[[6]] + ...
3
I think you can do like this:
f[{x_, y_}] := {(2 x)/(1 + x^2 + y^2), (2 y)/(
1 + x^2 + y^2), (-1 + x^2 + y^2)/(1 + x^2 + y^2)}
for points:
Manipulate[
Graphics3D[{{Black, PointSize[Large], Point[{0, 0, 1}]}, {Black,
PointSize[Large], Point[Append[pt, 0]]}, {Pink, PointSize[Large],
Point[f[pt]]}, {Opacity[0.2], Sphere[]}, {Opacity[0.2],
...
3
How about:
apply[func_] := Module[{}, xvalues = Range[0, 500, 2.5];
points1 = Map[func1, xvalues];
Do[If[points1[[i]] < 0, points1[[i]] = 0], {i, 1, Length[points1], 1}];
table1 = Transpose[{xvalues, points1}]];
Now you call the function apply with your desired funcX as an argument
apply[func1]
Or you can automate this by defining
...
3
To fix undesirable aspect(s) of Mr.Wizards solution, we might alter the code as follows
ClearAll[position3]
position3[expr_, level_: 1] :=
With[
{
positionData =
SortBy[
#[[1, 1]] -> #[[All, 2]] & /@
GatherBy[
Extract[expr, #, Composition[HoldPattern, Verbatim]] ->
# & /@
Position[expr, _, ...
2
In my continuing mission to provide smartass answers, you can do, for example:
u = {-3, 3}; v = {1, 5};
d = Function[{u, v},
((Abs[u[[1]]] - Abs[v[[1]]])^2 + (Abs[u[[2]]] - Abs[v[[2]]])^2)^(1/2)][u, v]
I think the reason why it's suggested to convert to pure functions is for performance, otherwise I don't think I'd bother. But maybe there are other ...
2
Your own formula can be refactored in a more concise form:
f1 = With[{c = +##/2}, c + (# - c).{{0, -1}, {1, 0}} & /@ {##}] &;
+##/2 is a "trick" that here is equivalent to Mean[{#, #2}]
the function needs to be applied with @@@ rather than /@
A shorter function can be written using Cross, similar to what J. M. used:
f2 = {+##, # - #2}/2 ...
2
Had Rotate[]/RotationTransform[] not been available, here's a possible alternative:
BlockRandom[SeedRandom[123, Method -> "MKL"]; (* for reproducibility *)
segs = Arrow[RandomVariate[NormalDistribution[], {5, 2, 2}]]];
Graphics[{{Blue, segs},
{Red, segs /. s_?MatrixQ :> With[{m = Mean[s]}, m + Cross[# - m] & /@ s]}}]
2
OK, I am stupid. ListCorrelate is what I want, indeed. I just have to use the correct parameters.
acf = norm2 ListCorrelate[int, int, {1, 1}, 0]*norm1 -1;
where norm1 and norm2 give me the normation I need and are defined as
norm1 = Table[1/(Deltat + 1 - m), {m, 0, Deltat}];
norm2 = 1/Mean[int]^2;
Thanks to Bill S, RunnyKine and Daniel Lichtblau ...
2
You did not provide a definition of v or ra which would be helpful, but I suspect this may at least help you move in the right direction:
vhh[i_, j_, r_] /; 2 <= i <= 5 && 7 <= j <= 10 :=
-ehh (1 - {1 - Exp[-Ahh (ra[i, j, r] - rshh)]}^2)
vhh[__] := 0
vch[i_, j_, r_] /; i == 1 && 7 <= j <= 10 :=
-ech (1 - {1 - Exp[-Ach ...
2
Replaced by one equivalent Pick, but the net result is a slowdown ...
Pick[#, #1 < #4 < #7 && #1/(10 #2 + #3) + #4/(10 #5 + #6) + #7/(10 #8 + #9) == 1 & @@@ #] &@
Permutations@Range@9
Only top voted, non community-wiki answers of a minimum length are eligible


