49

This shows a way to parametrise a line using the method suggested by Rahul Narain in a comment, i.e. using Fourier to approximate the data with a set of sinusoids. I use Rationalize to convert all the reals back to rationals, this isn't necessary but it makes the expression look more like those used in Wolfram Alpha. param[x_, m_, t_] := Module[{f, n = ...


45

This now has been discussed in Wolfram blog posts by Michael Trott: Part 1: Making Formulas… for Everything — From Pi to the Pink Panther to Sir Isaac Newton Part 2: Using Formulas... for Everything — From Complex Analysis Class to Political Cartoons to Music Album Covers Part 3: Even More Formulas… for Everything—From Filled Algebraic Curves to the Twitter ...


38

Plot uses two different algorithms depending on whether PerformanceGoal is set to Quality or Speed. Yaroslav Bulatov wrote here, i.e. in the link provided by Szabolcs in a comment above, that: Plot starts with 50 equally spaced points and then inserts extra points in up to MaxRecursion stages... According to Stan Wagon's Mathematica book, Plot ...


36

Wanna listen to a story? :) It was around 2002 when I finally became fed up with ParametricPlot3D[] and its inability to adaptively plot space curves. Recall that this was the old Graphics[] system where all the pictures were effectively done in PostScript. Thus, I set out to look for a way to adaptively plot curves in general. I was at the time very ...


36

First, an idomatic, but slow version. s1 = 1/GoldenRatio // N; s2 = 1/GoldenRatio // N; stem = {0., 0., 1.}; thickness = 0.15; branches = Table[RotationMatrix[2. k Pi/3., {0, 0, 1}].{Cos[Pi/4.], 0., Sin[Pi/4.]}, {k, 0, 2}]; data0 = {Join[{{0., 0., 0.}}, {stem}, branches, {{thickness, 1., 0.}}]}; iteration[data_] := Block[{U}, Flatten[Table[ U = data[[...


29

