The Stack Overflow podcast is back! Listen to an interview with our new CEO.

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
93
votes
4answers
7k 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 ...
68
votes
7answers
4k 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 ...
64
votes
6answers
5k 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 ...
49
votes
10answers
11k 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 ...
46
votes
4answers
2k 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 ...
43
votes
5answers
1k 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 ...
41
votes
4answers
3k 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: ...
39
votes
5answers
2k 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 ...
39
votes
1answer
958 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 ...
39
votes
2answers
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 ...
38
votes
4answers
3k 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 ...
38
votes
2answers
5k 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 ...
38
votes
3answers
2k 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 ...
36
votes
2answers
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 ...
34
votes
3answers
779 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, ...
34
votes
3answers
772 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 ...
33
votes
4answers
957 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 ...
33
votes
2answers
2k 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 ...
33
votes
1answer
905 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 ...
33
votes
1answer
1k 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 ...
32
votes
3answers
2k 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 ...
31
votes
3answers
681 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 ...
31
votes
2answers
2k 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 ...
30
votes
3answers
2k 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 ...
28
votes
8answers
2k 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 ...
28
votes
6answers
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 ...
28
votes
1answer
3k 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 ...
27
votes
4answers
3k 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 ...
26
votes
4answers
577 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 ...
26
votes
6answers
751 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 ...
26
votes
4answers
3k views

Second level depth pure function?

I have the following working construction: Select[ln125, # == Nearest[ln125, 551.748][[1]] &] Here, ln125 is a one ...
26
votes
3answers
749 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: ...
24
votes
3answers
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 ...
24
votes
4answers
2k 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? ...
23
votes
3answers
754 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: ...
23
votes
3answers
550 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: ...
22
votes
1answer
8k 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: ...
22
votes
2answers
443 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 ...
21
votes
9answers
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 ...
21
votes
5answers
670 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 ...
21
votes
2answers
549 views

Should I always be using Module in functions unless I explicitly want global variables?

I define functions a ton. In the past, I've mostly just defined my functions like: myFunc[var1_]:=( var2=var1^2; Return@var2; ) And I haven't run into too ...
21
votes
2answers
471 views

Custom atomic expressions - modern tutorial

Atomic but sophisticated expressions are all around for a long time: Graph SparseArray. More are coming witch each new release,...
21
votes
2answers
394 views

Kernel inexplicably hangs if I define a pure function without suppressing output

Bug introduced in 9.0 and fixed in 10.0.2 Save any unsaved work before trying as it may crash Mathematica and other programs by filling up the memory! In v9.0.1.0 on OSX 10.8.5, if I start a new ...
20
votes
5answers
6k 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 ...
20
votes
2answers
655 views

Using several anonymous functions mixed together

This works: list // BarChart[#[[2]], ChartLabels -> DateString @@@ #[[1]], ChartStyle -> "Pastel"] & This doesn't: ...
20
votes
2answers
627 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: ...
20
votes
3answers
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 ...
20
votes
3answers
1k 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 ...
20
votes
2answers
1k 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 ...
20
votes
1answer
967 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 ...