# Tagged Questions

For questions on writing functions (pure or using Set/SetDelayed) for any purpose, including the features that may be incorporated in those functions, such as options, patterns and conditions.

4k views

### Functions with Options

Suppose you want to create a function which has optional arguments. Maeder's book "Programming in Mathematica" covers the topic extensively up to version 3, but some things have changed/evolved since ...
3k views

### Functions vs. patterns

Every time I define a new function, I wonder which construct I should use: true functions obtained by using Function, or rule-based syntax. For example, these are ...
3k views

### How can I create a function with optional arguments and options?

Is it possible to create a function with optional arguments that also takes options? Here is a simple example. I have a function f with option "g". It also has ...
8k views

### Generating a Sierpinski carpet

I am trying to draw a Sierpinski_carpet. I have code that works, but I think there is a more elegant way to do than my way. Maybe I couls use Tuples or ...
1k views

### Tiling a square

I wondered if there was a way to automate the process of finding a way to tile a tile into a square. The idea is to represent the tile with a matrix of $0$s for blank space and $1$s for filled spaces ...
1k views

### Why is there no PositionFunction in Mathematica?

Too often I have seen the programs of inexperienced users greatly slowed by using Position in an iterative fashion, when far faster would have been to compute a ...
1k views

### Variable naming changes everything

Bug fixed in 10.0.0 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 ...
891 views

### Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs

Using global variables the following turns an "expression" into a Function: expr = 2 x; Function[x, Evaluate[expr]] Of course ...
662 views

### How can I make threading more flexible?

Threading automatically with Listable functions requires the argument expressions to have the same length (or for one of them to be atomic). For nested lists the ...
2k views

### Can a function be made to accept a variable amount of inputs?

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 ...
2k views

### Using pure functions in Table

I need a table with the elements made of pure functions and list elements. This is a simplified example: I need a list as: ...
760 views

### How to make MapAt work with Span?

Span (;;) is very useful, but doesn't work with a lot of functions. Given the following input ...
620 views

### which is better, using Assert[] or manual checks on arguments and other computations?

I never used Asserts in Mathematica, but trying to see what advantage they have over just argument check and additional definitions of the function to capture unwanted input. For example, which one ...
1k views

### Best practice of passing a large number of parameters to functions

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 ...
1k views

### Define parameterized function

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

### Can I make a default for an optional argument the value of another argument?

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 ...
2k views

### Convert an expression to a Function

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

### Constructing symbol definitions for With

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 With. For ...
1k views

### Is there any way to define pure functions with optional arguments?

For example consider the following function: Function[{u,v},u^2+v^4] Is there anyway to define default values for the variables ...
2k views

### Sum over n variables

What is the most painless way to sum over n variables, for example, if the range of summation is $i_1 < i_2 < i_3 < \dots < i_n$, where $n$ is an argument of the function in question? Is ...
474 views

### Nested definition: How can I define a function with a passed-in expression?

Here's a simplified version of what I'm trying to do: ...
325 views

### Is there a GraphicsPrimitiveQ (or a complete list of Heads of graphics primitives)?

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

### How to program a F::argx message?

How useful is it to program a user-built function in a package to produce a red warning message F::argx if you give the wrong number of arguments to that function? ...
351 views

### Plotting a defined function gives different results from plotting the function directly

Consider the following piece of code: function[t_]:=Exp[-9 t^2]; LogLogPlot[{function[t],Exp[-9 t^2]},{t,.01,100}] I expect the two plots to exactly overlap each ...
362 views

### Kernel inexplicably hangs if I define a pure function without suppressing output

Bug introduced in 9.0 and fixed in 10.0.2 Save any unsaved work before trying as it may crash Mathematica and other programs by filling up the memory! In v9.0.1.0 on OSX 10.8.5, if I start a new ...
444 views

### Why x = x doesn't cause an infinite loop, but f[x_] := f[x] does?

If I execute: In[1] := x = x Out[1] = x and then I evaluate the symbol x: ...
2k views

### How do you check if there are any equal arguments(even sublist) in a list?

I would like to set up a function which has to return True if at least two arguments of a given List are equal. So if I give {1,4,6,2} to the function it has to ...
1k views

### Function that counts the number of arguments of other functions

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 ...
3k views

### The difference between 0. and 0

I have a function for which 0 is a special case: f[A___, 0, B___] := 0 But since I am doing numerics, sometimes in the course ...
1k views

### How to Combine Pattern Constraints and Default Values for Function Arguments

EDIT: 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 ...
254 views

### What is the difference between defining a function and specifying the type of argument, versus applying a test to that argument?

Say I want to create a function that evaluates differently based on what type of argument is given. I've found two ways of doing this, ...
1k views

### Using patterns in pure functions

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

### Pattern that matches colors

Suppose I'm writing a function that takes a color as a parameter; for example: drawShape[color_] := Graphics[{Style[Disk[], color]}]; But if the caller inputs an ...
496 views

### SetAttributes[f,Flat]: Why the order dependence?

I'm experiencing a strange phenomenon. Here's a (quite artificial) test case: The following definition work just fine: ...
2k views

### Pick elements of largest absolute value

For example, given list = {{1, -3, -5}, {2, 1, 6}, {0, 2, 4}, {-9, 2, 6}} should return: {-5, 6, 4, -9} Updated I found ...
1k views

### Picking random items out of a list only once

I'm trying to create a function that randomly returns a value from a list but remembers the values that have been given before. At the end when the list is empty it should return an empty list. ...
471 views

### Improving speed of code computing number of nonrepeating partitions

I need to answer the following for a number of parameters: How many ways can the integer $k$ be written as a sum of $n$ different integers ranging from $1$ to $m$? My initial attempt was the ...
496 views

### Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
360 views

### Writing functions with “Method” options

I'd like to implement several behaviors for a particular function using a Method option added to the function definition: ...
423 views

### How can I export my learned ClassiferFunction[] and PredictorFunction[]s?

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

### Is it possible to change the order that symbol definitions are checked? (DownValues vs UpValues)

Suppose I have the function f with the following definition assigned to it: ...
554 views

### Quick way to use conditioned patterns when defining multi-argument function?

I have a simple function that is supposed to only accept numeric values (i.e. complex/real numbers and constant symbols e.g. Pi, E). $$f(a,b,c)=a+b+c$$ Edit: I should have chosen a less simple ...
275 views

### Clean and handy Options management/filtering

the case I want to be able to create a function with some default options but also without need to add full explicit list of options available for it. And then inside I want to be able to filter ...
683 views

### Lazy lists of Tuples and Subsets

I'm trying to build a lazy list that evaluates the n'th m-tuple or subset of a given list using Mathematicas ordering without calculating all the Tuples. The purpose is to allow for example the ...
1k views

### What is Mathematica's equivalent to MATLAB's filter function?

The MATLAB code filter(0.5,[1, -0.5], [1:10]) is equivalent to Rest@FoldList[(#1 + #2)/2. &, 0, Range[10]] I don't ...
784 views

### How can I evaluate only a single step of a recursive function?

Let's say have a simple recursive function for the Fibonacci sequence f[0] := 1 f[1] := 1 f[n_] := f[n - 1] + f[n - 2] but I want to see how it will expand in a ...
420 views

### Skipping “middle” Optional Arguments

Is there a way to call a function where the "middle" arguments should use their default value while specifying values for the "right-most" arguments? For example, given this function: ...
738 views

### How to create custom Graphics primitive?

How to create custom Graphics primitive? It should have the following properties, resembling properties of built-in geometric figures, like ...