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

62
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
446 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 ...
16
votes
2answers
787 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 ...
17
votes
3answers
761 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: ...
42
votes
6answers
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 ...
26
votes
4answers
595 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 ...
20
votes
1answer
418 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 ...
16
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 ...
20
votes
4answers
689 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 ...
14
votes
2answers
375 views

Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
16
votes
9answers
978 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 ...
37
votes
6answers
2k 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 ...
29
votes
5answers
902 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 ...
18
votes
3answers
359 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: ...
6
votes
3answers
312 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 ...
35
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 ...
22
votes
6answers
1k 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 ...
23
votes
6answers
447 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 ...
15
votes
1answer
667 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 ...
15
votes
2answers
538 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, ...
11
votes
3answers
412 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? ...
13
votes
2answers
363 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: ...
16
votes
3answers
550 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 ...
15
votes
1answer
254 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 ...
8
votes
3answers
553 views

Inverting a function in a certain region

InverseFunction works well for globally invertible functions, like f = 2*# + 2 &; InverseFunction[f] ...
13
votes
3answers
458 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
413 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 ...
11
votes
5answers
600 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
2answers
1k 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 ...
4
votes
2answers
155 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 ...
35
votes
9answers
7k 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 ...
31
votes
2answers
919 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 ...
21
votes
3answers
1k 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 ...
11
votes
1answer
417 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 ...
18
votes
4answers
333 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 ...
10
votes
4answers
294 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 ...
15
votes
6answers
891 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 ...
7
votes
4answers
491 views

Turn expression into function

I'm new to Mathematica and I spent the last hour trying to make the expression ...
14
votes
1answer
238 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
4answers
432 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: ...
19
votes
2answers
264 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 ...
12
votes
2answers
229 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 ...
7
votes
2answers
2k views

Building matrices by attaching vectors (columns) and matrices

Having the need to attach a column to a matrix or to join matrices to make longer rows is an operation that I use very frequently and I find the Join function ideal ...
7
votes
3answers
298 views

Composition of mappings not working as expected

I have two functions $f,g:\mathbb{R}^2 \to \mathbb{R}^2$ and I define a third one $h:\mathbb{R}^2 \to \mathbb{R}^2$ as the composition $$h(x,y) = g(f(x,y))$$ I'm trying to get this function into ...
4
votes
2answers
2k views

How to find (numerical) value of a derivative at point?

I have the following function: f[0, 0] = 0 f[x_, y_] := Exp[-(x^2 + y^2)^(-1)] How do I find its partial derivatives at any given point, including $(0,0)$? This ...
2
votes
4answers
1k views

How to write a differential operator in Mathematica

I have a very basic question. I am trying to code the LHS of the differential equation: ...
3
votes
3answers
328 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: ...
3
votes
1answer
231 views

NestList with a list inside?

I'm new to Mathematica, and was looking for more efficient ways to implement the Do loop below. a, ...
2
votes
1answer
208 views

Make a scatter plot

Considering I have weather data for last 10 years for London, how can I make a scatter plot that will show the previous day's temperature as a function from today's temperature?
24
votes
1answer
419 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 ...