Problem evaluating a complicated integral

Apologies for stating my problem poorly in the first instance, thank you for the help in narrowing down the issue. **Problem** For those interested, it's for the exact unbiased inverse of the generalized Anscombe Transform, as given in this paper: http://dx.doi.org/10.1109/TIP.2012.2202675. I'm trying to integrate, for a given value of $y$ and $\sigma$, the function $$ \int_{-\infty}^{+\infty} f_{\sigma}\left ( z \right ) \sum_{k=0}^{\infty}\left ( \frac{y^{k}\mathrm{e}^{-y}}{k!\sqrt{2\pi \sigma^{2}}} \mathrm{e}^{-\frac{\left ( z-k \right )^{2}}{2\sigma^{2}}} \right ) \mathrm{d}z $$ where $$ f_{\sigma}\left ( z \right ) = \left\\{\begin{matrix} 2\sqrt{z+\frac{3}{8}+\sigma^{2}}, & z > -\frac{3}{8}-\sigma^{2}\\\ 0, & z \leq -\frac{3}{8}-\sigma^{2} \end{matrix}\right. $$ which gives the equation in the reference below: $$ \int_{-\infty}^{+\infty} 2\sqrt{z+\frac{3}{8}+\sigma ^{2}}\sum_{k=0}^{\infty}\left ( \frac{y^{k}\mathrm{e}^{-y}}{k!\sqrt{2\pi \sigma^{2}}} \mathrm{e}^{-\frac{\left ( z-k \right )^{2}}{2\sigma^{2}}} \right ) \mathrm{d}z $$ In the reference, the values of the above function are tabulated, presumably in Matlab, for $\sigma \in \left \\{ 0.01,...,50 \right \\}$ and $y \in \left \\{0,...,200 \right \\}$. The authors have made this table available for download, but I want to do it myself. However, I can't get it to work - Mathematica won't evaluate it:               func[z_, y_, sig_] :=       Piecewise[{{2 Sqrt[z + 3/8 + sig^2],z > -3/8 - sig^2}},0.]*       Sum[((y^k )* Exp[-y])/(k! * Sqrt[2 \[Pi] sig^2]) *          Exp[-((z - k)^2) / (2 sig^2)], {k, 0, Infinity}]     NIntegrate[func[z, 5, 2], {z, -Infinity, Infinity}]      Have I made a mistake somewhere? Or misunderstood the integral/problem as given? **Update** A suggestion is to replace the infinite sum with an upper limit of ~50 as it converges quickly. This does allow Mathematica to now evaluate the integral.


Mathematica sporadically crashes on open

Sometimes, when I open Mathematica, while the opening splash screen still says "Initializing Kernel Connections", Windows will tell me that "Wolfram Mathematica 9 has stopped working". This will happen every time I try to open Mathematica for a while, but then just as randomly as it started, it will stop, and I'll be able to open Mathematica again with no problems. When it stops working, I'm given the option to Debug it, but all I can tell is that it's a segmentation fault that seems to be caused by dereferencing a null pointer. Interestingly, MathKernel still runs fine even when Mathematica is refusing to launch. Does anyone know how I can start fixing/investigating the cause of this? Edit:   Version: Mathematica Version 9.0.1.0, Microsoft Windows 64-bit   OS: Windows 8


Rearranging a matrix

I would like to convert a matrix which has a structure like this:               {{"A", 10, "D", 1},{"B", 3, "A", 2},{"C", 7, "B", 3},{"D", 6, "C", 4}}//MatrixForm//Print;      into one that looks like this:               {{"A", 10, "A", 2},{"B", 3, "B", 3},{"C", 7, "C", 4},{"D", 6, "D", 1}}//MatrixForm//Print;      Is there a way to do this that still works when column 1 is not in alphabetical order.


How can I set different opacity values for the background of a ListPlot

In the following example:               ListPlot[{1, 2, 3}, Background -> Green]      how can I set the `Opacity[]` for the background such that the opacity increases from top to bottom?


Take part of image under locator

How to create Manipulator with Locator to take part of an image? ![enter image description here](http://i.stack.imgur.com/Db9AG.png)


Complex line integral

Can someone recommend an online article or introductory tutorial that will show me how to do real and complex line integrals using _Mathematica_?


Porting code from MATLAB

I'd like to switch from MATLAB to Mathematica for my research in digital signal processing. I used Mathematica a lot during the '90s but I haven't used it since then, so I might as well be a complete newbie. As a first experiment I tried to port the following MATLAB function (a slow implementation of CQT):               function cq= slowQ(x, minFreq, maxFreq, bins, fs) % x must be a row vector          Q = 1/(2^(1/bins)-1);     maxK = ceil(bins*log2(maxFreq/minFreq));     maxN = ceil(Q*fs/minFreq);     if size(x,2) < maxN         x(end+1:maxN) = 0;     end          for k=1:maxK         fk = minFreq * 2^((k-1)/bins);        N = ceil(Q*fs/fk);        cq(k) = x(1:N) * (hamming(N) .* exp( -2*pi*i*Q*(0:N-1)'/N)) / N;      end          end      This is the code I came up with, which not only looks horrible but is also horribly slow (several orders of magnitude slower than MATLAB):               slowCQT[x_, minFreq_, maxFreq_, bins_, fs_] :=         Module[{Q, maxK, maxN, k, fk, Ncq, cqt},             Q = 1/(2^(1/bins) - 1);             maxK = Ceiling[bins*Log2[maxFreq/minFreq]];             maxN = Ceiling[Q*fs/minFreq];             If[Length[x] < maxN,                  x = Join[x, ConstantArray[0, maxN - Length[x]]]];             cqt = ConstantArray[0, maxK];             For[k = 1, k < maxK, k++,                 fk = minFreq*2^((k - 1)/bins);                 Ncq = Ceiling[Q*fs/fk];                 cqt[[k]] =                  N[x[[1 ;; Ncq]].(N[HammingWindow[Range[-1/2, 1/2, 1/(Ncq - 1)]]] *                      N[Exp[-2*Pi*I*Q*Range[0, Ncq - 1]/Ncq]])/Ncq];];             cqt]      Any suggestions or pointers to improve it? EDIT: Example usage MATLAB               fs = 44100;     T = (0:2*fs)/fs;     x=sin(2*pi*440*T);     tic; cqt = slowQ(x,27.5,880,24,fs); toc          Elapsed time is 0.305124 seconds.      Mathematica               fs = 44100;     T = N[Range[0, 2*fs]/fs];     x = N[Sin[2 Pi 440 * T]];     tic = AbsoluteTime[];     cqt = slowCQT[x, 27.5, 880, 24, fs];     AbsoluteTime[] - tic          89.755638


RecurrenceTable not evaluated: mathematica just echoes input

Forgive the newbie question... I am trying to create a table of the following system, following the Stirling example in the documentation, but Mathematica just echoes my input. What am I doing wrong?               RecurrenceTable[        {s1[n, k] == s1[n, k - 1] + s1[n - 1, k - 1],          s1[0, k] == 1, s1[n, 0] == Boole[n == 0], s1[n, 1] == Boole[n <= 2]},         s1, {n, 0, 6}, {k, 0, 4}     ] // Grid


Converting from TableForm to Grid

