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

60
votes
4answers
2k 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 ...
15
votes
2answers
647 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
630 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: ...
41
votes
6answers
1k 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 ...
22
votes
4answers
386 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 ...
25
votes
4answers
528 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
371 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 ...
18
votes
4answers
547 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
344 views

Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
16
votes
9answers
852 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 ...
36
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 ...
16
votes
5answers
1k 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 ...
35
votes
3answers
968 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 ...
21
votes
4answers
619 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
1answer
572 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 ...
13
votes
2answers
345 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: ...
15
votes
1answer
222 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 ...
22
votes
6answers
415 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
3answers
311 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: ...
15
votes
2answers
480 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, ...
13
votes
3answers
445 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 ...
14
votes
3answers
479 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 ...
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 ...
7
votes
3answers
487 views

Inverting a function in a certain region

InverseFunction works well for globally invertible functions, like f = 2*# + 2 &; InverseFunction[f] ...
6
votes
3answers
283 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 ...
32
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 ...
29
votes
2answers
784 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 ...
11
votes
1answer
376 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 ...
16
votes
4answers
275 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 ...
9
votes
4answers
247 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 ...
14
votes
1answer
230 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
351 views

Turn expression into function

I'm new to Mathematica and I spent the last hour trying to make the expression ...
18
votes
2answers
245 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
218 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
486 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 ...
7
votes
2answers
1k 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 ...
6
votes
4answers
345 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
272 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
147 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 ...
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
935 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: ...
24
votes
1answer
370 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 ...
19
votes
3answers
344 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: ...
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 ...
14
votes
5answers
740 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. ...
9
votes
3answers
278 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? ...
6
votes
3answers
844 views

Simulate MATLAB's meshgrid function

Here is MATLAB's meshgrid. I came up with these implementations in Mathematica: ...
11
votes
3answers
254 views

Pass by reference for an option argument

Pass by reference can be faked by using HoldAll or something similar in the definition of a "Function". But can pass by reference be faked for symbols passed as ...
8
votes
2answers
322 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 ...