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

47
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 ...
28
votes
6answers
923 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 ...
28
votes
2answers
592 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 0s for blank space and 1s for filled spaces ...
27
votes
9answers
6k 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 ...
26
votes
6answers
973 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 ...
24
votes
2answers
406 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 ...
22
votes
6answers
670 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 ...
22
votes
1answer
406 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" ...
21
votes
3answers
658 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 ...
21
votes
1answer
271 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 ...
15
votes
8answers
536 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 ...
15
votes
4answers
238 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 ...
14
votes
5answers
762 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 ...
14
votes
5answers
602 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. ...
14
votes
6answers
564 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 ...
14
votes
3answers
212 views

What's wrong with this pattern of the form Except[Repeated[…]]?

I'm trying to build a head that recognizes molecules. Here's the code ...
14
votes
3answers
348 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: ...
13
votes
2answers
298 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: ...
13
votes
3answers
151 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 ...
13
votes
3answers
387 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 ...
12
votes
2answers
183 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 ...
12
votes
1answer
143 views

Is it possible to Clear all variables (but not functions)?

I have written a Mathematica script in which I define functions and variables. Here is a vastly simplified example: ...
12
votes
3answers
272 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 ...
12
votes
1answer
196 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? ...
11
votes
4answers
287 views

Assessing argument type in set delayed function definitions

I'm wondering how to properly assess the type of arguments passed to functions defined with :=. I want my functions to be the most efficient, unambiguous and clear ...
11
votes
2answers
241 views

Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
11
votes
1answer
127 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 ...
11
votes
2answers
212 views

can a ColorFunction have side effects?

Can anyone explain this (to me) odd behavior. If I run this code once (fresh kernel) it works as intended. ...
10
votes
3answers
384 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 ...
10
votes
5answers
317 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 ...
10
votes
3answers
463 views

Passing down arguments

In R, one can use ... to pass arguments down to another function. For example ...
10
votes
2answers
199 views

Functions that remember their values

Can someone explain what is going on with the following ... func[y_] := func[y] = (Print["Hello world !!!"];) func[1] Hello world !!! ...
10
votes
2answers
232 views

Proper way to add vertices to an adjacency matrix

I'm looking for a robust way to add vertices to a graph by modifying its AdjacencyMatrix. Here's what I have so far: ...
10
votes
2answers
363 views

How to plot a barycentric line

I want to plot a barycentric function on an equilateral triangle (ternary plot). For example f1 = {Abs[Sin[x]], Mod[x, 2], Abs[Cos[x]]}; At the moment I evaluate ...
10
votes
2answers
295 views

Constructing functions aware of the number of output arguments

In Mathematica, you can construct a function f to have different definitions based on its input arguments. For example, ...
10
votes
1answer
108 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 ...
10
votes
1answer
152 views

Modules that initialize themselves on first call

I use a lot of functions that extract a specific data item from a file with many data items. I want these functions to load data (slow) and return the item (fast) on first call, but just return the ...
10
votes
1answer
286 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 ...
10
votes
0answers
127 views

func::usage needs to be run twice?

There is an annoying problem that I can't figure out why it's happening. I have defined a usage for a my function tensorA: ...
9
votes
6answers
1k views

Recursive function with if-statement

I am trying to represent the following function definition in Mathematica: $$\begin{align*} f(1)&=1 \\ f(2n)&= \begin{cases}f(n) & \text{if}\space n\equiv0\pmod{2} \\ 2f(n) & ...
9
votes
4answers
260 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 ...
9
votes
2answers
264 views

NestList on a function with more arguments

I'd like to know if it is possible to use NestList on a regular function with more arguments, such as: ...
9
votes
2answers
376 views

Converting ConditionalExpression to Piecewise

I have Solve[] return a list like ...
9
votes
2answers
152 views

How can I get the right hand side of a delayed expression?

Imagine there is a given function f, defined with SetDelayed, say f[x_] := Sin[x]^2 + Cos[x]^2. Is it possible to get rhs of ...
9
votes
2answers
196 views

Define Log so that negative reals evaluate on lower edge of branch

I need to get Mathematica to evaluate the logarithm of a negative real number using the lower branch instead of the upper branch, so that while ...
9
votes
1answer
334 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 ...
9
votes
2answers
239 views

Defining a ForEach function

Consider the following function definition: ForEach[iterators__] := Table[#, iterators] &; Two questions about it: I. It works perfectly if you call it like ...
9
votes
3answers
127 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 ...
9
votes
1answer
305 views

Functional programming and Do loops

I'm writing a Monte Carlo simulation. I'm using a Do loop to create the different simulations, iterating over different ...
8
votes
2answers
203 views

Generating a position lookup function for an arbitrary list of integers

In my code, I generate a list of integers called numlist. Here is an example numlist: ...

1 2 3 4 5