# Tag Info

1

Set the attribute Listable on the function. SetAttributes[f, Listable] Then it will auto-thread over arrays: f[{1, 2, 3}] (* {f[1], f[2], f[3]} *) Sin, Cos, etc. also have this attribute: Attributes[Sin] (* {Listable, NumericFunction, Protected} *)

3

table = Table[{ToExpression["i" <> ToString@n], ToExpression["j" <> ToString@n]}, {n, 5}] $\${{i1, j1}, {i2, j2}, {i3, j3}, {i4, j4}, {i5, j5}} (f[#1] = #2) & @@@ table $\${j1, j2, j3, j4, j5} ?f

5

Declaring expressions as real As others have already written you can set global $Assumptions, but then to get desired results you would need to, each time, use Refine, Simplify, or similar function that uses Assumptions. If you want certain expressions to be treated as "real" automatically, without simplifying, you can override behavior of built-in ... 3 If you use numbers you can define R[ψ_Real] := {{1, 0, 0}, {0, Cos[2 ψ], Sin[2 ψ]}, {0, -Sin[2 ψ], Cos[2 ψ]}} For symbolic analysis you will need to use Simplify in conjunction with assumptions as indicated by george2079. It would look something like this: R[ψ_] := {{1, 0, 0}, {0, Cos[2 ψ], Sin[2 ψ]}, {0, -Sin[2 ψ], Cos[2 ψ]}} and then ... 6 FindFormuala is EXPERIMENTAL and new in v10.2 Clear[x, y]; xData = {1, 3, 5, 11}; yData = {1, 9, 25, 121}; y[x_] = FindFormula[Transpose[{xData, yData}], x] (* x^2 *) 4 Try the following: data = Transpose[{x, y}]; FindFormula[data, z] 1 Is there a particular reason for use ConjugateTranspose instead of Transpose? Please note: I can't comment yet so take this as a comment. In another "answer" of mine, which was deleted, I was suggested to "comment on your own posts, and once you have sufficient reputation you will be able to comment on any post." Which I found a pointless advice as I ... 7 As shown in my comment, what I usually do is defer the compilation of the function until it is first used. Once your function is compiled, you store it in exact the same variable and therefore, you only have a delay in the very first call. This method is basically just a simple memoization and I use it very often in packages. For instance in my Heyex Data ... 3 It takes some careful coding to make sure the right values are explicitly numeric at the time they need to be (in the inner optimization). Can be done as below. And there may be better ways, I'm no expert. stratmin[p_ /; MatrixQ[p, Element[#, Reals] &], xlist_List /; VectorQ[xlist, Element[#, Reals] &]] := Module[ {y, c = Length[p], yvars, ... 9 I'm not quite sure what you mean. If you want a way of providing only one argument which then is interpreted as three, you could do: f[{a_, b_, c_}] := … f[args_] := With[{a = args[[1]], b = args[[2]], c = args[[3]]}, … ] fInternal[a_, b_, c_] := … f[args_] := fInternal[{args}] or for that last one f = fInternal @* List; If you want a way of making ... 2 You can define a periodic function by this simple idiom T = 1; g[x_ /; 0 <= x <= T] := x^2; g[x_] := g[Mod[x, T]] Here, T is the length of the period. What happens is that you restrict your function g to a certain interval and when your argument x falls outside this interval, you just shift it back (using Mod here). With this, you can use g anywhere ... 6 Here are a couple of other options: Use system option "StrictLexicalScoping" If you use SetSystemOptions["StrictLexicalScoping" -> True] Then your code runs fine (I changed the input to hun to avoid other errors): With[{fun = makeFun[10]}, hun[x_] := fun[x]; hun[Range[15]]] (* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} *) Reasonably general top-level ... 6 One possible workaround is to "turn off" the name rewriting that Function does is makeFun, and provide a name for the formal parameter you know is unique. There are several ways of doing this, but this one is mine: In[6]:= Module[{x, function}, Attributes[function] = HoldAll; makeFun[len_] := function[x, Take[x, ... 3 Overloading can do the trick too: g[x_Integer] = 1; g[x_] = 0; 2 If you want 2.0 to be recognized as an integer you may use: g[x_] := Boole[NumericQ@x && Last@Internal`TestIntegerQ@x] g /@ {-2, 2.0, 3, 1.7, foo, "bar"} (* {1, 1, 1, 0, 0, 0} *) 4 g = Boole @* IntegerQ; g /@ {-2, 3, 1.7, foo, "bar"} {1, 1, 0, 0, 0} Responding to the comment, this is your code corrected: ClearAll[g] g[x_] := 1 /; Floor[x] == x g[x_] := 0 /; Floor[x] != x g[2] g[2.5] 1 0 Capitalization is important in Mathematica. Nearly all System Symbols begin with a capital letter. <> is a shorthand infix ... 3 Try this: g[x_] := If[IntegerQ[x], 1, 0]; g[2] g[2.5] giving (* 1 0 *) Have fun! 2 If you don't want to use SetAttributes then you can do autocorrelate[f_, t_, \[Tau]_, T_] := Integrate[f[t]*f[t + \[Tau]], {t, 0, T}]/T Then with a[t_] := E^t you get autocorrelate[a, t, \[Tau], 10] (*1/20 E^\[Tau] (-1 + E^20)*) For the Sin function we have autocorrelate[Sin, t, \[Tau], 2 Pi] (*Cos[\[Tau]]/2*) 4 This specific problem has indeed been resolved as of version 10.0.2, although it is still possible to run into similar behavior in other computations. The Mac failure mode is worse than on other systems. To give an idea what was behind the system freeze, one of the operations attempted in the background by the Predictive Interface was a heuristic (based on ... 2 When you omit a parameter in the middle then Null is passed. You can check for this, replace the value with a default value, and continue with the execution. f[x_: "a", y_: "b", z_: "c"] := Module[{}, {x, y, z}] As you already know, this gives you the standard default behaviour. You can omit parameters from the right. The use of Module will become clear. ... 5 We can use BlankNullSequence to keep from listing all possibilities of missing arguments. We can use recursion f[a_]:=f[b] to keep from having to repeatedly write the function body. f[a___, Null, b___] := (* pair inputs with defaults *) Transpose[{ {a, Null, b}, {"defaultA", "defaultB", "defaultC", "defaultD"} }]// (* input or default? *) ... 11 Define function with Null inputs Clear[f] f[a_String: "a", Null, c_String: "c"] := a <> "b" <> c; f[Null, b_String: "b", c_String: "c"] := "a" <> b <> c; f[Null, Null, c_String: "c"] := "a" <> "b" <> c; f[a_String: "a", b_String: "b", c_String: "c"] := a <> b <> c; {f["x", "y", "z"], f["x", "y"], f["x", , ... 2 In case reading the documentation, as recommended by yohbs, did not fully answer your question, try U[x_, t] = f[(x^3 + 3 t/4)^(1/3)] Exp[x^2/2 - (x^3 + 3 t/4)^(2/3)/2]; Simplify[D[U[x, t], x] - 4 x^2 D[U[x, t], t] - x U[x, t]] (* 0 *) By the way, Exp[ - (x^3 + 3 t/4)^(2/3)/2] can be absorbed into f without loss of generality. 6 This is an approximation*: inv = Interpolation[ DeleteDuplicates[ Table[ {pP[x], x}, {x, 1, 400, .01}] , (#1[[1]] == #2[[1]]) & ], InterpolationOrder -> 0]; Plot[ inv[x], {x, 0, 80}] The issue now is how to find the exact x where the jumps occur.. *After looking at the results the jumps seem to always ... 6 Your code is almost completely correct, but I did notice your use of Append which actually doesn't reassign the value of edist, for that, you would to use AppendTo. 11 More Mathematica-ish SeedRandom[42]; mu = 0; sigma = 1; shotsPerGroup = 3; iterations = 4; rv = RandomVariate[NormalDistribution[mu, sigma], {iterations, shotsPerGroup, 2}]; pairs = Subsets[#, {2}] & /@ rv; Max /@ Apply[EuclideanDistance, pairs, {2}] (* {1.29553, 3.05122, 1.24002, 2.10169} *) 6 Adapting Leonid's method for How do you set attributes on SubValues? ClearAll[f, g]; SetAttributes[{f, g}, HoldAll]; g /: g[x_] + g[y_] := upvalue; f[x_] := downvalue f := With[{stack = Stack[_] /. HoldPattern[f] :> g}, With[{foo = Cases[stack, Alternatives @@ _ /@ First /@ UpValues @ g]}, g /; foo =!= {} ] /; stack =!= {} ] Now: f[1] ... 9 Without thinking about any consequences, one idea popped into my mind. First, your definitions for f with the DownValues. I made it a bit more interesting: ClearAll[f]; f // Attributes = {HoldAll}; f /: HoldPattern[f[x_] + f[y_]] := upvaluesSeen[f[x], f[y]]; f[x_] := downvalue[x] How about a small wrapper function that temporarily deletes all DownValues ... 3 You can hide your workaround in$Pre: SetAttributes[specialEvaluate, HoldAll] specialEvaluate[expr_] := ReleaseHold[ Hold[expr] /. UpValues[f] ] \$Pre = specialEvaluate; And now: f[1] + f[2] (* Out: upvalue *)

6

The use of pattern matching to inform Mathematica of which of several function definitions to apply to a function call is extremely powerful in practice. For one, it allows tail-recursive functions, functions which are essentially as efficient as iterators, to be defined. For two, it allows functions to exclude argument forms that are not acceptable, which ...

10

Mathematica works by rewriting expressions. Each of your definitions involves a different condition triggering the rewrite. Rewriting is the essence of symbolic mathematics. Mastery of this in Mathematica will allow you to implicitly delay evaluation until enough is known about the expression to evaluate it, efficiently evaluate special cases, terminate ...

0

(Code to extract text from cell copied from John Fultz here.) This needs work but it's the start of one possible approach. To split a tagged cell at semi-colons: nb = EvaluationNotebook[]; cellObject = First[Cells[nb, CellTags -> {"MyCode"}]]; SelectionMove[cellObject, All, Cell]; text = First[ FrontEndExecute[ ...

2

The reason your code is slow is that you call PixelValue for each voxel. (You also call ImageDimensions[sh] for each voxel when you only need to compute it once, but that's not a big deal.) Instead, you can use ImageData once on your silhouette, giving you all pixel values at once. Here is my suggestion: {w, h} = ImageDimensions[silb0]; im = ...

2

Using Range, Length, Nearest, Flatten, Select and MemberQ you can extract uniformly spaced log time from your uniformly spaced in time data. First an example is shown using 0.1 for the minimum time, 10.0 for the maximum time and 21 for the number of samples. Then it will be wrapped up into a function. Data is generated as in your question. y[t_] := 2 + ...

3

The algorithm does two things: Sample uniformly in log space and then convert it back to time space. Select data points in time space corresponding to the samples generated in (1). logspace from [13226] can be used for (1): logspace[increments_, start_?Positive, end_?Positive] := Exp@Range[Log@start, Log@end, Log[end/start]/increments] For step 2, ...

1

Ok here is the workaround. Actually it's the transfer of above MatLab code in Mathematica's procedural programming. Thanks to Sector, because his comments made me work harder with it!! I would appreciate now other ways of arriving in the same result which makes use of Mathematica functional or/and rule-based programming (and of course make the program ...

3

To evaluate the contents of a whole section within the same notebook and return its output please use the following simple function (which should be placed within the section you want to be evaluated) EvalSection := Block[{notebook, nb, thissection, result}, "find me 31415"; notebook = NotebookGet[EvaluationNotebook[]]; thissection = ...

3

I revised my previous function. Now it works great nestFactor[n_Integer] := Block[{q, f}, f = # /. {a_Integer, b_Integer} /; b > 1 :> {a,FactorInteger[b]} &; q = FixedPoint[f, FactorInteger[n]]; Replace[q, {a_Integer, b_} -> HoldForm[a^b], -1] /. HoldForm[a_^1] -> a //. {a_} -> a //. List[a__] -> HoldForm[Times[a]]] I ...

1

This may be more of a long comment than an answer. You say that you want to generalize your code, but your code seems to work pretty generally already. You could just wrap it in a function, and use it as is: powertower[n_Integer] := Times @@ Flatten[ HoldForm[ Power[##]] & @@@ (If[#[[2]] == 1, #[[1]], If[PrimeQ[#[[2]]] == True, #, ...

Top 50 recent answers are included