I wonder if there is an easy way to convert from TableForm to Grid. I have an existing data format that uses the Table function that I’d like to prettify…. Let’s setup a nested table as follows:               params = {"A", "B", "C", "D"};  (*example, can be more *);     axes = {"x", "y", "z”}; (*fixed number*) ;     mean = {l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12}; (*example data, maybe more*);     stdev = {m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12};     stat = {n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12};     labels = {"params", "axes", "mean\[PlusMinus]stdev", "other stat"};      My data format is as follows:               expr = MapThread[{#1, {#2, #3}, #4} &, {Flatten@      Table[axes, {i, 1, Length@params}], mean, stdev, stat}];     mytable = MapThread[{#1, #2} & , {params, Partition[expr, 3]}];      Visualizing the table:               TableForm[mytable]       ![TableForm output](http://i.stack.imgur.com/13Qt0.png) I’ve been banging my head on how to format this table using Grid while maintaining the general structure of the table. Q1. **What is the best way to convert this from TableForm to a Grid.** Q2. **Is there a better data structure I could use that would allow me to use TableForm or Grid interchangeably?** Related Question: Grid - sizing and spacing problems with spanning cells


Single Legend for a Table of Plots

For this toy problem               Needs["PlotLegends`"]          GraphicsGrid[      Partition[       Table[ListPlot[         Table[{x, f[x]}, {f, {Sin, Cos}}, {x, 0, Pi, Pi/10.}],          PlotRange -> {{0, Pi}, {-1, 1}},          PlotLegend -> {"Sine", "Cosine",}, LegendPosition -> {1.1, -0.4},          PlotMarkers -> Automatic], {k, 1, 6, 1}], 3], Spacings -> 0,       ImageSize -> 700]      I was trying to make a single legend (precisely the legend you see here four times) for the entire `GraphicsGrid` rather than the same legend four times. How do I do so? * * * **Edit:** Same question but now with v9 code that doesn't require loading any package:               GraphicsGrid[      Partition[       Table[ListPlot[{Sqrt[Range[50]], Power[Range[50], (3)^-1]},          PlotLegends ->           PointLegend[Automatic, {"one", "two"}, LegendFunction -> "Frame",            LegendLabel -> "datasets"]], {k, 1, 6}], 3], ImageSize -> 800]      ![enter image description here](http://i.stack.imgur.com/Xh3Ww.png)


InterpolatingFunction with growing Domain

I want to find roots of a function that is very slow to calculate (the function itself involves a bunch of FindMaxima) so I interpolate the function in a region where I think it likely the the root is, since I have very little certainty where the root is I have to interpolate an absurdly large region. Is there a way to have InterpolatingFunction remember the original function and expand its domain when evaluation is attempted outside it?


Unencoding encoded URLs in a function

Is there a built-in function for decoding encoded URLs in _Mathematica_? I would like to convert an encoded URL, for example `https%3A%2F%2Fwww.google.co.uk%2Fimages%2Fsrpr%2Flogo4w.png` into `https://www.google.co.uk/images/srpr/logo4w.png` as attempting to directly access the encoded URL with `Import[]` fails.


Twirl Image Transformation

I am looking to reproduce the functionality of Photoshop's "Twirl" filter, which twists an image that originally looks like this (pulled from this page): ![enter image description here](http://i.stack.imgur.com/Di28d.png) Into this: ![enter image description here](http://i.stack.imgur.com/IBjxt.png) Ideally, I'd like it to approximate the way the Photoshop Twirl filter behaves as much as possible, or at least be flexible enough to be able to reproduce the way the filter works.


How to get state of checkbox?

Please explain how to get state of checkbox for its usage in further calculations. And I want to keep the selection from session to session without external savings. Thanks in advance


How to style and position VerticalCallouts and RadialCallouts

Here is a pie chart with a labels placed with a "VerticalCallout"               PieChart[Range[10],      PerformanceGoal -> "Speed",      ChartLabels ->        Placed[Range[10], "VerticalCallout", Style[#, Red, Bold, 14] &],      SectorOrigin -> {Automatic, 1}]      ![enter image description here](http://i.stack.imgur.com/3ycE2.png) I was trying to figure out what, if any, options control the colour and thickness of the "call out" lines and disk. So Q1. Are there built in options to change this styling? I was able to alter the styling via a rule replacement:               PieChart[Range[10],       PerformanceGoal -> "Speed",       ChartLabels ->         Placed[Range[10], "VerticalCallout", Style[#, Red, Bold, 14] &],       SectorOrigin -> {Automatic, 1}] /. {{x_Thickness, _GrayLevel,          y_Opacity, z__} :> {AbsoluteThickness[1], Red, y,          z}, {_GrayLevel, _Opacity, Disk[x_List, _]} :> {Red,          Disk[x, 0.05]}}      ![enter image description here](http://i.stack.imgur.com/BE2FE.png) But... Q2. Is there a way to specify the vertical positioning of the labels (for "VerticalCallout"? That is, to specify how far left and right from pie chart that they are positioned? By default they appear to align at the "image boundary" but if I set image padding or alter the plot range the label positions don't alter. **Edit** ok I have figured out Q2 via rule replacements as well but would still like to know if this can be controlled via built in options.               PieChart[Range[10],        PerformanceGoal -> "Speed",        PlotRangePadding -> 0,        ImagePadding -> 0,        ImageSize -> 600,        PlotRange -> {{-4.5, 4.5}, {-4.5, 4.5}},        ChartLabels ->          Placed[Range[10], "VerticalCallout", Style[#, Red, Bold, 14] &],        SectorOrigin -> {Automatic, 1}] /. {Text[x_, {a_, b_}, z_] :>          Text[x, {a*1.8, b}, z], {x_Thickness, _GrayLevel, y_Opacity,           z__} :> {AbsoluteThickness[1], Red, y, z}, {_GrayLevel, _Opacity,           Disk[x_List, _]} :> {Red, Disk[x, 0.05]}} /.       Line[{{x_, y_}, {z_, y_}}] :> Line[{{x, y}, {z*1.8, y}}]      ![enter image description here](http://i.stack.imgur.com/SfE17.png)


Calculating morphometric properties

Is it possible to calculate segment length, segment diameter and branch angles for three dimensional geometry. Geometry contains vertex points and polygon surfaces as                 file = "http://i.stack.imgur.com/N6RYT.png";       Import[file, "Graphics3D"]      ![enter image description here](http://i.stack.imgur.com/N6RYT.png)                 data = Import[file, "VertexData"];       polysurface = Import[file, "PolygonData"];       Graphics3D[Point@data]


How can I obtain Wolfram Alpha's "alternative forms" of an expression inside Mathematica?

When I type in Wolfram Alpha, say,               cos(a+b)      or               cos(a+b)^2      or (OK this next one can easily be obtained in Mathematica, still, I have run into Bessel function expressions that cannot be simplified by Mathematica, but get a decent "alternative expression" through W|A)               D[A^mu BesselK[mu, A r], A]      I get several alternative forms of these, but I cannot seem to obtain them simply from **pure** Mathematica (i.e. no W|A integration stuff). Am I missing something or is Wolfram Alpha just smarter in these things? The alternative expressions have helped me quite a lot, so it would be nice to have them in my toolbox without having to access Alpha.


Implementing the Farey sequence efficiently

There is of course the silly implementation:               FareySequence[n_] := Union[Flatten[Table[j/i, {i, 1, n}, {j, 0, i}]]]      However, there are numerous properties and confinements of Farey sequences (that can be used, **potentially** , in an indirect manner). This calls for a very simple, and, very efficient recurring/functional implementation, exhibiting _Superiority_. But I'm new to _Mathematica_ and can't find the right combination of built-in functions, and pure functions.. Ideas?


Refresh dynamic variable when used with Get

I came across this issue with a more complicated program I was working on. Suppose we have a volatile variable `data`:               In[1]:= data = RandomReal[{0,1},{10}];      As this cell is evaluated,               In[2]:= Dynamic@data      refreshes as expected. However, if we want to save a certain instance of data and later load it in:               In[3]:= DumpSave["filepath.mx",data]      (change value of `data` to something else)               In[4]:= <<"filepath.mx"      the dynamic cell (`In[2]`) isn't updated (unless you evaluate it again). It can be forced to update on the loading of the .mx file by using a `Refresh[...,UpdateInterval->time]`, but it seems odd that re-evaluating `In[1]` instantly changes the dynamic cell while redefining `data` with the .mx file doesn't. Any explanation for this? And is using the `Refresh` method a good solution here?


How to convert the symbol $d$ in Integrate into $\mathrm{d}$?

I used               TeXForm[HoldForm[Integrate[x^2, {x, 1, 2}]]]      to convert the integral $$\int_1^2 x^2 \, dx$$ How to get $$\int_1^2 x^2 \, \mathrm{d}x ?$$


Excluding a Region in ParametricPlot3D

Suppose I have a torus and a closed path on said torus:               r = 1;     R = 2.5*r;     a = .8;     b = .4;      path = ParametricPlot3D[{{(R + r Cos[a Sin@w]) Cos[b Cos@w], (R + r Cos[a Sin@w]) Sin[b Cos@w], r Sin[a Sin@w]}}, {w, 0, 2 π},  PlotStyle -> {Black, Thickness[0.008]}];     patch = ParametricPlot3D[{{(R + r Cos@v) Cos@u, (R + r Cos@v) Sin@u, r Sin@v}}, {u, 0, 2 π}, {v, 0, 2 π}, Mesh -> False, PlotStyle -> Opacity[0.75]];     Show[patch, path, Boxed -> False, BoxRatios -> Automatic]      ![torus with path](http://i.stack.imgur.com/xOgU9.gif) What I want to know is: Is there some way of plotting my torus without the part that is cut out by the path? I'm sure there is an easy way to do this with something like "Eliminate" but it seems just outside of my skill.


RegionPlot (or FillingStyle) using hash lines?

> **Possible Duplicate:**   >  Filling a polygon with a pattern of insets I have a RegionPlot (and sometimes a regular Plot) where I'd like to shade two different parts of it two different ways. Since the final output will be printed in black and white, I'd really like to do this in an old fashioned way: with hash lines. I was mainly wondering if there is some built in way to do this without developing it from scratch.


How to show an exclusion limit

I would like to show an exclusion plot, by having a filling made of parallel tilted lines. Any ideas? Something along these lines ![enter image description here](http://i.stack.imgur.com/y82aW.gif)


Output of NonlinearModelFit differs from the correct result

I'm having a bad time dealing with the `NonlinearModelFit` in Mathematica 8, since the result given is a bit imprecise. An example is given on potential regression, as follows:               data = {{0.9, 1.1}, {2, 2}, {6, 4.1}, {6.9, 4.5}, {9.9, 5.5},              {10.7, 5.9}, {14, 6.7}, {15.9, 7.3}}          NonlinearModelFit[data, b*t^a, {a, b}, t]      The result I get is: `1.34232*t^0.615024`, however it should be `1.23...*t^0.6548`. What am I doing wrong? I experience the same thing when I try to do a exponential regression (like this: `NonlinearModelFit[data, b*a^t, {a, b}, t]`).


Error message LinkObject::linkd when calling TextRecognize

I am getting the message > LinkObject::linkd: "Unable to communicate with closed link > LinkObject["E:\Program Files\Wolfram > Research\Mathematica\9.0\SystemFiles\Converters\Binaries\Windows\Tesseract.exe", > 134, 7] This is what is did As Mathematica's version of Tesseract was not recognizing text correctly, I installed `tesseract-ocr-setup-3.02.02.exe` in another directory. But my efforts were in vain. Therefore, I uninstalled that setup and, then, when I tried the following code it gave me the error message quoted above. Maybe I messed up somewhere.               x = Import["http://i.stack.imgur.com/AqSqO.jpg"];     TextRecognize[x];      Please, can anyone help me to solve this problem. ![enter image description here](http://i.stack.imgur.com/AqSqO.jpg)


Extract the left channel from an mp3 file

I'm trying to control where a sound is going to be heard, in the left For example, when I import an mp3 file, and I want to hear it only from the left ear, what should I do? I've never worked with sounds before, so I didn't know where to start. The **Documentation Center** seems very undocumented on this topic.


Travelling salesman with start and end points for 30 points

I am doing a route optimisation for delivery vehicles and failing dismally. Please see problem statement below. My current solution uses FindShortestTour, but this does not have defined start and end points. Data is received from the calling application in the following format: {"Unique Identifier used by server", Original order, Task locked, Latitude, Longitude} The first point will always have the unique identifier "00000000-0000-0000-0000-000000000000" and represents the depot. This point will always have an order of 1 and always be locked. A number of tasks may be locked in their given order at the beginning of the list. The Task locked is a boolean represented by 1 - locked, 0 - unlocked. These locked tasks are not included in the optimisation as they are fixed in their given order at the beginning of the scheduled. The route is to be optimised finding the shortest path starting at the last locked point and ending back at the depot, traversing all other unlocked points. Depot is always locked and will be used if there are no other locked tasks. The output is to be in the following format: {"Unique Identifier used by server", Original order, Distance to Next Task in km} and is to be arranged in the optimal order. The order will always start with the depot the traverse locked Tasks in their given order. This will be followed by unlocked tasks optimised from the last locked to the depot. This list will not contain the final depot point as the distance returned is the distance to next task. i.e. The last ordered task distance will be the distance from itself to the depot. The calculation needs to be able to handle the optimisation of 30 points in under a minute as accurately as possible.               input = {{"00000000-0000-0000-0000-000000000000", 1.,          1., -26.17132739,          28.21375807}, {"817463b3-e330-4405-9008-e21821e6c121", 2.,          1., -26.2055333333333,          28.420565}, {"36418378-a9ef-49d7-be5a-3a54264a8479", 3.,          0., -25.99202013,          27.53309061}, {"49595197-11e5-463a-8f7b-6cd294c33f43", 4.,          0., -26.14895194,          27.92271447}, {"83fd029b-0313-4519-a785-ff7b9843c85c", 5.,          0., -26.169355,          28.2079083333333}, {"612bf08a-1679-4feb-8fee-d12deb49803a", 6.,          0., -25.6755766666667,          28.0820533333333}, {"382f1997-5efe-42c1-99f5-bcb8da30e1c8", 7.,          0., -26.8742866666667,          28.25047}, {"883d68f2-b50f-48ca-b065-febfc6ea9546", 8.,          0., -26.0938733333333,          28.1937966666667}, {"1bf089bf-acae-4a41-8c4b-e120cef8a148", 9.,          0., -25.9877716666667,          28.0691433333333}, {"6958e90b-d42a-4c13-b6ec-78bbdd301aba", 10.,          0., -25.7661166666667,          28.2811033333333}, {"2f2c5d25-c1de-449e-b779-dd95699d83ed", 11.,          0., -26.0474216666667,          28.0060766666667}, {"a11feb01-f067-49aa-b99d-50879229c423", 12.,          0., -25.7949916666667,          28.29928}, {"729b8bfb-029a-483a-814a-1575a6fe47bc", 13.,          0., -26.0258616666667,          28.0692033333333}, {"732771dd-55fd-4074-a097-2665686f67d8", 14.,          0., -26.772045,          28.49977}, {"0690914d-ba34-4086-b5ae-feda7ed6d22b", 15.,          0., -26.044905,          28.0346666666667}, {"5de23f0e-9a05-40af-8e1e-f887d5a06452", 16.,          0., -26.4070083333333,          28.138515}, {"3e95a2ac-9985-4753-a4cc-5372ca44ed12", 17.,          0., -25.64392423,          28.13148167}, {"d2e0bce2-8061-4b57-b983-aa409c1532fe", 18.,          0., -26.42138814,          28.1074221}, {"0259d54a-0782-4ac8-a5f6-42af6e3edbc3", 19.,          0., -25.78637, 28.28066}, {"f686b23a-de85-4004-ae70-8d2703336b5d",          20., 0., -26.043795,          28.1197816666667}, {"e8bca7d4-69ad-4477-8791-9daedbc563c9", 21.,          0., -26.2624883333333, 28.17859}};               outputReturned = {{"00000000-0000-0000-0000-000000000000", 1.,         21.020}, {"817463b3-e330-4405-9008-e21821e6c121", 2.,         26.772045}, {"732771dd-55fd-4074-a097-2665686f67d8", 14.,         63.26}, {"382f1997-5efe-42c1-99f5-bcb8da30e1c8", 7.,         27.24}, ..., {"83fd029b-0313-4519-a785-ff7b9843c85c", 5., 0.62}}      Current poor solution here: https://dl.dropbox.com/u/9666857/Schedule.m **Edit** The requirement boils down to a traveling salesman path problem. I have a fixed start and end point with a list of intermediate points which need to be visited exactly once in an optimal order. I have a working solution here


A math function similar to "LatticeReduce" for finding linear independent basis

We would like to ask a math function similar to "LatticeReduce" for finding linear independent basis. The input is a list of vectors $M=\\{v_1,v_2,v_3,\dots\\}$, with the following property: There is a subset $O=\\{w_1,w_2,w_3,\dots\\}\subset M$, such that $O$ is a basis, i.e. linearly independent and span $M$, $$ v_i=\sum_a c_{ia} w_a.$$ Moreover, the coefficients $c_{ia}$ are **non-negative integers**. An explicit example is the following: $$M=\left( \begin{array}{ccccc} 1 & 1 & 1 & 1 & 1 \\\ 1 & 1 & -1 & -1 & 1 \\\ 1 & 1 & -1 & 1 & -1 \\\ 1 & 1 & 1 & -1 & -1 \\\ 2 & -2 & 0 & 0 & 0 \\\ 2 & 2 & 2 & 0 & 0 \\\ 2 & 2 & 0 & 2 & 0 \\\ 2 & 2 & 0 & 0 & 2 \\\ 2 & 2 & -2 & 0 & 0 \\\ 2 & 2 & 0 & -2 & 0 \\\ 2 & 2 & 0 & 0 & -2 \end{array} \right),\quad O=\left( \begin{array}{ccccc} 1 & 1 & 1 & 1 & 1 \\\ 1 & 1 & -1 & -1 & 1 \\\ 1 & 1 & -1 & 1 & -1 \\\ 1 & 1 & 1 & -1 & -1 \\\ 2 & -2 & 0 & 0 & 0 \end{array} \right), $$ where $O$ is the first 5 rows of $M$ and $$M[[6]]=O[[1]]+O[[4]],\, M[[7]]=O[[1]]+O[[3]],\,\dots$$ In Mathematica form, the example is               m = {{1,  1,  1,  1,  1},          {1,  1, -1, -1,  1},          {1,  1, -1,  1, -1},          {1,  1,  1, -1, -1},          {2, -2,  0,  0,  0},          {2,  2,  2,  0,  0},          {2,  2,  0,  2,  0},          {2,  2,  0,  0,  2},          {2,  2, -2,  0,  0},          {2,  2,  0, -2,  0},          {2,  2,  0,  0, -2}};      May we know that how to write a function/program such that inputting such $M$, the program will output the desired $O$. _For this example the built-in function LatticeReduce works well. But we are not sure it always works._


How to set PageWidth when using PutAppend to append expressions to a file?

Do[       PutAppend[Table[i, {RandomInteger[100]}], "./file.m"],       {i, 100}     ]      I'd like each inner list to always appear on the same line, but not automatically wrapped at 68th character. How to achieve that? I wonder where and how the PageWidth option should be set for the InputStream used by the PutAppend.               #!/usr/bin/env bash          sed -e '         /.* $/ {             N             /\n .*$/ {                 s/\(.*\) \n \(.*\)/\1 \2/             }         }     ' $1      will fix the broken lines.


How to create a simple interface to get file path and execute some code on it?

I need to create a simple user interface to choose one file in the notebook directory, import it and execute some functions on the imported data. For the first version I created this code:               Button["get File Path",      fileData = Import@SystemDialogInput["FileOpen", NotebookDirectory[]];      ];      function[fileData]      Now I want it to be a little bit more error proof, so if you cancel your selection, you don't get an error, and the rest of your code is not executed.               Button["get File Path",     fileData=Quiet@Check[Import@SystemDialogInput["FileOpen",NotebookDirectory[]],$Canceled]         ]         If[fileData!=$Canceled,function[fileData]]      I don't feel that it is the best practice for this kind of situation. Some clue to make the code more intelligent? Maybe with `Module`, `DynamicModule`, `Return` or something else?


Opening a notebook from command line in an existing front end instance

I am using Linux, and I would like to be able to programmatically open notebooks in a running Mathematica instance from the command line. Currently, doing something like /opt/Wolfram/Mathematica/8.0/Executables/Mathematica foo.nb launches a new kernel/frontend instance. Is it possible to re-use a running frontend for opening notebooks (short of enforcing single-instance behavior, for which I believe there is a command line option)?


Interpolation with boundary conditions

I'm working on a sales projection, trying to create some flexibility in handle the forecast using locators. The toy code is something like this:               DynamicModule[{pts={{1,1},{2,1}}}         ,LocatorPane[             Dynamic[pts]            ,Dynamic@Plot[Piecewise[{{InterpolatingPolynomial[{{0,1},Sequence@@pts,{3,5}},x],x<3},{5,x>3}}],{x,0,5},PlotRange->{{0,5},{0,6}}]         ]     ]      ![plot](http://i.stack.imgur.com/IdyQl.png) Where I can change the locators position in order to change the curve. **The question is, assuming my plot functions as`f[x]`**   1. How to define `f'[3]=0` to don't get the slop break in `{3,5}`?   2. How to define `f'[0]>0` to don't get a initial down slope? So I could control the polinomial order to get these conditions met, still using locators. Maybe using `NDSolve` together with `LinearModelFit`? Or is there a simpler way? **Update** The first condition was solved by @kguler and @belisarius. Tks to both. Some clue for the second?


Mathematica usage (success stories) for financial back-ends

I've been working for about 5 years in Java, developing financial back-offices (web-services, business logic, report generation etc.). I think Mathematica is very suitable for such calculations and business logic development and am wondering if there are any success stories for its usage in such systems. I also think that it can be pretty to use Mathematica with JLink in my web- application to delegate calculations.   * **Does anyone have such an experience or know-how ?** **UPD 1:** Removed some questions (they have relation to Wolfram Workbench): What about unit-testing in Mathematica ? How to organize Mathematica code if it would be very large ?


How to calculate FDCT

I'm new to Mathemtica and I'm trying to calculate Discrete Cosine Transformation FDCT. I found the FourierDCT built-in function, but not DCT, so I need to implement it. I have tried couple of ideas but no luck yet. Any ideas that can get me started will be really appreciated. ![enter image description here](http://i.stack.imgur.com/oGSwG.png) Edit 1 **_*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ **** This is the result of FourierDCT on the same Matrix from the Wikipedia link above, and the values are different. I need Forward Discrete Cosine Trasnformation, not the FourierDCT: ![enter image description here](http://i.stack.imgur.com/pCkUu.png) From Wikipedia: "A DCT is **similar** to a Fourier transform in the sense that it produces a kind of spatial frequency spectrum." Edit 2 **_*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ **** This is the matrix I'm using as input in Mathemtica: b = {{52, 55, 61, 66, 70, 61, 64, 73}, {63, 59, 55, 90, 109, 85, 69, 72}, {62, 59, 68, 113, 144, 104, 66, 73}, {63, 58, 71, 122, 154, 106, 70, 69}, {67, 61, 68, 104, 126, 88, 68, 70}, {79, 65, 60, 70, 77, 68, 58, 75}, {85, 71, 64, 59, 55, 61, 65, 83}, {87, 79, 69, 68, 65, 76, 78, 94} }


Visualizing the output of a Voronoi diagram computation

I need to plot a graph (to be specific: Fortune Algorithm output) with given vertex coordinates and a few unconnected vertices. I am thinking of using Mathematica for that. `GraphPlot` does much of the task with `VertexCordinateRules` option but does not plot unconnected points.   1. So is there any way to do this?   And it would be even nicer if that graph comes with 2-D Axes. I was thinking to use `ListLinePlot` and `Point` commands but they give two different graphs as output.   2. Is there any option for combining output from two graphs? (The `Show` command didn't help.)


Unsupervised Machine Learning Algorithm for Autonomous Image Processing and Tracking

I am trying to prototype a Mathematica application that will enable Autonomous Intruder & Anomalous Event Detection, Tracking and Alarm to web users those who want to autonomously and asynchronously monitor their private spaces such as homes, offices as well as outdoor spaces such as backyards, roads and recreation facilities using inexpensive commercial Internet-connected IP-cams and webcams. I want to employ a proven and tested unsupervised algorithm that will help me accomplish my goal. Any idea which one would be the best? What are the Mathematica functions that will help me customize such an algorithm? I am using network license of Mathematica-8.


Colorize a 3D distribution of points according to density

Suppose we have some random 3D distribution of points. I'll use the spherical ball defined below as an example and a starting point for the discussion here :               Ball[num_]:=Table[     {         #1 Sqrt[1-#2^2]Cos[#3],         #1 Sqrt[1-#2^2]Sin[#3],         #1 #2     }          &[         Random[NormalDistribution[1, 0.5]],         Random[Real,{-1,1}],         Random[Real,{0,2Pi}]     ],{num}]          Graphics3D[{AbsolutePointSize[2],Point[Ball[10000]]},Boxed->True,BoxRatios->{1,1,1},ImageSize->800,SphericalRegion->True]      This code produces the ball shown here : ![A spherical distribution of points in 3D space](http://i.stack.imgur.com/ONB8Q.jpg) I would like to colorize the whole distribution with a color shade defined on the density of points, from **_color1_** (highest density of points) to **_color2_** (lowest density of points). Adding more colors to the shade is a desirable option ( ** _color1_** to **_color2_** to **_color3_** ... to **_colorN_** ). How can I do that ? What Mathematica code could do this ? Please, the suggestions should be compatible with **_Mathematica 7.0_**.


Changing variables algebraically

Suppose one has two functions, $y(x)$ and $z(x)$, and one seeks to obtain $y(z)$ by substituting $x(z)$ into $y(x)$. Can this be done in a single step? Or must $z(x)$ first be inverted independently? For the sake of illustration, suppose the functions consist of transcendental functions combined by the elementary operations of addition, subtraction, multiplication, division, and exponentiation. For instance, $y(x) = a\ln x + \displaystyle\frac{\exp(bx)}{c+x}$ $z(x) = \ln x \cdot \left(1 - \cos x \exp(a^2x) \right)^{r}$


Running some code every time a new notebook is opened

**Is it possible to automatically execute some code every time a new notebook is opened?** So for example I would like to print a message "New notebook" every time a new notebook is opened. This question was prompted by this answer about fixing indentation when moving to a new line. The "fix" requires that some code is applied to the notebook every time it is opened. But I think this question in interesting enough to stand on it own. I even have some working code, but it based on polling, so I would like to avoid that if possible. (also is it possible to get rid of the global variable `$OldNotebooks`?)               Clear[GetNewNotebooks, $OldNotebooks];         $OldNotebooks = Notebooks[];     GetNewNotebooks[] :=        Module[{new},         new = Complement[Notebooks[], $OldNotebooks]; $OldNotebooks =          Notebooks[]; new];     (*new=GetNewNotebooks[];*)          NBHistory = {}; Dynamic[NBHistory]          StartScheduledTask@       CreateScheduledTask[NBHistory = NBHistory~Join~GetNewNotebooks[]];      Now every time you open a new notebook, it will get added to the list of NBHistory and displayed.               (*When you had enough:) *)     RemoveScheduledTask[ScheduledTasks[]]


Symbolic integration in the complex plane

**Context** While answering this question, I defined (symbolic and numerical) path integrations as follows                ContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=             Integrate[Evaluate[(f /. par) D[g, t]], {t, a, b}]           NContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=             NIntegrate[Evaluate[D[g, t] (f /. par) /. t -> t1], {t1, a, b}]      I also defined a piecewise contour               Clear[pw];      pw[t_, a_: 1] = Piecewise[{{a Exp[I t], t < Pi}, {-a + 2 a (t - Pi)/Pi, t >= Pi}}]     ParametricPlot[pw[t] // {Re[#], Im[#]} &, {t, 0, 2 Pi}]      ![Mathematica graphics](http://i.stack.imgur.com/9JnzU.png) While checking these routines on wikipedia examples, I tried numerically                Table[NContourIntegrate[Exp[I i x]/(x^2 + 1), x -> pw[t, 2], {t, 0, 2 Pi}], {i, 2, 5}] // Chop          (* {0.425168,0.156411,0.0575403,0.0211679} *)      which corresponds accurately to (see example II for Cauchy distributions)               Table[Exp[-i] Pi, {i, 2, 5}] // N      On the other hand, the symbolic integration               ContourIntegrate[Exp[I x]/(x^2 + 1), x -> pw[t, 2], {t, 0, 2 Pi}] // FullSimplify      returns 0. **Question** What am I doing wrong? **Attempts** Example I and III work ;-)               ContourIntegrate[1/(x^2 + 1)^2, x -> pw[ t, 2], {t, 0, 2 Pi}] // FullSimplify     NContourIntegrate[1/(x^2 + 1)^2, x -> pw[ t, 2], {t, 0, 2 Pi}] // Chop          (* Pi/2  1.5708 *)      and               NContourIntegrate[1/I/x/(1 + 3 ((x + 1/x)/2)^2), x -> Exp[I t], {t, 0, 2 Pi}]//Chop     ContourIntegrate[1/I/x/(1 + 3 ((x + 1/x)/2)^2), x -> Exp[I t], {t, 0, 2 Pi}]          (* 3.14159  Pi *)


Defining a recursive sequence

I want to define a recursive sequence and then ask Mathematica to print a specific value: ![enter image description here](http://i.stack.imgur.com/2wC22.png) Am I doing something wrong?


How to find the period of an arbitrary mathematical function?

Is there a function to find the period of an arbitrary (possibly complex) function in _Mathematica_?


How to stop V10 asking to continue with updated styling each time I open a new notebook

Each time I open a new notebook, using File->New->Notebook, I get this message ![Mathematica graphics](http://i.stack.imgur.com/J0LeN.png) Then I check on the "Do this for all notebooks". But when I repeat this and want to create a new notebook, it asks again. Restarted M and still no change. Any idea what can cause this and how to resolve it? ![enter image description here](http://i.stack.imgur.com/hYfjF.gif) I am on window 7, 64 bit. Version 10.


How do I plot a function over a subset of the displayed interval?

I want to plot `f1[x]` over `0 < x < L/2` and `f2[x]` over `L/2 < x < L` (i.e. so that `f1[x]` isn't displayed over`L/2 < x < L`, etc.). How do I do this?


Some Problem with WhenEvent!

Anyone knows what's the problem with the following code and how can I fix it? I am not sure that I wrote the WhenEvent section correctly. By the way, I want to solve the equations and then plot y vs. y' when x goes to zero (it is obvious that it's an interval :) ). Thanks               tmax = 300;     {{sol1}, {ps}} = Reap[     NDSolve[      {x'[t] == -(x[t] + 2 x[t] y[t]),       y'[t] == -x[t] x[t] + y[t] (y[t] - 1),       x[0] == 0.1, y[0] == 0.1,       WhenEvent[Limit[x[t], x[t] -> 0], Sow[t]]},      {x, y},          {t, 0, tmax}]]


Way to find color at a point in a Graphics?

I need to figure out a way to find out the RGB color value at a certain coordinate in a Graphics object. The Graphics object I am dealing with is continually Dynamically updated, so it is made of moving objects. How can I find the color at a certain point in this moving graphics object. There is a function, for Image type, called ImageValue which will give color at the given point, but then I have to somehow convert the Graphics to a Image each time I want to check the color at a point, since the Graphics is changing. I have the following code to do that, but it takes much too long to do so, and causes a visible pause. I replace the Dynamic type of the Graphics with Image.               image = screen /. Dynamic -> Image      The above calculation takes too long, when I checked the timing of it. What I am asking for is a faster, easier way to make a Dynamic Graphic an Image so I can take color like that, or a way to take color at a certain point in Graphics. Please help, A frustrated student. Code except:               screen = Dynamic[Show[{backdrop, carsList}];     image = screen /. Dynamic -> Image;     points = ImageValue[image, {newX, newY}];         For[i = 1, i < Length[points], i++,                 If[points[[i]] == {0, 0, 2/3} || points[[i]] == {1, 0, 0},                     valid = False;                     Break[];                 ];             ];      points would usually hold more color data for points, I shortened code.


Interactive steam tables and phase diagrams in Mathematica

I teach an undergraduate course in Thermodynamics and I would love to use Mathematica to demonstrate the various engineering processes that involve the expansions and compressions of steam and common refrigerants such as R134a. I know that wolfram alpha does provide steam data but I'd rather have this from Mathematica. I also do know that in the Mathematica guide (`guide/ScientificAndTechnicalData`), some data is available but it is generally viscosities, molecular formulae etc. Is there any way I could get steam table data into/from Mathematica? Students generally use steam tables available in their textbooks and that is a fantastic starting point as I would never want to do away with that. However, using Mathematica would be a fantastic way of introducing my students to this wonderful tool that has helped me in my research. This would be very transformative to the way steam tables are particularly viewed as (with general disdain among sophomores and junior level students)!


How can I display a multigraph with different colored edges?

I'm new to Mathematica(version 9) and I'm trying to display a multigraph with different colored edges. Here's my code so far:               G = {{1 -> 2, 1},  {2 -> 3, 1},  {3 -> 4, 1}, {4 -> 5, 1},          {5 -> 6, 1},  {6 -> 7, 1},  {7 -> 8, 1}, {8 -> 9, 1},          {9 -> 1, 1},  {1 -> 2, 2},  {2 -> 3, 2}, {3 -> 4, 2},          {4 -> 5, 2},  {5 -> 6, 2},  {6 -> 7, 2}, {7 -> 8, 2},          {8 -> 1, 2},  {1 -> 2, 3},  {2 -> 3, 3}, {3 -> 4, 3},          {4 -> 5, 3},  {5 -> 6, 3},  {6 -> 7, 3}, {7 -> 1, 3},          {1 -> 2, 4},  {2 -> 3, 4},  {3 -> 4, 4}, {4 -> 5, 4},          {5 -> 6, 4},  {6 -> 1, 4},  {1 -> 2, 5}, {2 -> 3, 5},          {3 -> 4, 5}, {4 -> 5, 5},   {5 -> 1, 5}}          GraphPlot[G,                         EdgeRenderingFunction -> (Switch[#3, 1, {Black,  Line[#1]},                                              2, {Red,    Line[#1]},                                              3, {Blue,   Line[#1]},                                              4, {Green,  Line[#1]},                                              5, {Purple, Line[#1]}] &),         VertexLabeling -> True,         Method -> "CircularEmbedding",         MultiedgeStyle -> All]      ![example bug](http://i.stack.imgur.com/wOxkM.png) This draws a graph with only a few of its edges and gives many "Switch is not a graphics primitive or directive." errors. How can I get this code to draw all of the edges properly? Thanks, Corey


Using Memoization with a Mutable Object

In looking for a solution to this question, I ran across some old binary tree code by Daniel Lichtblau, reproduced below:               Clear[leftsubtree, rightsubtree, nodevalue, emptyTree, treeInsert]     leftsubtree[{left_, _, _}] := left     rightsubtree[{_, _, right_}] := right     nodevalue[{_, val_, _}] := val     emptyTree = {};          treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree}     treeInsert[tree_, elem_] /; SameQ[nodevalue[tree], elem] := tree     treeInsert[tree_, elem_] /; OrderedQ[{nodevalue[tree], elem}] :=      {leftsubtree[tree],        nodevalue[tree], treeInsert[rightsubtree[tree], elem]}     treeInsert[tree_, elem_] := {treeInsert[leftsubtree[tree], elem],        nodevalue[tree], rightsubtree[tree]}      When mapped onto a list, `treeInsert` gives you a sorted duplicate free list. For example,               tr = {};     Scan[(tr = treeInsert[tr, #]) &, RandomInteger[100, 5]];     Flatten@tr      (* {13, 28, 53, 59, 88} *)      On my machine, this takes ~2 s to process `RandomInteger[10, 10^5]`, but this increases to nearly 20 s with `RandomInteger[10, 10^6]`. There are likely other techniques to speed this up, but I am curious as to how memoization could be adapted to this problem. At issue, though, is that the `tree` changes with each insertion, and so it cannot be used directly for memoization because the definition depends directly on that form. How would one do this? **Edit** : as I discovered in my own testing, `Fold` works much better than `Scan` for creating a tree, as follows               tr = Fold[treeInsert, {}, RandomInteger[100, 5]];     Flatten@tr      (* {13, 28, 53, 59, 88} *)      **Update** : while my question, per se, was not answered directly, the answers themselves indicated that there were better ways to accomplish what I wanted. In the end, I chose the one I did for two reasons: speed and simplicity.


StringCases: return list of outputs for each of several patterns

According to the documentation,               StringCases[{s1, s2, ...}, p]      returns               {StringCases[s1, p], StringCases[s2, p], ...}      but, oddly enough,               StringCases["string", {p1, p2, ...}]      returns the results which match _any_ of the patterns $p_i$, which is essentially equivalent to               Union[{StringCases["string", p1], StringCases["string", p2], ...}]      Is there a way to modify `StringCases["string", {p1, p2, ...}]` to return just               {StringCases["string", p1], StringCases["string", p2], ...}      in an analogous manner to how `StringCases[{s1, s2, ...}, p]` does it? One alternate way to get the same output would be               Through[Table[StringCases[#, p[i]] &, {i, n}]["string"]]      but I was curious if there was another way.


With comma as decimal separator, how do you insert a period in the header/footer?

I have enabled comma as my decimal separator, which means that comma still acts normally and when pressing period it will be converted to a comma. In the header I would like to make a period, so I insert a period and it looks like a period, however when I view the print preview, the period is converted to a comma. How do I keep this from happening or is there a special period character that doesn't get converted to a comma? Alternatively how can I make the header plain text, as this behaviour doesn't occur in plain text mode? **Edit:** Answering @SjoerdC.deVries questions:   1. With header I mean the option you set with `File > Printing Settings > Headers and Footers...`   2. The setting to change the decimal separator was found in Mathematica under `Preferences > Appearance > Numbers > Formatting > Decimal point character`   3. The period is the normal period key, not one on the keypad, although I would think they act similar.


TreePlot EdgeLabeling Style

I am trying to control the style for edge labels in treeplot and have run into a problem. Consider these two graphs:               edges1 = {{1 -> 2,"Test"}, 2 -> 3}     edges2 = {{1 -> 2,"Test"}, 2 -> 3, 1 -> 4}      If I plot the first then the labeled edge displays correctly:               TreePlot[edges1, BaseStyle-> 20]      ![enter image description here](http://i.stack.imgur.com/pm4rf.png) But if I plot the second it slants the text:               TreePlot[edges2, BaseStyle-> 20]      ![enter image description here](http://i.stack.imgur.com/R6FF9.png) Anyone have any insight how to stop the second behavior? **Edit** Here is a more complicated example showing how it slants the text in both directions and in different amounts (Note that in actuality my edges have different labels)               edges = {{1 -> 2, "Test"}, {1 -> 3, "Test"}, {2 -> 14,      "Test"}, {3 -> 4, "Test"}, {4 -> 99, "Test"}, {3 -> 6,      "Test"}, {6 -> 7, "Test"}, {6 -> 8, "Test"}, {7 -> 9,      "Test"}, {8 -> 10, "Test"}, {8 -> 11, "Test"}, {10 -> 12,      "Test"}, {11 -> 13, "Test"}};     edges[[All, 2]] = Map[Panel@Style[#, 12] &, edges[[All, 2]]];     TreePlot[edges, Top, 1, AspectRatio -> 1/3]      ![enter image description here](http://i.stack.imgur.com/q9NMG.png) * _Edit 2 *_ Combining M.R.'s solution and LayerSizeFunction I can somewhat still control the aspect ratio, but Mr. Wizard's solution is much better M.R. + LayerSizeFunction:               DeleteCases[TreePlot[edges, Top, 1, LayerSizeFunction -> (1/4 # &)], AspectRatio -> _]      ![enter image description here](http://i.stack.imgur.com/1mzx7.png) Mr. Wizard:               edges3 = {{1 -> 2, "Test"}, {1 -> 3, "Test"}, {2 -> 14,      "Test"}, {3 -> 4, "Test"}, {4 -> 99, "Test"}, {3 -> 6,      "Test"}, {6 -> 7, "Test"}, {6 -> 8, "Test"}, {7 -> 9,      "Test"}, {8 -> 10, "Test"}, {8 -> 11, "Test"}, {10 -> 12,      "Test"}, {11 -> 13, "Test"}};     TreePlot[edges3, Top, 1, AspectRatio -> 1/3, EdgeRenderingFunction -> ({Line[#1],       If[#3 === None, {}, Text[Panel@Style[#3, 16], Mean@#1]]} &)]      ![enter image description here](http://i.stack.imgur.com/ImiTn.png)


Symbolic Constrained Optimization

I have a question regarding evaluating constrained optimization problems in symbolic terms. I would like to perform How can I implement the method of Lagrange multipliers to find constrained extrema? without specifying the objective function. As a simple example, suppose I have a constrained utility maximization problem: $\max\limits_{x,y} U(x,y)$ $s.t.\ p_xx+p_yy=I$ where $U_x,U_y>0$, the Hessian matrix of the second-order derivatives is negative definite, and $p_x$ and $p_y$ are unspecified coefficients. Using Lagrangian multipliers, the first-order conditions are: $U_x-\lambda$$p_x=0$   $U_y-\lambda$$p_y=0$   $I-p_xx-p_yy=0$ Of course, the model that I want to use is a little bit more complicated than this (otherwise it would be no problem doing it by hand). Thus, given an unspecified objective function $U(x,y)$ and budget constraint(s) with unspecified coefficients, I was wondering if it was possible in Mathematica to:   1) produce the first-order conditions, and   2) given the system of equations in (1), produce symbolic rather than numerical solutions, which are functions of $U_x$, $U_y$, $p_x$, $p_y$, etc. Again, this differs from How can I implement the method of Lagrange multipliers to find constrained extrema? because: that question specified that the objective function $f(x,y,z)=xy+yz$, the coefficients of the constraints are implicitly equal to 1, and thus, it produces numerical solutions for the constrained extrema.


How to make use of Associations?

I have been curious about it for long. Now that Mathematica 10 arrives, I think it's time to ask the question: How the new `Association` data structure would be used to improve Mathematica programming? There are a few related aspects of this question: (1) How fast is the key-search in `Association` (on the website it is said to be extremely fast)? Would it be O(N) or O(N log N) (note added: those estimate are stupid. See benchmarks below and more in answers)? Is it recommended to be used with a lot of keys? Also, how fast is the operation of inserting a key to an assoication? Would it be O(N) or O(N^2)? (2) Previously I use pattern matching to implement similar functionalities. For example, I do `f[a]=x; f[b]=y` to effectively realize `f = <| a->x, b->y |>`. What's the advantage of the latter over the former? (Seems keys can be more easily managed. But I don't have systematic understanding of the advantages.) (3) The new structure `Dataset` is built upon `Association`. Is it efficient enough in terms of both memory space and computational speed, that I can use `DataSet` to store and calculate big data (say, table with more than 10 thousand rows, like MCMC chains)? Previously I used pure array. (4) Examples where old code can be improved making use of `Association`? I have read through the guide about `Association`, which is basically a collection of related functions. It would be great if the usefulness of those functions could get explained. **Note added:** The replies are really great! Many thanks :) I also did some benchmarks as below. The testing association is the same one as Leonid Shifrin's: `Association[Thread[Range[n] -> Range[n] + 1]]`, where `n` is the x-axis of the plots. We observe (in one case. I am not sure about worst case):   * Creation, insertion (middle) and deletion (middle) are O(N)    * Insertion and removal at head or tail are O(logN)   * Lookup is O(1)   * Association takes O(N) memory space, with a larger constant factor than array Note that, in the first figure, deletion is fast only when using `Most` or `Rest`. `Delete[store, -1]` and `Delete[store, 1]` are as slow as Delete[store, otherNumber]. Also, in the second figure, Association and Dataset takes almost the same memory thus not very visible. ![enter image description here](http://i.stack.imgur.com/Klshh.png) ![enter image description here](http://i.stack.imgur.com/uE2w5.png)


Replacing and combining elements in a list

I am trying to increase the level of nesting in the following list while adding a 'tag' to each leaf:               testd = {{59.15, 13.2, 13.52, 0.7}, {77.21, 12.27, 0.12, 0.01},               {77.25, 12.35, 1.01, 0.02}, {78.22, 11.74, 1.26, 0.01},               {79.26, 11.37, 1.03, 0.02}};             tag = {a, b, c, d}      So, the end product would look like                (*    {{{a, 59.15},{b, 13.2},{c, 13.52},{d, 0.7}},             {{a, 77.21},{b, 12.27},{c, 0.12},{d, 0.01}},               << ... >>             {{a, 79.26},{b, 11.37},{c, 1.03},{d, 0.02}}}  *)      I can use               Replace[testd, x_ -> {x}, {2}]      to get               (* {{{59.15},{13.2},{13.52},{0.7}},{{77.21},{12.27},{0.12},{<0.01}},        {{77.25},{12.35},{1.01},{0.02}},{{78.22},{11.74},{1.26},{0.01}},        {{79.26},{11.37},{1.03},{0.02}}}  *)      I have tried               Replace[testd, x_ -> {#, x}, {2}] & /@ tag      > {{{{a, b, c, d}, 59.15}, {{a, b, c, d}, 13.2}, {{a, b, c, d}, 13.52}, {{a, > b, c, d}, 0.7}}, {{{a, b, c, d}, 77.21}, {{a, b, c, d}, 12.27}, {{a, b, c, > d}, 0.12}, {{a, b, c, d}, "<0.01"}}, {{{a, b, c, d}, 77.25}, {{a, b, c, d}, > 12.35}, {{a, b, c, d}, 1.01}, {{a, b, c, d}, 0.02}}, {{{a, b, c, d}, 78.22}, > {{a, b, c, d}, 11.74}, {{a, b, c, d}, 1.26}, {{a, b, c, d}, 0.01}}, {{{a, b, > c, d}, 79.26}, {{a, b, c, d}, 11.37}, {{a, b, c, d}, 1.03}, {{a, b, c, d}, > 0.02}}} which is not what i want... Can someone help me with the right syntax? or suggest a better way?


Developing domain specific languages and computational knowledge engines using Mathematica

In one of Leonid Shifrin's excellent summaries, he mentioned that MMA capabilities include developing Domain Specific Languages (DSL). I'd like to develop a Health care IT application that can   * interpret users' natural-language   * perform automatic markup to tag, link and journal clinical documentation and    * communicate orders and queries to web services such as terminology servers and computational knowledge engines (CKE). In Mathematica 8, the `=` operator enables communication with Wolfram|Alpha, indicating that the front end can be programmed to host this type of user interaction. I understand this is very vague and underspecified, but am curious where to start in investigating the capabilities of MMA in developing DSLs.


Implementing Remainder Tree

I want to implement Remainder Tree based on this. With the answers on SE I've come up with:               listProduct2[list_] := Times @@@ Partition[list, 2, 2]          T = NestList[listProduct2, Prime[Range[2^7]], 7]          n = 31415926535;          r = {n};     Do[r = Outer[Mod, r, T[[i]]], {i, 7, 1, -1}];      The final desired output is to calculate `n mod p` for all first 2^n primes using remainder tree but it's very slow rather than being fast. I don't know where I was wrong! **Updated** I have read somewhere that this method can be used for faster sieve implementation, around 10 times faster than any available sieve method!!.               Primo[n_] := Product[i, {i, Prime[Range[n]]}]          primeslist = Prime[Range[10^6]];          prod = Primo[10^6];          n = Primo[205000] + 1;          Timing[MemberQ[listMod[n, primeslist],0]]          {36.719, False}          Timing[GCD[n, prod] != 1]          {2.14, False}


How can I transform a matrix to a vector (vectorization)?

How can I transform a matrix to a vector in mathematica? $A=\bigg{(}\begin{matrix} a_1 &a_2\\\a_3&a_4 \end{matrix}\bigg{)} \longrightarrow |a>>=(\begin{matrix} a_1 &a_2&a_3&a_4 \end{matrix}) $                   Vec2 := Function[{x}, For[i = 1, i <= Length[x], i++;                                   For[j = 1, j <= Length[x], j++;                                        Vec2[[i + j*4]] = x[[i, j]]]]]


Restrict Mathematica command to what is inside parentheses

I have a bunch of expressions like this one: $\frac{e^{-\frac{7 J}{2 k T}} \left(2 e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}-e^{\frac{g H \mu _B}{k T}}-2 e^{\frac{2 g H \mu _B}{k T}}\right)+e^{\frac{5 J}{2 k T}} \left(3 e^{-\frac{3 g H \mu _B}{k T}}+2 e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}-e^{\frac{g H \mu _B}{k T}}-2 e^{\frac{2 g H \mu _B}{k T}}-3 e^{\frac{3 g H \mu _B}{k T}}\right)}{e^{-\frac{7 J}{2 k T}} \left(e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}+e^{\frac{g H \mu _B}{k T}}+e^{\frac{2 g H \mu _B}{k T}}+1\right)+e^{\frac{5 J}{2 k T}} \left(e^{-\frac{3 g H \mu _B}{k T}}+e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}+e^{\frac{g H \mu _B}{k T}}+e^{\frac{2 g H \mu _B}{k T}}+e^{\frac{3 g H \mu _B}{k T}}+1\right)}$ and I want to convert all the terms inside the parentheses, and not the terms outside, into hyperbolic trig functions, using **ExpToTrig** command, but I'm not sure how to do this. Any help would be really appreciated.


How to get the digits of the base 2 representation of an integer

I would like to convert a number into base 2 and then use `IntegerDigits[]` on it. When using `BaseForm[i,2]`, the notebook only displays the output in a wrapper, but does not actually convert the number into a base 2 sequence. This causes problems when I want to use `IntegerDigits[]` on the base 2 number to get a list of the binary digits, e.g. `{1,0,0,1,1}`. It simply displays `IntegerDigits[10011 2]`. How could I solve this? Thank you


"Indexing" a vector

I need to "index" a vector according to the first occurence of its distinct elements. I have written               index[list_] :=      Module[{x = list, p},       p = Flatten /@ Map[Position[x, #] &, DeleteDuplicates@x];       Table[x[[p[[i]]]] = i, {i, 1, Length@p}];       x]      which gives the expected result:               vec= {1, 4, 4, 8, 7, 7, 4};     index @ vec      > {1, 2, 2, 3, 4, 4, 2} **(1)** How could a more functional / efficient solution look like? **(2)** How could such a solution be extended to work with matrices? ad (2)               mat = {{1, 4}, {2, 7}, {7, 2}, {9, 4}};      should give > {{1, 2}, {3, 4}, {4, 3}, {5, 2}}


How to solve that kind of partial fraction decomposition equations?

I need to find all variables $A, B, C, D$ for given equation with independent variable $s$.   How can I solve that with _Mathematica_ ?   Example, not working: ![enter image description here](http://i.stack.imgur.com/X6VoW.png) * * * UPDATE: **One** ![enter image description here](http://i.stack.imgur.com/uWOy8.png) **Two** ![enter image description here](http://i.stack.imgur.com/mUV8y.png) **Three** ![enter image description here](http://i.stack.imgur.com/NZZFH.png) **Four** ![enter image description here](http://i.stack.imgur.com/dAxKV.png) Nothing of listed above gives the result I need. * * * UPDATE2: I need denominators below $A,B,C,D$ to be predefined (not what `Apart` offers). $A,B,C,D$ must be numbers (don't include variable).


Replace a value in a nested array

When I run the following,               red = {{{-4, 50}, {100, 136}}, {{-19, 1}, {35, 73}}, {{-24, 0}, {26, 63}}};      y = {{0.01497, 1}, {0.04304, 3}, {0.07111, 2}, {0.09918, 1}};      red=Interval@@@red;     If[#[[1]] <= 0.05, xii = #[[2]]; If[IntervalMemberQ[red[[xii]], 47], #[[1]] = 999.];] & /@ y;     y      Instead of the following result               y = {{999., 1}, {999., 3}, {0.07111, 2}, {0.09918, 1}}      I am getting an error:                Set::setps:{0.01497`,1} in the part assignment is not a symbol. >>      I know based on this that it is to do with passing name of the variable vs. value of the variable, but not sure how to fix it. I tried `Insert[#, 999., 1]` and `ReplaceList[#, 1 -> 999.]` without much success :(


Visualising Special Relativity

Mathematica newbie learning by doing (or not so far, in this case). **Problem** : Special Relativity - consider two inertial frames $A$ & $A'$ in relative motion. At a time $t0$ as measured in $S$, draw a sphere $S'$ of radius $b$ in the hyperplane of simultaneity of $A'$ (i.e. orthogonal to $t'$), i.e. a surface that is spherical seen in $A'$ and exists only for the "moment" $t'0$. $t'0$ is simultanous with $t0$ as seen from $A$. ( _I have the Lorentz transformation matrix ready; use`c=1` for simplicity_) **Objectives** : a) visualise $S$, the image of $S'$ as seen from $A$ as a function of time in $A$, ideally with some surface patterning (e.g. lat/long grid, colour gradients, etc.) on $S'$ that will be transformed along with $S'$ so that the appearance of the surface seen from $A$ is also meaningful (shows orientation, distortion, etc.) b) determine analytically $tmin$ and $tmax$, the times at which the $S$ appears and disappears according to $A$ (see Expectatons below) **Expectation** : I _think_ $S$ becomes an ellipsoid that grows and shrinks betweem $tmin$ and $tmax$: since simultaneous events in $A'$ are not simultaneous in $A$ they must be at different times and continuity of the sphere implies a continuous temporal interval. I am not sure which is harder: doing 4D geometry in one's head or trying to do it by programming [Mathematica] Polite request for explicit code, if possible: at this stage I don't think I can be relied on to read between the lines - and if you wouldn't mind explaining how it works then I would also learn two things at once. Thanks in advance PS: It is not difficult to plot a sphere (thanks to Kuba for an nice way of doing that), the problem is producing a description (functions?) that can be both plotted and transformed so as to preserve surface features and to get the analytical answer b) above. I have looked at many Mathematic demonstrations and code, and tried too many graphics functions to list here and explain why they didn't seem to work for me - it's a completely open question: how would _you_ do it? **Code for generating the Lorentz matrix.** NB you may notice special case handling for `v = 0` because _Mma_ objected to `0/0` (and for `v>=c` returning a `0 matrix` because I don't know how to throw an error)               LorentzF[v_] := Module[{l, i, j, dim, γ},        dim = Length[v] + 1;        If[NumericQ[Norm[v]] == True  && (Norm[v] == 0  || Norm[v] >= 1),         If[Norm[v] == 0,          l = Table[KroneckerDelta[i, j], {i, 1, dim}, {j, 1, dim}],          l = Table[0, {i, 1, dim}, {j, 1, dim}]],         If[dim < 2, l = {},          l = Table[0, {i, 1, dim}, {j, 1, dim}];          l[[1, 1]] = γ;          For[i = 2, i <= dim, i++,            l[[1, i]] = l[[i, 1]] = -γ v[[i - 1]]           ];          For[i = 2, i <= dim, i++,            For[j = 2, j <= dim, j++,             l[[i, j]] =              l[[j, i]] = (γ - 1) v[[i - 1]] v[[j - 1]]/ v.v +                KroneckerDelta[i, j]            ]           ];           ]         ];        γ = 1/Sqrt[1 - v.v];        l        ];      **Bona fides** Check that `-v` is the inverse               Simplify[LorentzF[{bx, by, bz}].LorentzF[-{bx, by, bz}]]  // MatrixForm      Pick out the spatial part [NB, this is physically wrong, but I'm showing willing] creating something that can be used by `GeometricTransformation`               LorentzFSpace[{vx_, vy_, vz_}] :=  LorentzF[{vx, vy, vz}][[2 ;; 4]][[All, 2 ;; 4]]      Plot a sphere using `RegionPLot`               RegionPlot3D[x^2 + y^2 + z^2 < 1, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]      Another attempt               Graphics3D[      GeometricTransformation[Sphere[], LorentzFSpace[{0.56, 0.56, 0.56}]], Axes -> True,       AxesLabel -> {x, y, z}, FaceGrids -> {{-1, 0, 0}, {0, 1, 0}, {0, 0, -1}} ]      But I can't "markup" `Sphere[]` or do a _proper_ hyperplane intersection because only the presentation is being changed (and it's still the wrong transform) Think about doing it by points and lines based upon a lat/long grid (which won't work for reasons given above) latdivs = # divisions of latitude to use, etc. NB, when I first entered the function below I used "=" instead of ":=" by mistake, which lead to a "Iterator does not have appropriate bounds" error on the inner iterator. I don't understand why that mistake had that effect.               sphereGrid4D[latdivs_, longdivs_, originpt_, radius_]  :=  Table[{originpt[[1]], originpt[[2]] + radius*sin[i 2 Pi/longdivs], originpt[[3]] + radius*cos[i 2 Pi/ longdivs], originpt[[4]] - radius*sin[j Pi /latdivs]}, {j, 0, longdivs}, {i, 0, latdivs}]      Kuba's contribution (on the question they suggested I delete, which I did)               frame = Chop@First@ParametricPlot3D[{Sin[u] Sin[v], Cos[u] Sin[v], Cos[v]}, {u, 0, 2 Pi}, {v, -Pi, Pi}, Axes -> None, PlotStyle -> None, PlotPoints -> 10];          Graphics3D[{frame, GeometricTransformation[frame, {{{2, 0, 0}, {0, 2, 0}, {0, 0, 2}}, {5, 5, 0}}]}]      (and I still don't understand the Chop@First@ part) **Last comment for tonight (Spanish time)** Actually, I may have solved the $tmin$, $tmax$ problem, but I'd like to _see_ the pictures to confirm! Idea: consider the sphere as define by the dot product of the vector p (I think I swapped my frames around, but it doesn't really matter) transform the vector back to the other frame and solve (my copy/paste may be screwed up and it's late, but I hope you get the idea)               v = {vx, vy, vz}; (* assign velocity components *)     sphere[p_] := Sum[p[[i]]^2, {i, 1, Length[p]}]; (* define a sphere by magnitude of p*)     p0 = {t0, 0, 0, 0};      s = Simplify[sphere[LorentzF[-v].p0]];     solns = Solve[s == b, t0]; Simplify[solns]      Getting: (sorry, don't know how to do this nicely)               {{t0 -> -(Sqrt[b]/Sqrt[-((1 + vx^2 + vy^2 + vz^2)/(-1 + vx^2 + vy^2 + vz^2))])}, {t0 -> Sqrt[b]/Sqrt[-((1 + vx^2 + vy^2 + vz^2)/(-1 + vx^2 + vy^2 + vz^2))]}}      which seemed OK (too) late last night, but now doesn't. Hence my confusions It would have been nice if I could have found a way to create a substitution `V^2=vx^2+vy^2+vz^2` but `V^2` can't be a symbol (?)


Converting Mathematica Greek letters from Notebook to Unicode Form in SE

Related : > How to "Copy as Unicode" from a Notebook?               Plot[\[Alpha], {\[Alpha], 0, 8}]          cellExpression          (*     Cell[BoxData[RowBox[{Plot,[,RowBox[{\[Alpha],,,RowBox[{{,RowBox[{\[Alpha],,,0,,,8}],}}]}],     ]}]],Input,CellChangeTimes->{3.58068*10^9,{3.58068*10^9,3.58068*10^9}}]     *)          CellExpression2InputText[cellExpression_] := First[FrontEndExecute[     FrontEnd`ExportPacket[cellExpression, "InputText"]]]          CellExpression2InputText[cellExpression]          (*     Plot[\[Alpha], {\[Alpha], 0, 8}]     *)          CellExpression2InputText[cellExpression] // CopyToClipboard          Paste[]          Plot[\[Alpha], {\[Alpha], 0, 8}]      when copy the result above to SE, the [Alpha] was not shown in Unicode Form. And I failed in my usage involved with `CellExpression2InputText` Mr.Wizard's method, this is good to copy directly from input cell.               SetAttributes[copyUnicode, HoldFirst]     copyUnicode[expr_, form_: InputForm] :=     Run["clip <", Export["$Clipboard.temp", ToString[Unevaluated @ expr, form],     "Text", CharacterEncoding -> "Unicode"]];      ### case 1               CellExpression2InputText[cellExpression] // copyUnicode          Paste[]      PasteResult（not good）               CellExpression2InputText[cellExpression]      ### case 2               ToExpression[CellExpression2InputText[cellExpression], InputForm, HoldForm] // copyUnicode          Paste[]      still not good ## question * * * So question is clear: How to convert `CellExpression` to string/clipboard with greek letters in Unicode Form when copy to SE without laborious work by hand.               \[Alpha] ==> to α


Find all roots in the interval of nonlinear equation

I am struggling on how to find all the roots of `1+1/2^x+1/3^x==0` which lie in a given of real and imaginary interval. `Solve` does not work, and `FindRoot` only returns one root. Is there a better way to get as many roots as possible? Thank you so much for your help.


How to generate a picture like this?

How to generate a picture like this? I'd like the surface of the manifold to randomly distort. ![](http://25.media.tumblr.com/tumblr_mdq7e6M88N1qc0s10o1_r1_500.gif)


Factor out invariant code from Plot

Given a simple Gaussian kernel               UnscaledKernel[a_, b_, sigma_] :=       Exp[-(((a - b)/sigma).((a - b)/sigma))/2]      and un-normalized smoothing function               Smooth[valCountLst_, val_, sigma_] :=        Sum[valCountLst[[i]][[2]]*         UnscaledKernel[{valCountLst[[i]][[1]]}, {val}, sigma], {i, 1,          Length[valCountLst]}];      and a normalization constant so that the integral on the defined domain is 1:               ScalingFactor[valCountLst_, sigma_, lower_, upper_] :=       Integrate[       Smooth[valCountLst, everyVal, sigma], {everyVal, lower, upper}]      From this unsmoothed data (that is, 1000 items at value 0 and 10 items at value 1):               testList = {{0, 1000}, {1, 10}};      **I'm plotting smoothed (un-normalized) data takes 0.024 seconds:**               Plot[N[Log[Smooth[testList, x, 0.2]]], {x, 0, 1.0}] // Timing      (output is `{0.024, THEFIGURE}`). **When plotting the smoothed, normalized data, it takes much longer, 13.09 seconds:**               Plot[N[Log[         Smooth[testList, x, 0.2]/ScalingFactor[testList, 0.2]]], {x, 0,         1.0}] // Timing      **This seems strange since the scaling factor takes only 0.044 seconds to compute.** My conclusion is that Mathematica is computing the scaling factor _for every point, even though it does not depend on the point value x_. **Is there a way to help Mathematica compute this expression once and factor it out (or memoize it)?** Thanks a lot.


Get DownValues that do not involve patterns?

Say I have a function with a few definitions that also implements memoization:               f[x_] := f[x] = x^2     f[x_, y_] := f[x, y] = x^2 + y^2      I then apply the function to some data:               f /@ {1, 2, 3}     f @@@ {{1, 2}, {3, 4}}      Now the function will have a bunch of `DownValues` both for the stored results and for the pattern based definitions. Is there some easy way to retrieve only all the stored result, leaving out the pattern based definitions?


Will Mathematica install and run on Raspberry Pi computer?

My club is considering buying a Raspberry Pi computer for tinkering. Can Mathematica be installed on and ran from it?


How can I change the style of every newly opened notebook?

I'd like to make _Mathematica_ open a new notebook using the Natural Color template (under the Creative category) by default. Is that possible? If so, how?


What is wrong about Abs[x]-a? Is it a bug?

![enter image description here](http://i.stack.imgur.com/LtKtT.png) Why is the `Out[74]` not `{1 - a, {x -> -1}}`?                Maximize[{Sqrt[x^2] - a, -1 <= x <= 1}, x]      > >     {1 - a, {x -> -1}} >


Best way to create symmetric matrices

From time to time I need to generate symmetric matrices with relatively expensive cost of element evaluation. Most frequently these are Gram matrices where elements are $L_2$ dot products. Here are two ways of efficient implementation which come to mind: memoization and direct procedural generation.               ClearAll[el, elmem];     el[i_, j_] := Integrate[ChebyshevT[i, x] ChebyshevT[j, x], {x, -1, 1}];     elmem[i_, j_] := elmem[j, i] = el[i, j];          n = 30;     ClearSystemCache[];     a1 = Table[el[i, j], {i, n}, {j, n}]; // Timing     ClearSystemCache[];     a2 = Table[elmem[i, j], {i, n}, {j, n}]; // Timing     ClearSystemCache[];     (a3 = ConstantArray[0, {n, n}];       Do[a3[[i, j]] = a3[[j, i]] = el[i, j], {i, n}, {j, i}];) // Timing     a1 == a2 == a3      * * *               {34.75, Null}          {18.235, Null}          {18.172, Null}          True      Here `a1` is a redundant version for comparison, `a2` is using memoization, `a3` is a procedural-style one which I don't really like but it beats the built-in function here. The results are quite good but I wonder **if there are more elegant ways of generating symmetric matrices?** * * * **SUMMARY (UPDATED)** Thanks to all participants for their contributions. Now it's time to benchmark. Here is the compilation of all proposed methods with minor modifications.               array[n_, f_] := Array[f, {n, n}];     arraymem[n_, f_] :=        Block[{mem}, mem[i_, j_] := mem[j, j] = f[i, j]; Array[mem, {n, n}]];     proc[n_, f_] := Block[{res},       res = ConstantArray[0, {n, n}];        Do[res[[i, j]] = res[[j, i]] = f[i, j], {i, n}, {j, i}];       res       ]          acl[size_, fn_] :=        Module[{rtmp}, rtmp = Table[fn[i, j], {i, 1, size}, {j, 1, i}];        MapThread[Join, {rtmp, Rest /@ Flatten[rtmp, {{2}, {1}}]}]];          RM1[n_, f_] :=        SparseArray[{{i_, j_} :> f[i, j] /; i >= j, {i_, j_} :> f[j, i]}, n];     RM2[n_, f_] :=        Table[{{i, j} -> #, {j, i} -> #} &@f[i, j], {i, n}, {j, i}] //          Flatten // SparseArray;          MrWizard1[n_, f_] :=        Join[#, Rest /@ #~Flatten~{2}, 2] &@Table[i~f~j, {i, n}, {j, i}];     MrWizard2[n_, f_] := Max@##~f~Min@## &~Array~{n, n};          MrWizard3[n_, f_] := Block[{f1, f2},       f1 = LowerTriangularize[#, -1] + Transpose@LowerTriangularize[#] &@          ConstantArray[Range@#, #] &;       f2 = {#, Reverse[(Length@# + 1) - #, {1, 2}]} &;       f @@ f2@f1@n       ]               whuber[n_Integer, f_] /; n >= 1 :=        Module[{data, m, indexes},         data = Flatten[Table[f[i, j], {i, n}, {j, i, n}], 1];        m = Binomial[n + 1, 2] + 1;        indexes =          Table[m + Abs[j - i] - Binomial[n + 2 - Min[i, j], 2], {i, n}, {j,            n}];        Part[data, #] & /@ indexes];          JM[n_Integer, f_, ori_Integer: 1] :=        Module[{tri = Table[f[i, j], {i, ori, n + ori - 1}, {j, ori, i}]},         Fold[ArrayFlatten[{{#1, Transpose[{Most[#2]}]}, {{Most[#2]},              Last[#2]}}] &, {First[tri]}, Rest[tri]]];          generators = {array, arraymem, proc, acl, RM1, RM2, MrWizard1,         MrWizard2, MrWizard3, whuber, JM};      The first three procedures are mine, all other are named after their authors. Let's start from cheap `f` and (relatively) large dimensions.               fun = Cos[#1 #2] &;     ns = Range[100, 500, 50]     data = Table[ClearSystemCache[]; Timing[gen[n, fun]] // First,        {n, ns}, {gen, generators}];      Here is a logarithmic diagram for this test:               << PlotLegends`          ListLogPlot[data // Transpose, PlotRange -> All, Joined -> True,       PlotMarkers -> {Automatic, Medium}, DataRange -> {Min@ns, Max@ns},       PlotLegend -> generators, LegendPosition -> {1, -0.5},       LegendSize -> {.5, 1}, ImageSize -> 600, Ticks -> {ns, Automatic},       Frame -> True, FrameLabel -> {"n", "time"}]      ![enter image description here](http://i.stack.imgur.com/n2W49.png) Now let's make `f` numeric:               fun = Cos[N@#1 #2] &;      The result is quite surprising: ![enter image description here](http://i.stack.imgur.com/rlhDC.png) As you may guess, the missed quantities are machine zeroes. The last experiment is old: it doesn't include fresh `MrWizard3` and RM's codes are with `//Normal`. It takes "expensive" `f` from above and tolerant `n`:               fun = Integrate[ChebyshevT[#1 , x] ChebyshevT[#2, x], {x, -1, 1}] &;     ns = Range[10, 30, 5]      The result is ![enter image description here](http://i.stack.imgur.com/UOJDZ.png) As we see, all methods which do not recompute the elements twice behave identically.


How to symbolically differentiate an infinite series without evaluating the series itself

I'm dealing with finite sums of infinite series. Each of the infinite series possesses a different starting index, i.e. each of the series begins at n = 0, n = 1, or n = 2. As a result, it's important to keep track of the indices for each of the series. In addition, Mathematica cannot evaluate the series, because it's too complicated and undesirable for what's to be accomplished. I've only written the series in this manner to allow for efficient symbolic manipulation. The problem is that Mathematica takes a long time "trying" to evaluate each of the series. I've tried Hold, HoldAll, Unevaluated, and HoldForm. HoldForm seems like the correct choice, but there's a problem. Although I don't want to evaluate the series themselves, I'd still like to be able to perform operations on the series, such as differentiation. So, does anyone know of a way to differentiate a series without evaluating the series itself? I'm new to Mathematica, so the answer might be simple. Thanks for your time.


How can I make a barchart?

I want to mimic the below image type using Mathematica's `BarChart3D` function. For this purpose I wrote the following code but it isn't working. ![enter image description here](http://i.stack.imgur.com/P1SIa.png)               BarChart3D[{1, 2, 3},        ImageSize->{550,250},LabelingFunction -> Above,         ChartLabels -> Placed[barChartLabels, Below], BarSpacing -> 1,         ChartStyle -> Green,         ChartElements -> (Graphics3D[{Purple, Glow[Purple], EdgeForm[Purple],                           Cuboid[]}, Boxed -> False]),         LabelStyle -> {Directive[Bold, 15], Directive[Bold, 15]}     ]


Write and Read to StreamPosition

One OutputStream and one InputStream are opened on the same file:               atmp = OpenAppend["tmp"];       Write[atmp, "a"];       Write[atmp, "b"];       Write[atmp, "cde"];       rtmp = OpenRead["tmp"];       Read[rtmp];       Write[atmp, "ABC"];       ReadList[rtmp]        > >     {"b", "cde"}   >   What happend to ABC?               Read[rtmp]       EndOfFile       FilePrint["tmp"]        > >     "a" >     "b" >     "cde" >     "ABC" >   * * * OK.   One after the other, close one, open the other.   But still skeptical.   Shouldn't I be able to set the StreamPosition now?               atmp = OpenAppend["tmp"];       Write[atmp, "a"];       Write[atmp, "bc"];       Write[atmp, "def"];       StreamPosition[atmp];       Close[atmp];       rtmp = OpenRead["tmp"];       Read[rtmp];       ReadList[rtmp];       StreamPosition[rtmp];       SetStreamPosition[rtmp, 1];       Read[rtmp];       FilePrint["tmp"];       Close[rtmp];       DeleteFile["tmp"];       Streams[];


Copy and pasted graphics are fuzzy

I have a function that creates a 2D line with filling to the axis. When I copy this graphic into word it is very fuzzy, so much so that the numbers and text are almost unreadable, not to mention the aesthetic problem. When I take away the filling, the graphic can be copy and pasted into word as normal. the code used is:               Show[       Plot[d[x], {x, 0, 5}, PlotRange -> {-0.003, 0.003}],        ListLinePlot[residualsdata, PlotStyle -> Black, Filling -> Axis,          FillingStyle -> Directive[Opacity[0.5], Green]]]      The graphic without the filling is gotten by:               Show[       Plot[d[x], {x, 0, 5}, PlotRange -> {-0.003, 0.003}],        ListLinePlot[residualsdata, PlotStyle -> Black]]      Does anybody know the cause of this problem and/or how to fix it?


Combining two pure functions

How to get from the following intermediate result to the final one with just one pure function?               data = {"2894;Hot Pink;53:09:44;1449714",         "17456;Dark Cyan;19:06:42;6929227", "5147;Lime;54:11:55;5247632"};         from = 2; to = 3; delim = ";"; nr = to - from + 1;            inter = StringSplit[#, delim][[from ;; to]] & /@ data       {{"Hot Pink", "53:09:44"}, {"Dark Cyan", "19:06:42"}, {"Lime", "54:11:55"}}            final = {{"Hot Pink;53:09:44"}, {"Dark Cyan;19:06:42"}, {"Lime;54:11:55"}}


Placing package in existing Utilities` context has odd paraellelization effect

I noticed this in V.10 but possibly it was in effect in V.9. I have a package which in simplified form looks like:-               BeginPackage["Utilities`DataHandling`"];     f;     Begin["`Private`"];     f[data_List] := Module[{samples, selectFrom},         selectFrom[]:=($KernelID->data);          DistributeDefinitions[selectFrom];          samples = ParallelTable[$KernelID->Apply[Hold,{"CTUDH",$Context, Context[selectFrom], selectFrom[]}], {10}, Method -> "CoarsestGrained"];         samples         ];     End[];     EndPackage[];      The actual package is much bigger and performed a useful function, the payload in ParallelTable here is to illustrate the problem. When f is executed, the local symbol **selectFrom** is given a definition and distributed to all sub-kernels. Except that its not (when the package is loaded via Needs). So far as the sub- kernels are concerned the symbol **selectFrom** has no definition so the call **selectFrom** results in **Utilities`DataHandling`Private`selectFromXXX** [] - the _Hold_ prevents this from evaluating in the master kernel on return. Try f[{1,2,3}]. Changing the package name to MyUtilities`DataHandling` or indeed anything else resolves this and **selectFrom** is correctly defined in all the sub-kernels. This only took a day or so to work out *sigh*. What is special about the (admittedly Built-in) context Utilities? How does it mess up _DistributeDefintions_?


LinearSolve failing to find solution to system of linear equations of 64 variables

I've got a 64x64 Matrix `L` for which I want to find the solution to the matrix equation `L . x == rho`. L is defined as `L[a, b, c, d, e, f]` with assumptions `Element[{a, b, c, d, e, f}, Reals]`. As long as I put specific numbers in `L`, e.g. `L[1, 1, 1, 1, 1, 1]`, `LinearSolve[L, rho]` (with `rho` something like `rho = {1, 0, 0, ..., 0}`) finds the solution within a fraction of a second. But when making even one argument symbolic, say `L[a, 1, 1, 1, 1, 1]`, `LinearSolve` finds no solution (with `rho` as defined above): > LinearSolve::nosol: Linear equation encountered that has no solution. But there is a solution, at least all values of `a` I tried manually. And `a` is only added linearly in only some of the components of `L`. And even `Det[L]` is nonzero, so there should be a solution. I assume I'm doing something pretty wrong. Can anyone help me? Edit: Here is a sample matrix L[a,b,c,d,e,f] with fewer dimensions(5x5) where LinearSolve works(probably not the best sample because the big L matrix is more or less spare and this example doesn't look so):               L[a,b,c,d,e,f]={{1, 0, 0, 0, 0}, {0, (0. + 2. I) c, -((I dSin[f])/Sqrt[3]), -((I d Cos[f])/Sqrt[3]), 0},     {(I d Cos[f])/Sqrt[3], -((I d Sin[f])/Sqrt[3]), -11.565 - (0. + 1. I) a +(0. + 0.666667 I) c, 0, -(1/2) I e Sin[f]},     {-((I d Sin[f])/Sqrt[3]), -((I d Cos[f])/Sqrt[3]), 0, -11.565 - (0. + 1. I) a + (0. + 1.33333 I) c, 0},     {0, 0, -(1/2) I e Sin[f], 0, -0.2 - (0. + 1. I) a + (0. + 1. I) b - (0. + 0.2 I) c}}      i is no variable but the imaginary unit


Collecting roots of different equations and create a list

I solve two equations and have two solutions one by each equation. I want to create list of these roots. Could anyone please help me? Appreciate it. m02R150 = FindRoot[P1 == 0, {E1, 0.07, 0.1}] m01R150 = FindRoot[P1 == 0, {E1, 0.19, 0.2}] {E1 -> 0.0992422} {E1 -> 0.195237} What I want is to create a list: Lm0R150 = {0.0992422, 0.195237}


Split Lingustic(IPA) at Words Unique Sounds

How might I split a word at each IPA of each unique sound. For example               {"pray", "wade"}     (* {{"p","r","ˈeɪ"}, {"w","ˈeɪ","d"}} *)      ssch answered a question here showing how to add the IPA form to WordData. After adding such values I determined that ideally I am looking to separate the values in between each IPA sound(this probably isn't the correct terminology). An example would be the following `"pray"` and `{"p","r","ˈeɪ"}`. `"wade"` would return `{"w","ˈeɪ","d"}` Ideally a list of each unique IPA sound could be useful something like `{"b", "d", "dʒ", "f", "g", "h"....` So how might I get a list of Mathemametica's IPA sounds such that I can split a word's IPA form at each unique IPA sound?


How can I only draw outer common tangent to two circles?

I have code worked for drawing common tangent lines to two circles(http://en.wikipedia.org/wiki/Tangent_lines_to_circles), now I want to delete the inner common tangent lines, how?               Manipulate[Block[{t1, t2, v1, v2, pts},       t1 = {xm, ym};       t2 = {xn, yn};       {v1, v2} = p;       pts = {t1, t2} /. NSolve[{(t2 - v2).(t2 - t1) == 0, (t1 - v1).(t2 - t1) == 0,          (t1 - v1).(t1 - v1) == r1^2, (t2 - v2).(t2 - v2) == r2^2}, {xm, ym, xn, yn}, Reals];       If[pts == {t1, t2}, pts = {}];       Graphics[{Circle[p[[1]], r1], Circle[p[[2]], r2], Line[pts]},         PlotRange -> 6, Frame -> 1]       ], {{p, {{-3, 1}, {3, 0}}}, Locator}, {{r1, 1}, 1, 3}, {{r2, 2}, 1,        3}]      ![enter image description here](http://i.stack.imgur.com/e5Yov.png)


Interacting with 3D Graphics, for export

Are there any export formats which preserve the ability to interact with 3D Graphics? (In particular, the ability to rotate.) EDIT: I've found this question: How to make a 3D plot auto-rotate? which produces an object with head DynamicModule. Can I export as an animated gif or QuickTime movie?


Truncating out higher order polynomials in series of fractions

I have taken sequential partial derivatives of a two variable polynomial fraction, resulting in a very long series of polynomials of form:               C*x^i*y^j/(some product series of (1-x^k*y)^n)      What I wish to do is a series of basic truncations. First, I eliminate all polynomials that have `x^i*y^j` with `i` or `j > 4` in the numerator. I keep looking over the documentation and StackExchange and cannot find anything that works for me. I am open to suggestions. Edit: Thus far, I have merely sorted the long series, and picked out the valid fractions starting from the bottom. What is the solution that uses Mathematica functions?


Counting 'False' values at the ends of a list

I have table like this:               t = {False, False, False, 4.5, 6.789, 1.23, 0.98, False, False}      and I want to know how many False values I have at the beginning and at the end of the table. I made:               size = Length[t]     t = Cases[t,Except[False]];     size2 = Length[t]     diff = size - size2      But this counts number of all `'False'` values inside the table. But I want to know how many is at the beginning and how many at the end (so i my example I have: 3 at the beginning and 2 at the end). How can I solve that?


Unset while running recursion

I am trying to run a recursive definition while at the same time clearing previously found values, so my memory is not completely consumed. I found this: How to clear parts of a memoized function? But it does not seem to be what I am looking for. I want to clear memorized values, while the recursion is running. I thought I could do something like this:               Block[{$IterationLimit = $RecursionLimit = ∞},f [m_]:= f [m] = f [m-1]+f [m-2]          f[0]=0          f[1]=1          If [m - 3 > 0, Unset[f[m-3]]]      But it does not work. I realize I could just use `Fibonacci[n]`, but I am doing this to try to learn _Mathematica_ not to study the Fibonacci sequence. Thank you for any help!


Speeding up this fractal-generating code

I used the code below (which is a sample from this gist containing more similar code) in my answer to my own question about Mandelbrot-like sets for functions other than the simple quadratic on Math.SE to generate this image: ![graphic](http://i.stack.imgur.com/pL8nx.png)               cosineEscapeTime =       Compile[{{c, _Complex}},        Block[{z = c, n = 2, escapeRadius = 10 \[Pi], maxIterations = 100},         While[And[Abs[z] <= escapeRadius, n < maxIterations],          z = Cos[z] + c; n++]; n]]          Block[{center = {0.5527, 0.9435}, radius = 0.1},       DensityPlot[       cosineEscapeTime[x + I y], {x, center[[1]] - radius,         center[[1]] + radius}, {y, center[[2]] - radius,         center[[2]] + radius}, PlotPoints -> 250, AspectRatio -> 1,        ColorFunction -> "TemperatureMap"]]      What could I do to improve the speed/time-efficiency of this code? Is there any reasonable way to parallelize it? (I'm running Mathematica 8 on an 8-core machine.) * * * _**edit_** Thanks all for the help so far. I wanted to post an update with what I'm seeing based on the answers so far and see if I get any further refinements before I accept an answer. Without going to hand-written C code and/or OpenCL/CUDA stuff, the best so far seems to be to use `cosineEscapeTime` as defined above, but replace the `Block[...DensityPlot[]]` with:               Block[{center = {0.5527, 0.9435}, radius = 0.1, n = 500},      Graphics[       Raster[Rescale@         ParallelTable[          cosineEscapeTime[x + I y],           {y, center[[2]] - radius, center[[2]] + radius, 2 radius/(n - 1)},            {x, center[[1]] - radius, center[[1]] + radius, 2 radius/(n - 1)}],         ColorFunction -> "TemperatureMap"], ImageSize -> n]      ]      Probably in large part because it parallelizes over my 8 cores, this runs in a little under 1 second versus about 27 seconds for my original code (based on `AbsoluteTiming[]`).


How to visualize the voting choices in the moderator elections?

I'm trying to use Mathematica to create some visual representations of the votes cast in the recent Mathematica-StackExchange moderator elections. (Not the vote-counting system itself, OpenSTV, but rather the choices people made.) This is what I've got so far, but I'm stuck on how to represent the data visually, not knowing much about charting. According to this Meta post, the results can be downloaded in text form from this page. It looks to be a plain text file (with oddball Unicode characters):               data = Import[      "http://mathematica.stackexchange.com/election/download-result/1", "Table", CharacterEncoding -> "UTF8"]          (*     {{6, 3}, {1, 1, 2, 3, 0}, {1, 2, 4, 3, 0}, {1, 1, 4, 2, 0}, {1, 3, 1, 5, 0},      .... {"Verbeia"}, {"Mr.Wizard"}, {"F'x"}, {"Eiyrioü von Kauyf"}, {"Mathematica Moderator Election 2012"}}     *)      Although I couldn't find a guide to the format, it looks reasonable to assume that the initial {6,3} is the number of candidates and the number of vacancies, that the strings at the end before the election name are the candidates names, and that the lists starting with 1 and ending with 0 are the individual votes. So:               votes = Cases[data, {1, a_, b_, c_, 0} -> {a, b, c}]      gives the votes:               (*     {{1, 2, 3}, {2, 4, 3}, ... {1, 3, 5}}     *)      which I suppose can be turned into something more readable by picking up the names from the end of the list:               votes1 = votes /.       Table[        n -> First@data[[Rescale[n, {1, 6}, {-7, -2}]]],       {n, 1, 6}]      to give something like this:               (*     {{"R.M.", "J.M", "Verbeia"}, {"J.M", "Mr.Wizard", "Verbeia"},       {"R.M.", "Mr.Wizard", "J.M"}, {"Verbeia", "R.M.", "F'x"},       {"Mr.Wizard", "J.M", "Verbeia"}, {"J.M", "R.M.", "Mr.Wizard"} ...     *)      So now I'd like to make this data accessible visually, using charts or graphs. (Or, as the online help says, "produce compelling dynamic visualizations".) How could I do this?


How can we create Randolph diagrams in Mathematica?

I have become fascinated with Randolph Diagrams and was wondering how we would create the diagrams from logical sequences using _Mathematica_? It looks like it would be a combination of logic and graphing. I have no idea where to start. I need some suggestions to get me going. **Edit** Randolph's paper on JStor


Where to download the MathWorld package?

I was trying to run some notebook I downloaded from MathWorld, but lots of them need               << MathWorld`Curves`      I tried to google it , only to find this, but the link links to nothing but a blank page. so where do I find these packages?


Accurately distort graphics

I would like to accurately distort this plot of $\sin(x^{1/2})$ (and others like it) so that the wavelengths are evened out (ie - "inverse-square root" it). ![enter image description here](http://i.stack.imgur.com/d7oRl.gif) I should like to do the same to "de-log" plots too. I have no idea where to start though.


FullSimplify yielding different results in mathematica 8 and 9

I have been experiencing some problems running a certain mathematica file in version 9. I've tracked the problem to a particular sum that I perform. Running the same code in version 8 and 9 I get two different results for this sum. If I then ask mathematica whether the two sums are identical mathematica 8 says that they are whereas mathematica 9 says that they are not. So: I run the same code in version 8 and 9 and get a different result, if I compare the results version 8 says that they are the same, version 9 says that they are not. Why would this happen? A bug? Comparison attached below.               Chop@FullSimplify[       1.9999999999999996` x0^4 + 3.9999999999999987` x0^2 x1^2 +        2.` x1^4 + 0.3333333333333333` x1^2 x2^2 + (0.857142857142857` x0^2 -        0.699854212223765` x0 x1 + 0.14285714285714285` x1^2) x2^2 +        (0.5238095238095237` x0^2 + 0.11664236870396075` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.5238095238095236` x0^2 + 0.11664236870396079` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.5238095238095237` x0^2 + 0.11664236870396089` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.523809523809524` x0^2 +  0.11664236870396096` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.5238095238095236` x0^2 + 0.11664236870396066` x0 x1 + 0.5873015873015873` x1^2) x2^2 +        (0.5238095238095237` x0^2 + 0.11664236870396083` x0 x1 + 0.5873015873015874` x1^2) x2^2 +        1.9999999999999996` x2^4 ==        1.9999999999999996` x0^4 + 2.` x1^4 + 4.` x1^2 x2^2 + 1.9999999999999996` x2^4 +        6 x0^2 (0.5238095238095236` x1^2 + 0.5238095238095236` x2^2) +        x0^2 (0.857142857142857` x1^2 + 0.857142857142857` x2^2) +         x0 (1.166423687039609` x1^3 - 0.6998542122237649` x1 x2^2) +        2 x0 (-0.19440394783993475` x1^3 + 0.11664236870396069` x1 x2^2) +        x0 (-0.1944039478399347` x1^3 + 0.11664236870396072` x1 x2^2) +        x0 (-0.1944039478399347` x1^3 + 0.11664236870396077` x1 x2^2) +        2 x0 (-0.1944039478399347` x1^3 + 0.11664236870396083` x1 x2^2)]      Cheers, David


Replace an expression with a slightly tricky LHS transformation

I would like to make the substitution `x^(11*y) -> r` in the following equation               x^(11 *y^z) - 1       to end up with:               r^(y^(z - 1)) - 1      How can I do this in _Mathematica_?


Why is EigenValues returning Root expressions?

This is the code I have:               ϵs = -13.6;     ϵso = -29.1;     ϵp = -14.1;     ssσ = -7.20;     spσ = 9.46;          θ = ((π - β)/2);          Hmatrix0[θ_] =      {       {ϵs, 0, ssσ, Cos[θ]*spσ, -Sin[θ]*spσ, 0},        {0, ϵs, ssσ, -Cos[θ]*spσ, -Sin[θ]*spσ, 0},        {ssσ, ssσ, ϵso, 0, 0, 0},        {Cos[θ]*spσ, -Cos[θ]*spσ, 0, ϵp, 0, 0},        {-Sin[θ]*spσ, -Sin[θ]*spσ, 0, 0, ϵp, 0},        {0, 0, 0, 0, 0, ϵp}     }          Eigenvalues[Hmatrix0[θ]]      This is a sample of one of the eigenvalues: > Root[(38319.6 + 0. I) - 130827. Cos[β] - 116527. Cos[2 β] + (120228. - > 9278.49 Cos[β] - 4004.37 Cos[2 β]) #1 + (29612. + 9.09495*10^-13 Cos[β]) > #1^2 + 2480.29 #1^3 + 84.5 #1^4 + 1. #1^5 &, 1] I wish to plot the eigenvalues as a function of beta as it ranges from $\frac{\pi}{2}$ to $\pi$ but I don't know what those hashes are and putting `N[hmatrix0[`$\beta$`]]` doesn't work.


Function won't compile. Is there a workaround?

Here's a simplified form of a function I would like to compile, but it produces errors               DataType = Compile[{{Inputdata, _Real, 1}}, Module[{CIEL, CIEa, CIEb},         dim = Dimensions@Inputdata;         If[dim[[1]] > 3,          {CIEL, CIEa, CIEb} = Inputdata             ]         ],        CompilationTarget -> "C"        ];      The error _Mathematica_ produces is: > Compile::extscalar: `dim=Dimensions[Inputdata]` cannot be compiled and will > be evaluated externally. The result is assumed to be of type Void. >> Is there a workaround to allow these types of functions to compile for conditionals that depend on the dimensions of a list?