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.

learn more… | top users | synonyms

25
votes
2answers
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 ...
71
votes
4answers
3k 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 ...
23
votes
4answers
582 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 ...
23
votes
3answers
1k 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: ...
26
votes
4answers
1k 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 ...
50
votes
7answers
2k 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 ...
27
votes
1answer
539 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 ...
27
votes
4answers
678 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 ...
26
votes
6answers
563 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 ...
17
votes
5answers
2k 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 ...
32
votes
5answers
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 ...
17
votes
9answers
1k 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 ...
13
votes
3answers
606 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? ...
14
votes
2answers
266 views

f[arg1, arg2,…,argN] vs. f[{arg1, arg2,…,argN}]

I am trying to reproduce the API of a function (written in R) that accepts an arbitrary number of arguments and handles it the same way as it would handle a single argument that is a list of different ...
42
votes
6answers
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 ...
16
votes
1answer
865 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 ...
14
votes
7answers
705 views

A function that accepts a pair or a list of pairs

Probably a duplicate, but it's not easy to search on "lists". I have a function that accepts a list of lists, say {{a1, b1}, {a2, b2}, {a3, b3}} and performs some ...
15
votes
2answers
431 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 ...
23
votes
6answers
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 ...
20
votes
3answers
401 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: ...
17
votes
2answers
457 views

Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
14
votes
2answers
430 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: ...
6
votes
3answers
372 views

Using function with multiple definitions in Manipulate

I'm trying to use Manipulate to visually try out different values of lambda in a Box-Cox transformation. I've created a boxcox ...
29
votes
2answers
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 ...
20
votes
5answers
513 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 ...
17
votes
3answers
761 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 ...
1
vote
2answers
110 views

Expressions containing globally undefined symbols inside a function where they are defined

Consider the following code. f[a_,b_]:=x; Clear[a,b]; x=a+b; f[1,2] It returns a+b. However, from a certain viewpoint, one ...
9
votes
3answers
735 views

Inverting a function in a certain region

InverseFunction works well for globally invertible functions, like f = 2*# + 2 &; InverseFunction[f] ...
37
votes
3answers
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 ...
23
votes
3answers
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 ...
15
votes
2answers
701 views

Constructing functions with variable number of output arguments

In Mathematica, you can construct a function f to have different definitions based on its input arguments. For example, ...
15
votes
1answer
333 views

Multiple templates for a single user-defined function

How do I use the ::usage tag to allow the Mathematica v9 front end to know that there are multiple ways to call an overloaded function (a function that can have ...
15
votes
1answer
272 views

How to make a function like Set, but with a Block construct for the pattern names

How can we define a function that works like f[x_]=ComputeSomething[x] and treats x as a variable that does not have a value? ...
6
votes
1answer
164 views

Creating a Block from a list of rules

How can I create a function which works like Block but takes a list of rules as its first argument, rather than a list of assignments? The function needs to be ...
4
votes
2answers
176 views

How to achieve Set+Part like behaviour in custom Set function?

So I've been toiling away on my DataFrame package. I've been trying to get Set to work with it, but it seems it either can't be done (ie via ...
3
votes
3answers
442 views

Alternatives pattern in a function definition

I thought that I remembered a way to write a function definition using "|", but can't find documentation for it. So for example, I'd want to define: ...
32
votes
2answers
1k views

Variable naming changes everything

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 ...
13
votes
3answers
511 views

Is it possible to get the order of inputs when “overloading” an orderless function?

When working with symbolic matrix operations or other objects which don't have commutative multiplication, it would be nice to not have to constantly switch out times for ...
10
votes
2answers
556 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 ...
10
votes
4answers
409 views

How to pass a list of arguments into HoldAll

I have a list of arguments (which in reality is lengthy): arguments = {a, b, c} arguments2 = {a_, b_, c_} f[Sequence@@arguments2] := a + b + c Note: It seems ...
17
votes
2answers
395 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 ...
7
votes
3answers
2k views

Simulate MATLAB's meshgrid function

Here is MATLAB's meshgrid. I came up with these implementations in Mathematica: ...
6
votes
4answers
592 views

Function argument to default under certain condition

Inspired by this and this question (and how I handle this in practice), what is the best way to default a function value when a certain condition is met? For example, if a function is defined as: ...
6
votes
3answers
128 views

Explicit use of Evaluate not behaving the way I expect it to

I discovered a strange behavior of the Evaluate function. Case 1: ...
5
votes
2answers
2k views

Gram Schmidt Process for Polynomials

I want to implement the Gram Schimdt procedure to the vector space of polynomials of degree up to 5, i.e. I want to find an orthogonal basis from the set of vectors $v=(1,x,x^2,x^3,x^4,x^5)$. The ...
12
votes
5answers
822 views

define a function from a list

I would like to create a mapping from a list and I am wondering if there is a slick way of doing it. For example, consider the list ...
4
votes
3answers
206 views

Constructing a function with Flat and OneIdentity attribute with the property that otimes[a]:>a

I want to have a function (called otimes) with the following two properties: it has the attribute OneIdentity and ...
39
votes
9answers
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 ...
28
votes
1answer
609 views

How to augment the realm of functions Mathematica thinks it knows how to integrate symbolically

My question involves extending the functionality of Integrate over specific integrals in the most generic manner. Specifically, is it possible to "hack into" ...
20
votes
3answers
412 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: ...