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

23
votes
4answers
494 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 ...
65
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 ...
20
votes
2answers
919 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 ...
18
votes
3answers
949 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: ...
46
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 ...
25
votes
1answer
474 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 ...
26
votes
4answers
619 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 ...
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 ...
21
votes
4answers
796 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 ...
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 ...
38
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
949 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 ...
14
votes
2answers
390 views

Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
6
votes
3answers
332 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 ...
25
votes
6answers
494 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 ...
19
votes
3answers
377 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: ...
9
votes
3answers
618 views

Inverting a function in a certain region

InverseFunction works well for globally invertible functions, like f = 2*# + 2 &; InverseFunction[f] ...
36
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
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 ...
15
votes
1answer
745 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 ...
23
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 ...
14
votes
2answers
612 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
477 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
387 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
600 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
293 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 ...
13
votes
3answers
479 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
463 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 ...
17
votes
2answers
368 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
1k views

Simulate MATLAB's meshgrid function

Here is MATLAB's meshgrid. I came up with these implementations in Mathematica: ...
14
votes
1answer
243 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? ...
12
votes
2answers
232 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 ...
11
votes
5answers
690 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
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 ...
4
votes
2answers
163 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
349 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: ...
38
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
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 ...
27
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 ...
11
votes
1answer
454 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 ...
20
votes
4answers
378 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
345 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
936 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
725 views

Turn expression into function

I'm new to Mathematica and I spent the last hour trying to make the expression ...
14
votes
7answers
645 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 ...
6
votes
4answers
506 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: ...
20
votes
2answers
281 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 ...
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
327 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
3k 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 ...