Version 9 answer - use built-in functionality The symbols Image`CreateHDRI and Image`ToneMapHDRI were present in version 8 but didn't seem to do anything. In version 9 there is functioning code behind them. This is all undocumented, and therefore liable to change before it is officially released, but here is what I've managed to dig up. Image`CreateHDRI ...


27

Here I will attempt to provide a basic implementation of the random forest algorithm for classification. This is by no means fast and doesn't scale very well but otherwise is a nice classifier. I recommend reading Breiman and Cutler's page for information about random forests. The following are some helper functions that allow us to compute entropy and ...


22

One can use CellularAutomaton and apply only one rule: do not allow 4 white cells together! ClearAll[f]; f@{{1, 1, _}, {1, _, _}, {_, _, _}} = 0; f@{{_, 1, 1}, {_, _, 1}, {_, _, _}} = 0; f@{{_, _, _}, {_, _, 1}, {_, 1, 1}} = 0; f@{{_, _, _}, {1, _, _}, {1, 1, _}} = 0; f@{_, {_, x_, _}, _} := If[Random[] < 0.1, 1, x]; Here 0 and 1 mark black and white ...


21

As of Version 10 , Mathematica has a built in function Classify, which implements support vector machines and some other common machine learning algorithms. trainingset = {1 -> "A", 2 -> "A", 3.5 -> "B", 4 -> "B"}; classifier = Classify[ trainingset, Method -> "SupportVectorMachine"];


21

The Mathematica Journal has a nice article on SVM's: A Flexible Implementation for Support Vector Machines, with an accompanying notebook and .m file providing an SVM implementation.


21

This was supposed to be a comment to Simon's answer, but it's gotten too long. Still, I wanted to share a somewhat cleaned-up version of Simon's Fourier-fitting function param[] (which I have renamed to FourierCurve[]): FourierCurve[x_, m_, t_, tol_: 0.01] := Module[{rat = Rationalize[#, tol] &, fc}, fc = Take[Chop[Fourier[x, FourierParameters -> {-...


21

You can do: x[[2 ;; -2, 2 ;; -2]] = 0; x or ReplacePart[x, {i, j} -> 0 /; And @@ MapThread[Less, {{1, 1}, {i, j}, Dimensions@x}]]


21

My answer is based on a modification of a binary heap. Basically the construction looks something like this. We start with a binary tree: Notice that if we label the nodes breadth-first, the labels have an interesting property. Each parent node $n$ has two children, $2n$ and $2n+1$. This also works in reverse: the parent of node $n$ is node $\left\...


20

Played with some image processing functions, get some rough procedure. Import the test image: img = Import["http://i.stack.imgur.com/H2Ksg.jpg"]; Do some gamma adjust to emphasize the edge: img // ImageAdjust[#, {0, 0, 5}] &; Draw rough edges: GradientFilter[%, 2, "NonMaxSuppression" -> True] // ImageAdjust Binarize and dilate it to form ...


20

This answer is going to be a bit of a sprawl. Please read on. I am going to present several methods of simulation, hopefully in increasing order of performance. Method 1 We can carry out the filling of seats, at least as I understand the puzzle, quite literally like this: fillseats[seats_List] := ReplacePart[seats, {{1}, {2}} + RandomChoice @ ...


19

Higher-order SVD (in sense of Tucker decomposition) of the matrix $M$ with dimensions $d_1\times d_2\times\cdots\times d_n$ is $$ M_{i_1,i_2,\dots,i_N} = \sum_{j_1} \sum_{j_2}\cdots \sum_{j_N} s_{j_1,j_2,\dots,j_N} u^{(1)}_{i_1,j_1} u^{(2)}_{i_2,j_2} \dots u^{(N)}_{i_N,j_N}, $$ where $s$ is the core tensor and $u^{(i)}$ is the orthogonal matrix. The matrix ...


19

Below is given a solution derived with ILP combinatorial optimization: The total of the assigned values to the $5 \times 5$ table is $61$. I called in the comments this approach to be "brute force" because of the generation of a larger number of variables and conditions and pushing them to Maximize or LinearProgramming. Same approach was used for my answer ...


18

Here's my take using NestList cm[n_] := NestList[# + 1 &, Join[Range[n/2 + 1], Reverse@Range[n/2]], n - 1] Then cm[11] Here's a FoldList version (just as fast): cmf[n_] := FoldList[#1 + #2 &, Join[Range[n/2 + 1], Reverse@Range[n/2]], ConstantArray[1, n - 1]] The above methods according to the benchmarks posted are already as fast ...


18

1. Bisection algorithm The algorithm itself is fairly straightforward and "fast" in some sense: the number of iterations is roughly Log2 of the ratio of the initial interval length and the desired accuracy. My point is that the time spent by Flatten, Select, Thread, etc. in your function is fairly small. The significant time-waster is reevaluating the ...


18

Update: If you want 4-neighborhood, you can use MorphologicalComponents to do most of the work, which is fast and easy to implement (that was my original attempt, see below). But I don't think this can be adapted for 8-neighborhood. For 8-neighborhood, I would implement the standard 2-pass connected component labeling algorithm (this might be what ...


18

I also got angry about those randomly picked and ill-implemented benchmarks by the Julia team. I appreciate their efforts (jit compilers are useful), but the Fibonacci example was straight away ridiculous. Here is a compiled quick sort implementation that employs a stack in order to avoid recursive calls. The problem with recursion in CompiledFunctions is ...


17

Preface Below, you will find two different solutions. For understanding the problem itself, the first, iterative solution is better suited since it gives insight in how the solution can be found without directly executing the instructions given as input. Iterative Solution Detailed explanation To explain the idea behind this approach let us work with a ...


17

Earlier in the summer I had written the following for How to obtain adaptive sampling as in Plot function?. It is something like J. M.'s technique. But instead of a new version of Mathematica coming along, my brain turned on and I discovered a workaround using FunctionInterpolation. I've been considering posting the following as an answer to that question,...


16

This is an incomplete answer; I will continue it tomorrow. Work In Progress: errors may abound. Preamble hat-tip to Leonid For the variations with custom test or ordering functions we can snoop on applications of that function to deduce the algorithm that is used. In the case of the default methods we must rely on observed complexity and guesswork ...


16

RandomPartition[n_, p_] := Module[{r}, r = RandomSample[Range[n - 1], p - 1] // Sort; AppendTo[r, n]; Prepend[r // Differences, r[[1]]] ] RandomPartition[100, 16] (* {4, 1, 4, 3, 12, 5, 13, 3, 9, 8, 2, 2, 12, 11, 1, 10} *) RandomPartition[100, 16] // Total (* 100 *) Testing: And @@ Table[ n = RandomInteger[100000]; p = RandomInteger[{1, n}];...


16

In addition to Carl Woll's post: Computing the pseudoinverse of a the graph Laplacian matrix (a.k.a. the KirchhoffMatrix) is very expensive and in general leads to a dense matrix that, if the graph is too large, cannot be stored in RAM. In the case that you have to compute only a comparatively small block of the resistance distance matrix, you can employ ...


15

Disclaimer: This is not an implementation of the Random Forest Algorithm. Also, while I have on occasion used random florists, until today I had not heard of the Random Forest Algorithm. I poked around a bit on the Net and learned that these take subsamples of data, subsampling the variables as well, and form decision trees for the subsetted subsamples. ...


15

Original Bresenham I guess I can come of with a somewhat shorter implementation without using Reap and Sow. If someone is interested, it follows almost exactly the pseudo-code here bresenham[p0_, p1_] := Module[{dx, dy, sx, sy, err, newp}, {dx, dy} = Abs[p1 - p0]; {sx, sy} = Sign[p1 - p0]; err = dx - dy; newp[{x_, y_}] := With[{e2 = 2 err}, {If[...


15

One function comes to mind that already implements matching of multidimensonal rules: CellularAutomaton. Allow me to represent your board data like this: board = SparseArray[ a /. h_[x_, y_] :> ({-y - 1, x + 1} -> h) /. {black -> ●, white -> ○}, {7, 7}, " "]; For my example I shall show a generic 3x3 rule operation, but this can easily be ...


15

You asked for shortened, improved, so here it is using RegularExpressions: StringCases[string, RegularExpression["(\\D+)(\\d+)"] :> {"$1", ToExpression["$2"]}] {{"ABC", 123}, {"DEFG", 456}, {"HI", 89}, {"UZXX", 1}} Here's a version using StringSplit: Partition[StringSplit[string, RegularExpression["(\\d+)"] :> FromDigits @ "$1"], 2]


Only top voted, non community-wiki answers of a minimum length are eligible