Questions tagged [function-construction]

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.

Filter by
Sorted by
Tagged with
97 votes
4 answers
9k 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 ...
magma's user avatar
  • 5,280
75 votes
7 answers
5k 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 ...
David's user avatar
  • 14.9k
75 votes
7 answers
6k views

How to avoid collision between 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 ...
Andy Ross's user avatar
  • 19.2k
50 votes
10 answers
13k 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 ...
chyanog's user avatar
  • 15k
50 votes
5 answers
3k 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 ...
einbandi's user avatar
  • 4,024
48 votes
6 answers
6k 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 ...
orome's user avatar
  • 12.8k
47 votes
2 answers
7k views

Is there any algorithm that runs faster in Mathematica than in C or Fortran?

I'm just curious. My friend just told me that Mathematica is mostly for symbolic calculation and not efficient for Numerical computations. He told me that's the reason most of the people don't use ...
Gummala Navneeth's user avatar
46 votes
4 answers
4k views

Function 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: ...
yulinlinyu's user avatar
  • 4,795
44 votes
4 answers
4k 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 ...
Nothingtoseehere's user avatar
44 votes
5 answers
2k 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 ...
Mr.Wizard's user avatar
  • 270k
40 votes
2 answers
1k 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 ...
Simon Woods's user avatar
  • 84.6k
40 votes
2 answers
2k views

How can I export my learned ClassiferFunction[] and PredictorFunction[]s?

Mathematica 10 provides beautiful high-level machine learning functionality. Sadly, the learned functions once created are rather opaque objects. I need to use them in other projects, so here is my ...
user5601's user avatar
  • 3,581
40 votes
2 answers
2k views

Variable naming changes everything

Bug fixed in 10.0.0 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 ...
5xum's user avatar
  • 503
39 votes
3 answers
3k 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 ...
Gianpiero Cea's user avatar
37 votes
3 answers
964 views

Is there a comprehensive list of functions with operator forms?

As of version 10, Mathematica sports operator forms for many functions like Map, SortBy, ...
Martin Ender's user avatar
  • 8,734
37 votes
3 answers
994 views

Can we intelligently control evaluation in Thread?

This is a bid at creating a canonical Q&A. Many questions have been asked that come down to the fact that Thread evaluates its first argument before threading ...
Mr.Wizard's user avatar
  • 270k
37 votes
2 answers
3k 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 ...
U.T.'s user avatar
  • 563
37 votes
3 answers
3k 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 ...
StackExchanger's user avatar
36 votes
2 answers
2k 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 ...
rogerl's user avatar
  • 4,209
34 votes
4 answers
1k 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 ...
M.R.'s user avatar
  • 31.2k
34 votes
3 answers
3k views

Is there any way to define pure functions with optional arguments?

For example consider the following function: Function[{u,v},u^2+v^4] Is there anyway to define default values for the variables ...
M6299's user avatar
  • 1,461
34 votes
1 answer
1k 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 ...
Nasser's user avatar
  • 137k
34 votes
2 answers
1k views

Custom atomic expressions - modern tutorial

Atomic but sophisticated expressions are all around for a long time: Graph SparseArray. More are coming with each new release, ...
Kuba's user avatar
  • 136k
32 votes
3 answers
3k 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 ...
Jane T.'s user avatar
  • 485
32 votes
1 answer
4k views

How does Return work?

It is not completely clear to me how Return[] works. The documentation says: Return[expr] returns the value expr from a ...
Szabolcs's user avatar
  • 233k
31 votes
3 answers
826 views

Why does removing a function and defining it on the same line not work?

Why do the two pieces of code below yield rather different results? The only difference is that in the first one the function definition is in the same line as the ...
Soldalma's user avatar
  • 1,289
30 votes
9 answers
3k 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 ...
sjdh's user avatar
  • 7,607
30 votes
5 answers
4k views

Second level depth pure function?

I have the following working construction: Select[ln125, # == Nearest[ln125, 551.748][[1]] &] Here, ln125 is a one ...
DimG's user avatar
  • 608
30 votes
1 answer
11k views

Module with "local functions"

I am trying to use a Module having "local functions", i.e., those which I need to define only inside this module. So I tried this: ...
Pavithran Iyer's user avatar
29 votes
6 answers
3k 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 ...
Simon Woods's user avatar
  • 84.6k
28 votes
3 answers
1k views

Writing functions with "Method" options

I'd like to implement several behaviors for a particular function using a Method option added to the function definition: ...
dionys's user avatar
  • 4,301
27 votes
4 answers
17k views

Turn expression into function

I'm new to Mathematica and I spent the last hour trying to make the expression ...
Beni Bogosel's user avatar
27 votes
4 answers
5k 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 ...
Phira's user avatar
  • 755
26 votes
4 answers
816 views

Is there a GraphicsPrimitiveQ (or a complete list of Heads of graphics primitives)?

For various reasons related to workflow associated with creating figures for journals, I am creating functions that will accept graphics primitives and a set of options and spit out a ...
march's user avatar
  • 22.9k
26 votes
6 answers
875 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 ...
bobthechemist's user avatar
26 votes
4 answers
1k views

Quick way to use conditioned patterns when defining multi-argument function?

I have a simple function that is supposed to only accept numeric values (i.e. complex/real numbers and constant symbols e.g. Pi, E). $$f(a,b,c)=a+b+c$$ Edit: I should have chosen a less simple ...
seismatica's user avatar
  • 5,061
24 votes
3 answers
1k views

Modeling the spread of an infection in networked computers

I would like to show the iterative stages of infection for problem 2 in this link. In case the link dies, I have copied the text for the problem below: One hundred computers are connected in a ...
martin's user avatar
  • 8,152
24 votes
4 answers
3k 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? ...
Hp Radojewski Schäfer Von's user avatar
24 votes
3 answers
673 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: ...
a06e's user avatar
  • 11.1k
23 votes
3 answers
981 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: ...
celtschk's user avatar
  • 19.1k
23 votes
3 answers
2k views

How to find the name of the current function?

I would like to know the name of the current function from within that function. For example, consider the following code ...
Ian Hinder's user avatar
  • 2,125
23 votes
2 answers
734 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: ...
celtschk's user avatar
  • 19.1k
23 votes
1 answer
1k 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 ...
jVincent's user avatar
  • 14.8k
22 votes
9 answers
3k 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 ...
Gianpiero Cea's user avatar
22 votes
5 answers
9k 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 ...
Ian Hincks's user avatar
  • 1,849
22 votes
5 answers
809 views

Distributing function arguments with function compositions. How to compute $(f + g^2)(x) = f(x) + g(x)^2$?

Suppose I have two functions f and g. To compute $f + g$ evaluated at a point $x$, I know that one can use ...
user32416's user avatar
  • 1,193
22 votes
2 answers
2k 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 ...
Suzan Cioc's user avatar
  • 2,023
22 votes
3 answers
2k views

How to define a function that is Listable for some but not all arguments?

I want to define a function f[x,y] that is Listable for only the first argument, not the second. If we use ...
renphysics's user avatar
  • 1,550
22 votes
2 answers
484 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 ...
G. H. Hardly's user avatar
21 votes
4 answers
1k views

Skipping "middle" Optional Arguments

Is there a way to call a function where the "middle" arguments should use their default value while specifying values for the "right-most" arguments? For example, given this function: ...
Mike Pierce's user avatar

1
2 3 4 5
49