Highest voted questions tagged function-construction - Mathematica Stack Exchange most recent 30 from mathematica.stackexchange.com 2019-11-11T22:11:11Z https://mathematica.stackexchange.com/feeds/tag?tagnames=function-construction&sort=votes https://creativecommons.org/licenses/by-sa/4.0/rdf https://mathematica.stackexchange.com/q/353 93 Functions with Options magma https://mathematica.stackexchange.com/users/137 2012-01-20T14:15:37Z 2017-03-08T09:07:44Z <p>Suppose you want to create a function which has optional arguments. Maeder's book <em>Programming in Mathematica</em> covers the topic extensively up to version 3, but some things have changed/evolved since then. </p> <p>So now what is the standard code to use for a function <code>func[x, ...]</code> which takes optional arguments?</p> https://mathematica.stackexchange.com/q/704 68 Functions vs. patterns David https://mathematica.stackexchange.com/users/103 2012-01-26T01:02:37Z 2015-05-08T03:25:40Z <p>Every time I define a new function, I wonder which construct I should use: true functions obtained by using <code>Function</code>, or rule-based syntax. For example, these are two ways of defining a square function:</p> <pre><code>square = Function[x, x^2] (* Alternatively: square = #^2&amp; *) square2[x_] := x^2 </code></pre> <p>Is there some fundamental difference (e.g. execution efficiency) between the two approaches?</p> https://mathematica.stackexchange.com/q/1567 64 How to avoid collision between optional arguments and options Andy Ross https://mathematica.stackexchange.com/users/43 2012-02-10T06:23:54Z 2017-12-09T06:56:50Z <p>Is it possible to create a function with optional arguments that also takes options? </p> <p>Here is a simple example. I have a function <code>f</code> with option "g". It also has optional arguments <code>y</code> and <code>z</code> which are set to default values. </p> <pre><code>Options[f] = {"g" -&gt; Identity}; f[x_, y_: 2, z_: 3, OptionsPattern[]] := OptionValue["g"][x + y + z] </code></pre> <p>Now, if I give values for all of the arguments and an option value it works just fine.</p> <pre><code>In:= f[1, 2, 3, "g" -&gt; (#^2 &amp;)] Out= 36 </code></pre> <p>If I give only the required argument, no problems.</p> <pre><code>In:= f Out= 6 </code></pre> <p>However, if I give the required arg and an option value but don't give the optional arguments, I run into trouble..</p> <pre><code>In:= f[1, "g" -&gt; (#^2 &amp;)] Out= 4 + ("g" -&gt; (#1^2 &amp;)) </code></pre> <p>Is there a good way around this?</p> <p><strong>EDIT:</strong></p> <p>Obviously, it is possible to write multiple definitions...</p> <pre><code>f[x_, y_, z_, OptionsPattern[]] := OptionValue["g"][x + y + z] f[x_, y_, OptionsPattern[]] := OptionValue["g"][x + y + 3] f[x_, OptionsPattern[]] := OptionValue["g"][x + 2 + 3] </code></pre> <p>I'm curious if there is a clean way to do it with a single definition.</p> https://mathematica.stackexchange.com/q/22052 49 Generating a Sierpinski carpet chyanog https://mathematica.stackexchange.com/users/2090 2013-03-25T16:23:26Z 2017-03-11T03:01:49Z <p>I am trying to draw a <a href="http://en.wikipedia.org/wiki/Sierpinski_carpet">Sierpinski_carpet</a>. I have code that works, but I think there is a more elegant way to do than my way. Maybe I couls use <code>Tuples</code> or <code>Permutations</code> or some similar function to simplify my code.</p> <p><img src="https://i.stack.imgur.com/x3FRh.png" alt="enter image description here"></p> <pre><code>f[{{x1_, y1_}, {x2_, y2_}}] := Map[Mean, { {{{x1, x1, x1}, {y1, y1, y1}}, {{x1, x1, x2}, {y1, y1, y2}}}, {{{x1, x1, x1}, {y1, y1, y2}}, {{x1, x1, x2}, {y1, y2, y2}}}, {{{x1, x1, x1}, {y1, y2, y2}}, {{x1, x1, x2}, {y2, y2, y2}}}, {{{x1, x1, x2}, {y1, y1, y1}}, {{x1, x2, x2}, {y1, y1, y2}}}, {{{x1, x1, x2}, {y1, y2, y2}}, {{x1, x2, x2}, {y2, y2, y2}}}, {{{x1, x2, x2}, {y1, y1, y1}}, {{x2, x2, x2}, {y1, y1, y2}}}, {{{x1, x2, x2}, {y1, y1, y2}}, {{x2, x2, x2}, {y1, y2, y2}}}, {{{x1, x2, x2}, {y1, y2, y2}}, {{x2, x2, x2}, {y2, y2, y2}}} }, {3}]; d = Nest[Join @@ f /@ # &amp;, {{{0., 0.}, {1, 1}}}, 3]; Graphics[Rectangle @@@ d] Clear["*"] </code></pre> https://mathematica.stackexchange.com/q/20766 46 Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs einbandi https://mathematica.stackexchange.com/users/4296 2013-03-06T18:28:21Z 2018-08-25T15:54:09Z <p>Using global variables the following turns an "expression" into a <code>Function</code>:</p> <pre><code>expr = 2 x; Function[x, Evaluate[expr]] </code></pre> <p>Of course this doesn't work if for some reason a value is assigned to <code>x</code>. Thus, I want to turn <code>expr</code> into a <code>Function</code> inside a <code>Module</code>. But it seems like there is a scoping problem:</p> <pre><code>Module[{x, expr}, expr = 2 x; Function[x, Evaluate[expr]] ] (* Function[x$, 2 x$1713] *) </code></pre> <p>Clearly, the <code>x</code> used in the first argument of <code>Function</code> is not the same as the <code>x</code> in the second. I played around with <code>Evaluate</code> and even with <code>Replace</code> and <code>Slot</code>, also trying to create a function with an anonymous variable, but didn't succeed. The only way that I managed to get the right result is this one involving strings:</p> <pre><code>Module[{x, expr}, expr = 2 x; "(" &lt;&gt; StringReplace[ToString@expr, ToString@x -&gt; "#1"] &lt;&gt; ")&amp;" // ToExpression ] </code></pre> <p>Is there a simpler, more straight-forward way to achieve this, without ever using any global variables?</p> https://mathematica.stackexchange.com/q/208045 45 Is there any algorithm that runs faster in Mathematica than in C or Fortran? Gummala Navneeth https://mathematica.stackexchange.com/users/66938 2019-10-17T05:35:48Z 2019-10-19T06:27:13Z <p>I'm just curious. My friend just told me that Mathematica is mostly for symbolic calculation and not efficient for Numerical computations. He told me that's the reason most of the people don't use Mathematica for CFD and other numerical intensive code.</p> <p>I've just started with Mathematica (I don't know C and Fortran). I was assuming that since Mathematica is new when compared to C and Fortran it should have included all the problems that C and Fortran might have, and since Mathematica has many inbuilt functions it should run faster than C and Fortran.</p> <p>Why is this not the case?</p> <p>Is there any case where Mathematica's code runs faster than C and Fortran?</p> https://mathematica.stackexchange.com/q/25591 43 Why is there no PositionFunction in Mathematica? Mr.Wizard https://mathematica.stackexchange.com/users/121 2013-05-21T13:16:02Z 2016-05-19T12:49:20Z <p>Too often I have seen the programs of inexperienced users greatly slowed by using <code>Position</code> in an iterative fashion, when far faster would have been to compute a look-up table for positions beforehand.</p> <p><em>Mathematica</em> provides such functionality for <code>Nearest</code> and <code>Interpolation</code> "out of the box" with the syntax of <code>function[data]</code> along with dedicated functions <code>NearestFunction</code> and <code>InterpolatingFunction</code>.</p> <p>There is no equivalent with <code>Position[data]</code> producing a <code>PositionFunction</code> object. I observe that <code>Position</code> appears to be used more often than either of the other functions so this seems like a regrettable omission. Two complications I can think of are:</p> <ul> <li><p>the levelspec of <code>Position</code></p></li> <li><p>the handling of patterns</p></li> </ul> <p>Based on this I ask:</p> <ol> <li><p>What other complications are there for creating a PositionFunction?</p></li> <li><p>How best can such a function be implemented?</p></li> <li><p>How can the utility and performance of the function be maximized?</p></li> <li><p>All limitations considered would such a function be valuable?<br> Why is there no such functionality in <em>Mathematica</em>?</p></li> </ol> https://mathematica.stackexchange.com/q/7756 41 Function in Table yulinlinyu https://mathematica.stackexchange.com/users/978 2012-07-01T17:10:38Z 2017-03-22T16:51:22Z <p>I need a table with the elements made of pure functions and list elements. This is a simplified example:</p> <p>I need a list as:</p> <pre><code>{a[]*Sin[#]&amp;,a[]*Sin[#]&amp;,a[]*Sin[#]&amp;} </code></pre> <p>and, my failed try is : <code>Table[a[[i]]*Sin[#]&amp;,{i,3}]</code></p> <p>Why is the failure and how can I improve it?</p> https://mathematica.stackexchange.com/q/15718 39 Can I make a default for an optional argument the value of another argument? orome https://mathematica.stackexchange.com/users/37 2012-12-04T20:36:20Z 2015-02-01T10:10:23Z <p>I'd like to define a function with several optional arguments, some of which default to the value supplied for other arguments. For example, I'd like to be able to write something like</p> <pre><code>f[x_, y_: 0, z_: y] := {x, y, z} </code></pre> <p>and have</p> <pre><code>{f[1, 2], f} </code></pre> <p>produce </p> <pre><code>{{1, 2, 2}, {1, 0, 0}} </code></pre> <p>Instead I get</p> <pre><code>{{1, 2, y}, {1, 0, y}} </code></pre> <p>Can I make a default for an optional argument the value of another argument? If not, what's the best approach for accomplishing this?</p> https://mathematica.stackexchange.com/q/23395 39 How can I make threading more flexible? Simon Woods https://mathematica.stackexchange.com/users/862 2013-04-16T15:37:27Z 2013-09-15T13:43:50Z <p>Threading automatically with <code>Listable</code> functions requires the argument expressions to have the same length (or for one of them to be atomic). For nested lists the threading will continue down through the levels, provided the lengths are the same at each level. So, for example, these all work because the <code>Dimensions</code> of the two lists are the same at the first $n$ levels:</p> <pre><code>Array[#&amp;, {10, 5, 3}] + Array[#&amp;, {10}]; Array[#&amp;, {10, 5, 3}] + Array[#&amp;, {10, 5}]; Array[#&amp;, {10, 5, 3}] + Array[#&amp;, {10, 5, 3}]; </code></pre> <p>whereas this doesn't work because the outer <code>Dimensions</code> don't match ($10\neq 5$):</p> <pre><code>Array[#&amp;, {10, 5, 3}] + Array[#&amp;, {5, 3}]; (* Thread::tdlen: Objects of unequal length ... cannot be combined. *) </code></pre> <p>But there <em>is</em> an obvious interpretation of the above code, which is to map the addition over the outer level of the first argument, i.e. to add the second 5x3 array to each of the ten 5x3 arrays in the first argument.</p> <p>A more easily visualised example is adding an offset to a list of coordinates:</p> <pre><code>coords = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; offset = {0, 10}; </code></pre> <p>One way is to explicity <code>Map</code> the addition over the coordinate list:</p> <pre><code>result = # + offset &amp; /@ coords (* {{1, 12}, {3, 14}, {5, 16}, {7, 18}} *) </code></pre> <p>If the coordinate list was very long, a more efficient approach using <code>Transpose</code> might be preferred:</p> <pre><code>result = Transpose[Transpose[coords] + offset] (* {{1, 12}, {3, 14}, {5, 16}, {7, 18}} *) </code></pre> <p>Neither of these is particularly readable though. It would be nice to have a "smart" threading function that would identify that the second dimension of <code>coords</code> (length 2) matches the first dimensions of <code>offset</code> (also length 2), allowing the code to be written very readably:</p> <pre><code>result = smartThread[ coords + offset ] (* {{1, 12}, {3, 14}, {5, 16}, {7, 18}} *) </code></pre> <p>How can I write such a <code>smartThread</code> function, which will take an expression of the form <code>func_[a_, b_]</code> and match up the various dimensions in <code>a</code> and <code>b</code> to do this kind of flexible threading?</p> https://mathematica.stackexchange.com/q/25182 39 Variable naming changes everything 5xum https://mathematica.stackexchange.com/users/7446 2013-05-14T12:29:19Z 2015-07-20T17:36:35Z <p><strong>Bug fixed in 10.0.0</strong></p> <hr> <p>I am having a rather unusual problem I do not understand with Mathematica where renaming one of the variables of my function causes the function to stop "working". Here is the example of the code doing what it should:</p> <pre><code>F[t_, a_, b_, l_] = x[t] /. First@ DSolve[{x'[t] == a*x[t]*(1 - (x[t]/b)) - l*x[t], x == 0.4}, x[t], t]; </code></pre> <p>Changing one variable name causes the code to throw out error messages. The non-working code is</p> <pre><code>F[t_, r_, b_, l_] = x[t] /. First@ DSolve[{x'[t] == r*x[t]*(1 - (x[t]/b)) - l*x[t], x == 0.4}, x[t], t]; </code></pre> https://mathematica.stackexchange.com/q/6588 38 Can a function be made to accept a variable amount of inputs? R Hall https://mathematica.stackexchange.com/users/686 2012-06-09T01:18:26Z 2015-06-16T07:14:24Z <p>I have a function that takes two inputs and processes them for a single output. What I need is one that can take a varying number of inputs. and process them to a single output. Is this possible in Mathematica?</p> <pre><code> DatasetAverage[inputData_, inputData2_] := Block[{dataAvg, v, w}, v = Length[inputData]; w = Length[inputData2]; If [v != w, Print["DatasetAverage: Data sample sizes do not match"]]; dataAvg = Table[Mean[{inputData[[i]], inputData2[[i]]}], {i, 1, Length[inputData2]}] ] </code></pre> https://mathematica.stackexchange.com/q/6822 38 Tiling a square Gianpiero Cea https://mathematica.stackexchange.com/users/1463 2012-06-14T18:01:18Z 2014-02-19T22:37:06Z <p>I wondered if there was a way to automate the process of finding a way to tile a tile into a square.</p> <p>The idea is to represent the tile with a matrix of $0$s for blank space and $1$s for filled spaces like in $\{\{0,1,1\}, \{1,0,0\}\}$.</p> <p><img src="https://i.stack.imgur.com/0k8C4.png" alt="The tile."></p> <p>The square (or a general rectangular area) is represented by an array as well.</p> <p>The function should then have as arguments two lists (representing the tile and the area) and should find the ways (if they exist) to do the tiling.</p> <p>This is quite an hard problem for me, I have tried playing with <code>Plus</code>, so that if the result matrix has $2$ it means that the tile overlaps while if it is $0$ there is a gap but I can't find a way to tell <em>Mathematica</em> that they should fit the area.</p> https://mathematica.stackexchange.com/q/7999 36 Define parameterized function rogerl https://mathematica.stackexchange.com/users/790 2012-07-06T22:03:31Z 2014-01-10T14:40:44Z <p>I would like to be able to define the gain function of a system from its parameters. Specifically, I'd like to define a function that accepts two inputs, call them $b$ and $w$, and returns a function that accepts a single parameter, $v$ and returns $1/\sqrt{(w^2 - v^2)^2 + b^2 v^2}$ .</p> <p>What's the right way to do this? Presumably I'd like to be able to write </p> <pre><code>gain[b,w][v] </code></pre> <p>to evaluate the function, with parameters b and w, at v. But I'd also like to be able to write</p> <pre><code>f[v_] = gain[b,w] </code></pre> <p>and have <code>f[v]</code> be the same as <code>gain[b,w][v]</code>.</p> https://mathematica.stackexchange.com/q/60045 34 Is there a comprehensive list of functions with operator forms? Martin Ender https://mathematica.stackexchange.com/users/2305 2014-09-18T19:44:42Z 2016-09-15T08:47:52Z <p>As of version 10, Mathematica sports operator forms for many functions like <code>Map</code>, <code>SortBy</code>, <code>Select</code> which allow you to curry one or more of the arguments. Like</p> <pre><code>m = Map[myFunction]; </code></pre> <p>which creates a new function <code>m</code> which automatically maps <code>myFunction</code> to any list that's passed to it.</p> <p>As the question title says, is there a comprehensive list of which functions support this now, or do I just have to recheck every function I'm using from now on, in case this feature was added (and is useful in my current problem)?</p> <p><strong>Edit:</strong> I just found <a href="http://reference.wolfram.com/language/guide/FunctionCompositionAndOperatorForms.html" rel="noreferrer">this list</a> buried in the docs, but it's not complete (e.g. <code>GroupBy</code> is missing).</p> https://mathematica.stackexchange.com/q/138661 34 Can we intelligently control evaluation in Thread? Mr.Wizard https://mathematica.stackexchange.com/users/121 2017-02-25T23:49:52Z 2017-02-28T13:58:25Z <p>This is a bid at creating a canonical Q&amp;A.</p> <p>Many questions have been asked that come down to the fact that <a href="http://reference.wolfram.com/language/ref/Thread.html" rel="nofollow noreferrer"><code>Thread</code></a> evaluates its first argument before threading is attempted. In a few minutes I found:</p> <ul> <li><a href="https://mathematica.stackexchange.com/q/4390/121">Threading behavior of SameQ vs Equals</a></li> <li><a href="https://mathematica.stackexchange.com/q/8360/121">Implementing myMapThread with Thread, Apply</a></li> <li><a href="https://mathematica.stackexchange.com/q/14121/121">Threading over a list of lists of lists and a list of atomic expressions</a></li> <li><a href="https://mathematica.stackexchange.com/q/37274/121">Why does Thread FileDate give an error message?</a></li> <li><a href="https://mathematica.stackexchange.com/q/45240/121">Efficient calculation of diagonal matrix elements</a></li> <li><a href="https://mathematica.stackexchange.com/q/83236/121">List operation list1 &gt;= list2 should compare elements</a></li> <li><a href="https://mathematica.stackexchange.com/q/85279/121">How to Thread with custom functions? Thread vs Map?</a></li> <li><a href="https://mathematica.stackexchange.com/q/102104/121">Why doesn&#39;t Thread always thread?</a></li> <li><a href="https://mathematica.stackexchange.com/q/108529/121">Map works but Thread doesn&#39;t</a></li> <li><a href="https://mathematica.stackexchange.com/q/133028/121/#134188">Function of Five Variables, and iterating over the last 3</a></li> <li><a href="https://mathematica.stackexchange.com/q/135909/121">Thread Part ([[]]) over two lists</a></li> <li><a href="https://mathematica.stackexchange.com/q/137227/121">Inconsistent behavior of thread on empty llists</a></li> </ul> <p>Basic examples of the problem:</p> <pre><code>Thread[{1, 2, 3} == {3, 2, 1}] </code></pre> <blockquote> <pre><code>False </code></pre> </blockquote> <p>(One might have expected <code>{False, True, False}</code>)</p> <pre><code>Thread[Print[{a, b, c}, " = ", {1, 2, 3}]]; </code></pre> <blockquote> <p>{a,b,c} = {1,2,3}</p> </blockquote> <p>(One might have expected <code>a=1</code>, <code>b=2</code>, <code>c=3</code>, on three separate lines.)</p> <p><strong>How can this most <em>easily</em> and <em>robustly</em> be addressed?</strong></p> https://mathematica.stackexchange.com/q/6114 33 How to make MapAt work with Span? M.R. https://mathematica.stackexchange.com/users/403 2012-05-28T06:59:03Z 2013-08-27T07:00:40Z <p><code>Span</code> (<code>;;</code>) is very useful, but doesn't work with a lot of functions. Given the following input</p> <pre><code>list = {{"a", "b", "c"}, {"d", "e", "f", "g"}, {"h", {{"i", "j"}, {"k", "l"}, {"m", "n"}, {"o", "pp"}}}} </code></pre> <p>We would like</p> <pre><code>MapAt[Framed, list, 1 ;; 2] MapAt[Framed, list, {{1, 1}, {2, 2 ;; 3}, {3, 2, 1 ;; 3, 1}}] </code></pre> <p>to work as expected</p> <p><img src="https://i.stack.imgur.com/vwOtu.png" alt="enter image description here"></p> <p>Here is my first go at it:</p> <pre><code>SpanToRange[Span[x_:1,y_:1,z_:1]] := Module[{zNew = z}, If[x&gt;y &amp;&amp; z==1, zNew = -1]; Range[x, y, zNew] ] /; And[VectorQ[{z,y,z}, IntegerQ], And @@ Thread[{z,y,z} != 0]] helper = Function[list, Module[{li=list}, If[FreeQ[li, Span], li, li = Replace[li,s_ /; Head[s] =!= Span :&gt; {s}, {1}]; li = li /. s:_Span :&gt; SpanToRange[s]; Sequence @@ Flatten[ Outer[List, Sequence @@ li], Depth[Outer[List, Sequence @@ li]]-3]] ] ]; protected = Unprotect[Span, MapAt]; Span /: MapAt[func_, list_, s:Span[x_:1,y_:1,z_:1]]:= MapAt[func, list, Thread[{SpanToRange[s]}]]; MapAt[func_, list_, partspec_] /; !FreeQ[partspec, Span] := Module[{f,p = partspec}, MapAt[func, list, Join[helper /@ p]] ]; Protect[Evaluate[protected]]; </code></pre> <p>But this is far from finished, and the extended down values should support all valid uses of <code>Span</code> such as</p> <pre><code>MapAt[Framed, list, 3 ;;] MapAt[Framed, list, ;; ;; 2] MapAt[Framed, list, ;; 10 ;; 2] </code></pre> https://mathematica.stackexchange.com/q/55833 33 Best practice of passing a large number of parameters to functions U.T. https://mathematica.stackexchange.com/users/18741 2014-07-25T10:23:28Z 2014-10-18T23:18:02Z <p>I have a number of functions that all take a large number of parameters. I am wondering what is the best practice of passing these parameters to those functions. I could, of course, simply specify the parameters outside the functions, as in (note that, in the actual example, there are far more parameters)</p> <pre><code>mu=1; sigma=1; lb=0; ub=10; f[x_] := PDF[LogNormalDistribution[mu, sigma],x] </code></pre> <p>However, I would prefer to explicitly pass the parameters to the functions. In Python, I would use a dictionary. In Mathematica, one possibility would be a replacement rule.</p> <pre><code>par={mu-&gt;1,sigma-&gt;1,lb-&gt;0,ub-&gt;10}; f[x_,par_] := PDF[LogNormalDistribution[mu, sigma],x]/.par </code></pre> <p>However, this can cause warnings if a function only takes numerical arguments, e.g.</p> <pre><code>Plot[f[x,par],{x,lb,ub}]/.par </code></pre> <blockquote> <p>Plot::plln: Limiting value lb in {x,lb,ub} is not a machine-sized real number. >></p> </blockquote> <p>The plotting actually, works, though. </p> <p>Also, passing parameters using replacement rules seems to be inefficient, since - if possible - evaluations are done symbolically, and only then are values substituted for variables.</p> https://mathematica.stackexchange.com/q/130 33 which is better, using Assert[] or manual checks on arguments and other computations? Nasser https://mathematica.stackexchange.com/users/70 2012-01-18T09:55:41Z 2015-07-09T06:09:05Z <p>I never used <a href="http://reference.wolfram.com/mathematica/ref/Assert.html">Asserts</a> in Mathematica, but trying to see what advantage they have over just argument check and additional definitions of the function to capture unwanted input.</p> <p>For example, which one of these 2 would you think is better?</p> <pre><code>ClearAll[f] f[x_] := (Assert[x &gt; 0]; Sqrt[x]) On[Assert]; f[2.] f[-2.] </code></pre> <p>The last call above generated in the console a beep and a message:</p> <pre><code>Assert::asrtf: Assertion -2.&gt;0 failed. &gt;&gt; </code></pre> <p>But I could also just write</p> <pre><code>ClearAll[f]; f[x_] := Sqrt[x] /; x &gt; 0 f[2.] f[-2.] </code></pre> <p>and the second call will return unevaluated</p> <pre><code>f[-2.] </code></pre> <p>and If I want a beep, I could always do something like</p> <pre><code>ClearAll[f]; f[x_] := Sqrt[x] /; x &gt; 0 f[x_] := Throw["f[x] not supported for negative values"] </code></pre> <p>or something along these lines.</p> <p>Since asserts seem to be used to assert that input to a function is within the ranges supported by the function, what benefit they have over the other method shown above?</p> <p>Or should one look into using Asserts inside the function itself, i.e. in the middle of a computation, to check that intermediate results are within expected ranges? But also then, I would use a simple <code>If</code> check instead, and return an error code to the caller (which I prefer) or use Throw. An example from help shows this:</p> <pre><code>myFun[x_] := Block[{y}, y = x^2; Assert[y &gt; 5]; Sin[y] ] </code></pre> <p>So that the call <code>On[Assert]; myFun[1.0]</code> generated <code>Assert::asrtf: Assertion y&gt;5 failed</code>.</p> <p>But I can write instead</p> <pre><code>myFun[x_] := Block[{y}, y = x^2; If[y &lt;= 5, Throw["y&lt;=5"]]; Sin[y] ] </code></pre> <p>and now the call <code>myFun[1.0]</code> will also generate a message and a beep as well from the same place.</p> <p>I guess I am looking for when in Mathematica the use of Assert would be better and recommended over these other ways of checking. </p> <p>My only guess now is that Assertion code can be disabled and enabled more easily, and this can have an effect on run time. i.e. after testing the code, I can disable Asserts from the final version, and it should run faster, since all these checks are not being done at run time any more. But with the manual checking as above, that code remains there all the time.</p> <p>thanks</p> https://mathematica.stackexchange.com/q/56319 33 How can I export my learned ClassiferFunction[] and PredictorFunction[]s? user5601 https://mathematica.stackexchange.com/users/5601 2014-07-31T15:40:50Z 2017-05-29T15:00:02Z <p>Mathematica 10 provides beautiful high-level machine learning functionality. Sadly, the learned functions once created are rather opaque objects. I need to use them in other projects, so here is my question: </p> <p><strong>Can I export the neural networks, random forest decision trees, or any other internals of the learned functions for externally use, e.g. can I export a neural net into a standard FANN File format.</strong> </p> <p>PS. My real hope is to use <em>Mathematica</em> <strong>V10</strong> to generate machine-vision convolutional neural networks and then embed them within my clojure, pythons and iOS projects.</p> https://mathematica.stackexchange.com/q/29206 32 Is there any way to define pure functions with optional arguments? M6299 https://mathematica.stackexchange.com/users/7115 2013-07-26T07:44:31Z 2016-11-01T20:27:32Z <p>For example consider the following function:</p> <pre><code>Function[{u,v},u^2+v^4] </code></pre> <p>Is there anyway to define default values for the variables <code>u</code> and <code>v</code>?</p> <p>I know that this is possible for ordinary functions as follows:</p> <pre><code>f[u_:1,v_:0]:=u^2+v^4 </code></pre> <p>But I am looking for a way to do this with pure functions defined by <code>Function[]</code>.</p> https://mathematica.stackexchange.com/q/128818 31 Why does removing a function and defining it on the same line not work? Soldalma https://mathematica.stackexchange.com/users/22021 2016-10-16T02:39:18Z 2017-03-20T15:42:31Z <p>Why do the two pieces of code below yield rather different results? The only difference is that in the first one the function definition is in the same line as the <code>Remove</code> command while in the second one the two commands are in different lines.</p> <pre><code>Remove[f]; f[x_] := 1; ?? f (* Information: Symbol f not found *) </code></pre> <pre><code>Remove[f]; f[x_] := 1; ?? f (* Globalf and the function definition *) </code></pre> <p>Defining another function on the same line does work:</p> <pre><code>Remove[g]; Remove[f]; g[x_] := 1; ?? g (* Global`g and the function definition *) </code></pre> https://mathematica.stackexchange.com/q/4937 31 How to Combine Pattern Constraints and Default Values for Function Arguments? StackExchanger https://mathematica.stackexchange.com/users/1149 2012-05-01T02:06:15Z 2019-05-03T14:24:56Z <p><strong>EDIT:</strong> <em>As several respondents have noted in the answers and comments below, the original example had a default value that would never be used because of the way patterns and default values are applied. I've edited the example so that it now focuses on the question that was being asked and which has already been answered.</em></p> <p>Is it possible to achieve the following behavior in a function definition:</p> <pre><code>Remove[foo]; foo[Optional[Pattern[x, _?IntegerQ], 1]] := x; foo[] foo 1 2 </code></pre> <p>using "colon syntax" shorthand? </p> <p>Note that,</p> <pre><code>Remove[foo]; foo[x : _?IntegerQ : 1] := x; foo[] foo foo[] foo </code></pre> <p>does not produce the desired result.</p> <p>The first code sample is too verbose; setting a default value for a function argument while simultaneously checking type when an argument is supplied should be common enough practice to deserve its own shorthand notation.</p> <p>Can anyone modify the second example to achieve the desired results? If Mathematica syntax does not directly support shorthand for combining default values with argument type checking, perhaps someone could suggest how this might be achieved using the Notation package.</p> https://mathematica.stackexchange.com/q/7040 30 Function that counts the number of arguments of other functions Jane T. https://mathematica.stackexchange.com/users/1529 2012-06-19T14:25:09Z 2012-06-20T02:01:58Z <p>I have a newbie question: is it possible to write a function that counts the arguments (total and optionals) of a given function? Possibly it should be able to work with built-in and custom functions as well.</p> <p>For example, if I define</p> <pre><code>f1[x_Integer] := x + 1; f2[x_Integer, y_Integer: 1] := x + y; g[x_Real, y_] := x - y; </code></pre> <p>I would like to have</p> <pre><code>countArgs[f1] {1,0} countArgs[f2] {2,1} countArgs[g] {2,0} </code></pre> <p>and also, for example,</p> <pre><code>countArgs[Sin] {1,0} </code></pre> <p>thank you.</p> <p>@celtschk</p> <p>Well, I didn't even know the use of UpValues, but basically what I am asking is the number of inputs the function needs, I don't care what the function does with those inputs. In your examples I would say</p> <ul> <li>{Infinity,0} for foo? It's more a question than an answer, sorry, but I had not thought aboute these unusual cases.</li> <li>this is nasty, I didn't think of a case like that either, I would say {3,{2}}, the {2} meaning exactly 2, to avoid bar[1,2], which is not legal.</li> <li>{2,0} but just because you wrote f[g,g], so it's practically a guess, I don't know what are UpValues and if they go against the spirit of my question by messing with the function. I hope I was clear.</li> <li>the last one I would say {3,0} as they were flattened.</li> </ul> <p>Thank you, I start seeing that my question is not so obvious because there are too many complicated definitions for functions to take into account.</p> <p>For now I understood that is possible with built-in functions with </p> <pre><code>SyntaxInformation[f] </code></pre> <p>(thank you Heike) but that mybe is a little too much asking for a general custom function.</p> https://mathematica.stackexchange.com/q/3174 28 Using patterns in pure functions sjdh https://mathematica.stackexchange.com/users/515 2012-03-19T08:32:36Z 2017-09-23T02:53:13Z <p>Pure functions may be handy if you don't want to assign your function a name. For example I would calculate $x(x-1)$ for some numbers $x$ by</p> <pre><code>In: #(#-1) &amp; /@ {1, 2, 3} Out: {0, 2, 6} </code></pre> <p>Is it possible to use patterns in this construction? For example something like</p> <pre><code>f[x_Integer] := x(x-1) </code></pre> <p>but then without defining a function f first.</p> https://mathematica.stackexchange.com/q/10067 28 Convert an expression to a Function Simon Woods https://mathematica.stackexchange.com/users/862 2012-08-30T15:58:55Z 2012-08-31T02:42:31Z <p>I need a function which can take an expression and return a pure function based on the symbols in the expression. The symbols might have values so must be protected from evaluation. It is probably easiest to give an example:</p> <p>I would like to evaluate something like</p> <pre><code>x = y = 1; extractPureFunction[Sin[Pi x^2] + y] </code></pre> <p>and obtain</p> <pre><code>Function[{x, y}, Sin[Pi x^2] + y] </code></pre> <p>or</p> <pre><code>(Sin[Pi #1^2] + #2) &amp; </code></pre> <p>Any ideas?</p> https://mathematica.stackexchange.com/q/29353 28 How does Return work? Szabolcs https://mathematica.stackexchange.com/users/12 2011-12-16T12:43:37Z 2019-09-09T12:59:55Z <p>It is not completely clear to me how <code>Return[]</code> works.</p> <p>The documentation says:</p> <blockquote> <p><code>Return[expr]</code> returns the value expr from a function. </p> </blockquote> <p>But in <em>Mathematica</em> it is not clear where are the boundaries of a "function" defined using patterns and <code>Set(Delayed)</code>. The system simply applies replacement rules until there's nothing to change anymore.</p> <p>Consider these examples:</p> <pre><code>a := (Module[{}, Return; 1]; 2) a (* 0 *) </code></pre> <p>It is not completely clear to me why <code>Return</code> breaks out from <code>a</code>, and not from <code>Module</code> or one of the <code>CompoundExpression</code>.</p> <p>The following doesn't work, and simply returns the <code>Return</code> expression. It reminds me a bit of how <code>Unevaluated</code> is handled.</p> <pre><code>(Module[{}, Return; 1]; 2) (* Return *) </code></pre> <p>If we add another layer of definitions, the effect of <code>Return</code> will stop there:</p> <pre><code>b := (a; 3) (* 3 *) </code></pre> <p>Why do these three inputs give different results? What is the general rule for deciding where <code>Return</code> breaks out to precisely?</p> <p>The answer lies somewhere in fully understanding the evaluation process.</p> <p>Would someone care to elucidate this point, perhaps with pointers to the parts of the documentation which make this clear?</p> https://mathematica.stackexchange.com/q/134 27 Sum over n variables Phira https://mathematica.stackexchange.com/users/101 2012-01-18T10:13:25Z 2016-09-27T16:11:49Z <p>What is the most painless way to sum over n variables, for example, if the range of summation is $i_1 &lt; i_2 &lt; i_3 &lt; \dots &lt; i_n$, where $n$ is an argument of the function in question?</p> <p>Is there a package for this and more complex summation ranges?</p> <p>I am not happy with programming loops all the time for this common summation range and if one has a large summation range, one cannot just use a combinat command to generate all subsets of a certain size, if this takes too much memory.</p> <p>Example:</p> <p>$$f(n)=\sum_{0 &lt; i_1 &lt; i_2 &lt; \dots &lt; i_n &lt; 2n+1} \qquad \prod_{1\le r &lt; s \le n} (i_s-i_r)$$</p> https://mathematica.stackexchange.com/q/88342 26 Is there a GraphicsPrimitiveQ (or a complete list of Heads of graphics primitives)? march https://mathematica.stackexchange.com/users/29734 2015-07-15T21:04:41Z 2018-10-14T19:32:07Z <p>For various reasons related to workflow associated with creating figures for journals, I am creating functions that will accept graphics primitives and a set of options and spit out a <code>Graphics</code> object with those primitives and those options in some configuration.</p> <p>(Of course, this sounds like all I'm doing is re-creating <code>Graphics</code>, in that I can call</p> <pre><code>Graphics[ &lt;List of primitives&gt;, &lt;Sequence of options&gt;] </code></pre> <p>but it's more complicated than that.)</p> <p>In any case, I would like to be able to check whether the inputs to the function are graphics primitives or not. We can create our own <code>GraphicsPrimitiveQ</code> if we have a list of the <code>Head</code>s of graphics primitives. For instance,</p> <pre><code>Clear[GraphicsPrimitiveQ, listOfHeads] listOfHeads = {Line, Polygon, Point, Arrow, Tube}; GraphicsPrimitiveQ[x_] := MatchQ[Head[x], Alternatives @@ listOfHeads] </code></pre> <p>in which case if we define</p> <pre><code>f[x__?GraphicsPrimitiveQ] := {x} </code></pre> <p>then</p> <pre><code>f[Point[{0, 0}], Line[{{1, 1}, {0, 0}}]] (* {Point[{0, 0}], Line[{{1, 1}, {0, 0}}} *) </code></pre> <p>and</p> <pre><code>f[Point[{0, 0}], 1] (* f[Point[{0, 0}], 1] *) </code></pre> <ul> <li><p>So: <strong>Is there something like a GraphicsPrimitiveQ?</strong></p></li> <li><p>Or: <strong>Is there hidden somewhere in Mathematica an easy way to get a list of all graphics primitives?</strong></p></li> <li><p>Alternatively, if there's no built-in <code>ListOfGraphicsPrimitives[]</code>, then <strong>Is there a programmatic way of making the function <code>GraphicsPrimitiveQ</code>?</strong> (Added this because I for some reason didn't anticipate the clever answers below.)</p></li> </ul> https://mathematica.stackexchange.com/q/28610 26 Constructing symbol definitions for With bobthechemist https://mathematica.stackexchange.com/users/7167 2013-07-15T13:56:24Z 2014-10-18T23:21:24Z <p>I would like to be able to define two arrays, one containing symbol names and one containing the values of those symbols, for use in constructs such as <code>With</code>. For example:</p> <pre><code>params = {a,b,c,d}; vals = {1,2,3,4}; With[{a=1,b=2,c=3,d=4},Print["Do something fancy"]] </code></pre> <p>I would like to construct the local variable assignment array {a=1, b=2, ....} automatically. The wishful-thinking solution of <code>With[params = values, ...]</code> doesn't work and I've tried a random selection of Mapping, Threading and Holding, all to no avail. It looks like a similar <a href="https://mathematica.stackexchange.com/questions/280/reassign-values-to-symbols">question has been answered before</a>, however, the function proposed by <a href="https://mathematica.stackexchange.com/users/81/leonid-shifrin">Leonid</a> doesn't work in the <code>With</code> block. I suspect my issue focuses on an attempt to manipulate Symbols in a non-trivial manner (and by non-trivial, I simply mean anything beyond a = 1).</p>