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.
48
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 ...
30
votes
6answers
961 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
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 ...
28
votes
2answers
603 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 ...
28
votes
2answers
506 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
6answers
1k 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 ...
23
votes
1answer
288 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 ...
22
votes
6answers
724 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
410 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
693 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
4answers
512 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 ...
15
votes
8answers
544 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
242 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
784 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
609 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
588 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
7answers
464 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 ...
14
votes
3answers
213 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
364 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
307 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
157 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
393 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 ...
13
votes
1answer
199 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? ...
13
votes
1answer
135 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 ...
12
votes
2answers
196 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
2answers
187 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 ...
12
votes
1answer
148 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
291 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 ...
11
votes
4answers
297 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
246 views
Using several anonymous functions mixed together
This works:
list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] &
This doesn't:
...
11
votes
2answers
303 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, ...
11
votes
2answers
213 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
446 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
335 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
484 views
Passing down arguments
In R, one can use ... to pass arguments down to another function. For example
...
10
votes
2answers
204 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
239 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
373 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
1answer
113 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
159 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
294 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
131 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
263 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
292 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
394 views
9
votes
2answers
155 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
207 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
2answers
279 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 ...
9
votes
1answer
359 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 ...



