How to perform a multi-peak fitting?

I am wondering how to implement the multi-peak detecting and fitting in Mathematica. Following is an example of fitting the data using three peaks (such that the data ~ peak1 + peak2 + peak3). ![Illustration of a multi-peak fitting](http://i.stack.imgur.com/tZcHo.png) The peak model is given and fixed (all peaks are fitted by the same model), but its particular form (which will be input) can be Gaussian or Lorentzian or some other customized functions. The number of peaks is unknown and should be detected automatically, and the fitting model must also be built accordingly. Is there a Mathematica function that can simply do this? Or if anyone can give an idea of how to do the multi-peak fitting using Mathematica. (I am aware of fitting functions like `FindFit`,`NonlinearModelFit` etc., so my question is more about how to build the model and estimate the initial parameters for input of the fitting functions.) * * * I am expecting something like this:               PeakFit[data_, pfun_, x_]:=...      where the `data` is a list of points like `{{x1_,y1_}..}`, `x_` specifies the variable to be used, and the peak function `pfun` is a pure function whose first three parameters control the peak height, the peak width, and the central position, and the remaining (optional) parameters are for further control of the shape of the peak. For example a Gaussian model may be described as               pfun = Function[{x}, #1 Exp[-(x - #3)^2/(2 #2^2)]] &;      Given the data and the peak function, I wish `PeakFit` to return a `FittedModel` object containing the resulting model like `pfun[A_,w_,xc_][x]+...`.


How to plot a graph from it's incidence matrix?

I'm using Mathematica v9 and am trying to draw a graph by using it's incidence graph, but it won't draw it, which occurs an error "is not a valid incidence matrix.". But I've checked my matrix, and it's totally fine. I tried three matrices but error comes out every time. Here are my matrices in input forms. $6\times11$ incidence matrix:               ({{1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0},       {1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},       {1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1},       {0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0},       {0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0},       {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1}})         $9\times12$ incidence matrix:               ({{1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0},       {1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0},       {1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1},       {0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0},       {0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1},       {0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0},       {0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1},       {0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0},       {0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0}})      And here's a screenshot of my codes and their errors. ![enter image description here](http://i.stack.imgur.com/gKXzt.png) How do I fix this?


How to enlarge $\it{Mathematica}$'s knowledge about certain functions?

I'm often troubled with the following task. I need to carry out symbolical computations involving certain special functions. Let me take as an example Barnes gamma-function. It is included in _Mathematica_ 's standard tools under the name of `BarnesG[x]`. However, _Mathematica_ often does not deal with it efficiently. For instance, there is an identity stating `BarnesG[1+x]=Gamma[x]BarnesG[x]` where `Gamma[x]` is Euler gamma function. _Mathematica_ does not seem to "know" it. Execution of               Simplify[ BarnesG[1 + x] - Gamma[x] BarnesG[x]]       results in no real simplification. What is the most efficient way to "teach" _Mathematica_ such kind of identities? The only tool that I'm aware of is to create a corresponding transformation function and then use it in the process of simplification. In the case under discussion transformation function would be               tf[e_] := e /. {BarnesG[1 + x_] :> Gamma[x] BarnesG[x]};      Then evaluation of               Simplify[ BarnesG[1 + x] - Gamma[x] BarnesG[x], TransformationFunctions->{Automatic,tf}]      indeed gives zero. However, it does not help to work with numerical values. For example I still have no simplification for               Simplify[ BarnesG[7/6] - BarnesG[1/6] Gamma[1/6],                TransformationFunctions -> {Automatic, tf}]      So my questions are   1. What is the most convenient way of solving my problem?   2. If the one that I'm already using is OK, then how to extend it to numerical computations?    3. A little bit off topic: how can I bring _Mathematica_ to use new transformation function by default in opposite to explicit indication for this in every `Simplify` command? Any help is appreciated/ I'm sorry if I won't be quick enough with my replies.


Estimate parameters of the state space model

I'm using Mathematica 9 and its Control Systems functionality. I've searched the references extensively but seem not to be able to find any examples of state space model parameters estimation. All examples show models parametarized already or when they are given symbolic parameters they are not simulated. So my question is whether there're built-in functions that would estimate state space model paramters (including covariance matrices for stochastic inputs and measurements)? If there is none as of now may be you could give me some directions on implementing such procedures myself? **Example problem** Let me provide an example problem which I will borrow from (Zivot et. al, 2003): > Harvey (1985) and Clark (1987) provide an alternative to the BN > decomposition of an I(1) time series with drift into permanent and > transitory components based on unobserved components structural time series > models. For example, Clark's model for the natural logarithm of postwar real > GDP specifies the trend as a pure random walk, and the cycle as a stationary > AR(2) process: > > $y_t=\tau_t+c_t$ > > $\tau_t=\mu+\tau_{t-1}+v_t$ > > $c_t=\phi_1 c_{t-1}+\phi_2 c_{t-2}+w_t$ Now I want to try and estimate this example in Mathematica. First I get the data:               gdp = Differences[Log[CountryData["Russia", {"GDP", {1999, 2013}}][[All,2]]]]      Then I setup a state-space model as follows:               eq = {y[t] == c[t] + τ[t], c[t + 1] == α c[t] + β c[t - 1],      τ[t + 1] == μ + τ[t]}          StateSpaceModel[eq, {{y[t], 0}, {c[t], 0}, {τ[t], 0}},     {}, {y[t]}, t]      So what do I do next in order to estimate the parameters with data?   1. Zivot, E., Wang, J., Koopman, S.J. (2004) State Space Modeling in Macroeconomics and Finance Using SsfPack for S+FinMetrics


Is there a method to enumerate the keys/values of System`Utilities`HashTable

Lacking from the simple API of `System`Utilities`HashTable` is a method to enumerate the keys/values.               ?System`Utilities`Hash*          HashTable   HashTableAdd    HashTableContainsQ  HashTableGet    HashTableRemove      After creating a hash table               h = System`Utilities`HashTable[];     System`Utilities`HashTableAdd[h, "a", 1];      Various methods to extract its content fail.               h[[1]]     h     DownValues[h]      Any way out?


Solving an identity

I am trying to solve this identity using _Mathematica_ : $$3 \sqrt{5 \sqrt[3]{37}-16}=\sqrt[3]{a}-\sqrt[3]{b}-c $$ I know that `a`, `b` and `c` are positive integers. I want to find what `a`, `b` and `c` are. I tried               FindInstance[{a >= 1, b >= 1, c >= 1,      3*Sqrt[5*(37)^(1/3) - 16] == (a^(1/3) - b^(1/3) -  c)}, {a, b, c}, Integers]      That did not work. I tried a few more approaches using `FindInstance` but with no luck. Did I miss something or am I using the wrong function? The answer is `a = 1369`, `b = 296` and `c = 2`.


Transferring a large amount of data in parallel calculations

This question is inspired by one of @whuber's answers Consider the following code:               μ = RandomReal[{0, 1}, 100];     Σ = DiagonalMatrix[Exp[RandomReal[{0, 1}, 100]]];          AbsoluteTiming[      RandomVariate[MultinormalDistribution[μ, Σ], 400000];]      It runs in 3.5 seconds here. Now let's parallelize it:               LaunchKernels[]          AbsoluteTiming[      Join @@ ParallelTable[       RandomVariate[MultinormalDistribution[μ, Σ], 200000], {2}];]      This runs in 6.3 seconds on a 2-core machine---much _slower_. It also uses a lot of memory (which I checked using a process monitor). Now let's suppress returning the results from the subkernels by including a semicolon:               AbsoluteTiming[      Join @@ ParallelTable[       RandomVariate[MultinormalDistribution[μ, Σ], 200000];, {2}];]      This one runs in 2.6 seconds---a speedup. What is happening here? Why is the calculation that returns the result so much slower? Is it a general rule with parallel calculations that returning even moderately large data tends to lead to a significant slowdown? Is the slowdown due to MathLink's performance? Is there anything one could do to avoid the slowdown? **Warning:** This might eat all your memory and force your system to swap! This computer has 6 GB and everything was fine. If you have less memory, reduce the amount of data a bit. * * * ## Solution @Oleksandr's excellent analysis showed that the performance bottleneck is `MemberQ`, in particular that it unpacks all arrays inside the expression tested. This is completely unnecessary, and it's possible to define a more efficient (though more limited) version of `MemberQ`:               memberQ[list_, form_] := Or @@ (MatchQ[#, form] & /@ list)      Note that `MemberQ` only tests at level 1 by default (unlike `FreeQ` which tests at all levels). This made it easy to re-implement the two-argument form of `MemberQ`. We can temporarily change `MemberQ` while executing parallel operations:               ClearAll[fix]     SetAttributes[fix, HoldAll]     fix[expr_] := Block[{MemberQ = memberQ}, expr]          fix@AbsoluteTiming[       Join @@ ParallelTable[          RandomVariate[MultinormalDistribution[μ, Σ],            200000], {2}];]      This runs in 3.0 seconds now, a huge improvement. This is just an illustration of how to fix the performance problem, but the code I showed here is not completely safe to use in its current form. Some notes:   * Changing builtins is always risky, and can easily cause problems   * I used `Block` to localize the change, which reduces the risk. Note that `Block` will not affect calculations in the parallel kernels, so if `fix` is used _only_ on the parallelization functions, in the form `fix@ParallelTable[...]`, then it will only have an effect for these functions, but not for the code that is being parallelized. This reduces the risk further.   * I did not implement the 3-argument form of `MemberQ`. If this is used anywhere in the parallel tools, `fix` will break things. It'd take a bit more work to correctly implement this too, preferably just falling back to the builtin `MemberQ` for this case. There may always be some undocumented behaviour of `MemberQ` which we are not aware of and which differs from `memberQ`.   * I did not implement short circuiting, so `memberQ` will be slower in some cases. This can be fixed as well. These potential problems can largely be fixed with a bit of work, and I believe this method can work well for fixing this particular performance problem of parallel calculations.


Programmatically retrieving e-mails from a remote server

Mathematica has a function for sending mail (`SendMail`) and can import the `MBOX` format. But what I'd like to do is programmatically _retrieve_ mail from a Gmail account, from within _Mathematica_ on a Windows system. Is this possible? **Use case:** I use MarineTraffic.com's e-mail notifications about ship arrivals to watch interesting ships as they pass by. I'd like to filter incoming messages from them and use data from previous notifications to filter 'seen' ships. I may want to do some automated lookup on ship names too to find those that are more likely to be interesting. A perfect task for _Mathematica_ — if only I could periodically get the new mails and process them!


Compatibility of Mathematica Notebooks written on Mac with Windows

I wrote a notebook on Mac OS 10.7.4 and run it on Windows XP at work. On my Mac I use a full version of Mathematia 8.0.1.0, whereas on the Windows-system only a trial version (Version 8.0.4.0.). First of all I cannot run the following code on the Windows system (on Mac it works perfect):               ImportData={{"Test1", 5670.`, 0.`, 180.`, 2756.`, 2443.`, 180.`, 1008.`, 2007.`},                 {"Test2", 100.`, 0.`, 3006.`, 1235.`, 9874.`, 4543.`, 3241.`, 5004.`}};           WhitespaceCleaning[string_] :=           StringReplace[           string, (StartOfString ~~ Whitespace) | (Whitespace ~~                EndOfString) :> ""]          OriginalData =        Drop[ImportData, 1] /. {a_, b_, cc_, d_, e_, f_, g_, h_, i_} ->       {WhitespaceCleaning@a, {b, cc, d, e, f, g, h, i}};      However I can get the same result as on my Mac with the following code for my Windows system:               allData=ImportData;     numData=allData[[All,2;;]]     strings0=allData[[All,1]];     stringsWOSpacing=WhitespaceCleaning/@strings0;     OriginalData=Transpose[{stringsWOSpacing,numData}]      The rest of my code runs perfect (I get the same results on both operating systems). However, running my code on Windows provokes many messages (such as Divide::index, Divide::infy, Power::infy, General::stop, Less::nord, LessEqual::nord) which does not happen on my Mac. I don't understand why Mathematica on my Windows system is acting so odd. Does anyone has an idea?


RandomVariate with a Discrete Distribution

Nature has provided me with a random variable $Z$ taking on the values $0, 1, 2, \ldots$, with probabilities $z_0, z_1, \cdots$. I can sample from the distribution of $Z$ reasonably efficiently (I have done so $2^{28}$ times), and so I have estimates $\hat{z_0},\hat{z_1},\ldots$ of $z_0,z_1,\ldots$. I am interested in the number $f(z_0,z_1,\ldots,z_8)$, where $f$ is an explicit but involved function. Obviously, a good estimate is $f(\hat{z_0}, \hat{z_1}, \ldots,\hat{z_8})$, and a standard way to build a confidence interval is bootstrapping. To do this, I need to sample from the discrete distribution with probabilities $\hat{z_0}, \hat{z_1},\dots,\hat{z_8},q$, ($q$ chosen to make the probabilities add up to 1) and I need to sample $2^{28}$ times (I don't need the samples, just the number of times 1 comes up, 2 comes up, ...), and this process needs to be repeated, say, 1000 times. That's a lot of sampling, and it's going way too slowly. The first law of fast _Mathematica_ code is to use built-in functions. Is there a way to get `RandomVariate` to work with an arbitrary discrete distribution? Any other suggestions for rapidly sampling from an arbitrary distribution (again, I only need the `Tally` of the sampling, not the sample itself)?


How to make the Show function work in this case?

I can't get this to work, the Show function shows only the first plot. Why this happens and how to solve it?               Show[Plot[x^2, {x, 2, 10}], Plot[1 - x, {x, 1, -10}]]


Please explain this short code

l = {"BreuschPagan" -> BreuschPagan[data, lm, coords],         "WhitesHeteroskedasticity" -> WhitesHeteroskedasticity[lm, coords]};          f = {"BreuschPagan", "WhitesHeteroskedasticity"}          In[360]:= l /. Rule[f_, _] :> f          Out[360]= {"BreuschPagan", "WhitesHeteroskedasticity"}`      Have tried reading the support but i just dont get it. If I only apply `l /. Rule[f_, _]` the output becomes `_` And why does `l /. Rule[lof_, _] :> f` give the out               {{"BreuschPagan", "WhitesHeteroskedasticity"}, {"BreuschPagan",        "WhitesHeteroskedasticity"}}


Why won't my function plot?

If I define               g[z_] := Which[       0 <= z <= 0.9,     5*(Min[0.1, z] - Max[0, z - 1]),       0.9 <= z <= 1.1,   5*(Min[0.1, z] - Max[0, z - 1]) + 5*(Min[1, z] - Max[0.9, z - 1]),       1.1 <= z <= 2,                                       5*(Min[1, z] - Max[0.9, z - 1]),       True,              0       ]      and plot using               Plot[g[z], {z, 0, 2}]      I get ![enter image description here](http://i.stack.imgur.com/6Auvv.png) while if I plot using               ListPlot[{#, g[#]} & /@ (Range[1000]/500), PlotRange -> All, Joined -> True]      I get ![enter image description here](http://i.stack.imgur.com/EEG4F.png) which is what I expect. Why does `Plot` fail to plot my function as expected?


Extract data from DateListPlot, limited by PlotRange

Extracting the _points from a line_ in a ListPlot in this answer uses               points = Cases[Normal@plot, Line[pts_] :> pts, Infinity];      This works in DateListPlot (provided `Joined->True`) (example below, using `Last` to get the y-axis data only)               Clear[test,plot,points];     test={{"2010",1},{"2011",2},{"2012",3},{"2014",4},{"2015",5},{"2016",6}};     plot=DateListPlot[test,Joined->True]     points=Last/@Flatten[Cases[Normal@plot,Line[pts_]:>pts,Infinity],1]      ![enter image description here](http://i.stack.imgur.com/8c2Hx.gif)               (*OUTPUT     {1.,2.,3.,4.,5.,6.}      However, when the plot is limited by `PlotRange` using date values (lower plot), the function returns the entire list of points.               plot2=DateListPlot[test,Joined->True,PlotRange->{{"2012","2015"},{0,6}}]     points2=Last/@Flatten[Cases[Normal@plot2,Line[pts_]:>pts,Infinity],1]      ![enter image description here](http://i.stack.imgur.com/kXEYS.gif)               (*OUTPUT     {1.,2.,3.,4.,5.,6.}      Is there a function, like `points` which can return _only the points displayed on the plot_ in DateListPlot under 'PlotRange` ?


MathLink and a function of a real variable

I am trying to use a real function of a real variable written in C from Mathematica, my .tm file reads as follows:               :Begin:     :Function:       my_function     :Pattern:        MyFunction[ x_Real]     :Arguments:      { x }     :ArgumentTypes:  { Real }     :ReturnType:     Real     :End:          double my_function(double x) { /* snip */ return ret; }      I can compile with mcc, install the program from within Mathematica, and call my function as MyFunction[1.0], but it won't work if I call it with an integer argument, like MyFunction[1], as it is not automatically converted to a Real and then to a double. How can I make my function work well also with integer arguments? Also I have to apply some numerical Mathematica methods (like NMinimize, NIntegrate) and they fail when evaluating the function for integer values.


Numerically solving system of partial differential equation

I am trying to solve a system of partial differential equation with boundary conditions. But I got an error message saying `NDSolve::icfail:` Unable to find initial conditions that satisfy the residual function within specified tolerances. Try giving initial conditions for both values and derivatives of the functions. As I understand it, this is due to the absence of a system of equations of derivative with time of function G[t,x] and L[t,x] and solve this system can only be effected by The Numerical Method of Lines.                Remove["Global`*"];      pde = {       (-Derivative[1][Y21][t] - Derivative[1][Y31][t]) == -X20[t] -          X30[t] + Y21[t] - G1[t] (1 - Y21[t] - Y31[t]) + Y31[t],        Derivative[1][Y21][t] == 0.01` - Y21[t] - G1[t] Y21[t],       Derivative[1][Y31][t] == 9.9` + X30[t] - G1[t] Y31[t],       (-Derivative[1][X20][t] - Derivative[1][X30][t]) ==         0.2` + X20[t] - L0[t] (1 - X20[t] - X30[t]) + X30[t] - Y21[t] -          Y31[t],       Derivative[1][X20][t] == 0.79` - L0[t] X20[t] + Y21[t],        Derivative[1][X30][t] == 0.1` - X30[t] - L0[t] X30[t]}      with boundary condition:               BC = {       Y21[0] == 0, Y31[0] == 1,       X20[0] == 0.8, X30[0] == 0,         G1[0] == 10, L0[0] == 1        };          desired = {Y21, Y31, X20, X30, G1, L0};     NDSolve[{pde, BC}, desired, {t, 0, 1000}];      I tried to discretize the system in space using the finite-volume method. (http://reference.wolfram.com/mathematica/tutorial/NDSolvePDE.html). Maybe somebody knows the alternative method of solve that type of equations? It is a system of differential equations describing the process of countercurrent extraction. On top of the extraction column enters the two liquid components. The gas phase enters to the bottom of column. Liquid components have different solubility in the gas phase, due to which they are separated - coming out on top of the column the gas phase enriched by one component and the liquid phase exiting from the bottom - the other. This is the differential material balances for each component in the gas and liquid phases. The boundary conditions are taken from the known composition of the feed liquid phase on top of the column (z = 10) and the known composition of the gas coming from the bottom (z = 0) is also assumed that the initial time t = 0 corresponds to the equilibrium of the two streams at full lack of mixing. All constant parameters I removed for readability equations. Detailed description of the output of the system of equations described in the article: https://www.dropbox.com/s/v3oewg2w3etszbu/article.pdf. The authors solved a similar system using the method of lines in the software package gproms. The system was discretised in space using the finite-volume method. I'm trying to solve this problem in the software package Math, using "MethodOfLines" technique, but unfortunately so far without success. I would be very grateful for any help in this matter. I apologize for my English is not the native language for me.


What best practices or performance considerations are there for choosing between Cases, Position, Pick and Select?

`Cases`, `Select`,`Pick` and `Position` each have different syntaxes and purposes, but there are times when you can express the same calculation equivalently using either of them. So with this input:               test = RandomInteger[{-25, 25}, {20, 2}]          {{-15, 13}, {-8, 16}, {-8, -19}, {7, 6}, {-21, 9}, {-3, -25}, {21, -18}, {4, 4}, {2, -2}, {-24,  8}, {-17, -8}, {4, -18}, {22, -24}, {-4, -3}, {21, 0}, {19,    18}, {-23, -8}, {23, -25}, {14, -2}, {-1, -13}}      You can get the following equivalent results:               Cases[test, {_, _?Positive}]           {{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}          Select[test, #[[2]] > 0 &]           {{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}          Pick[test, Sign[test[[All, 2]] ], 1]           {{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}               test[[Flatten@Position[test[[All, 2]], _?Positive] ]]           {{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}      Are there performance or other considerations that should guide which you should use? For example, is the pattern-matching used in `Cases` likely to be slower than the functional tests used in `Select`? Are there any generic rules of thumb, or is testing the particular case you are using the only solution?


Can Mathematica find the discriminant formula?

This question is not really practical, but rather a curiosity question. Can _Mathematica_ solve a quadratic equation without its discriminant?   I mean, whenever it see a quadratic equation it tries to solve it with discriminant. (I use `Trace` for that)   But could it find it discriminant formula by itself?   I mean, the discriminant was found by human, and looking from how it was found, I see that was not very easy. I know that _Mathematica_ looks for patterns in equations. Can it found patterns, like discriminant?


Example from Mathematica documentation (ExtremeValueDistribution) seems to be evualting "forever"

I am referring to this example at the reference page for the extreme value distribution: http://reference.wolfram.com/mathematica/ref/ExtremeValueDistribution.html#6764486 The first three commands seem to be running ok, but the last line of code just will not stop evaluating on my machine (MathematicaMark9 result > 1.5) - somthing seems to be very wrong:               Show[DiscretePlot[Mean[max\[ScriptCapitalD]], {n, 2, 100}, PlotStyle -> Orange],       Plot[approxMean, {n, 2, 100}, PlotRange -> All, PlotStyle -> Directive[Thick, Dashed]]]      What am I doing wrong? Or is that a mistake in the documentation or an error in Mathematica 9.0.1? _Edit: I added the_ `bugs` _tag because it seems clear by now that this is really a bug in Version 9.0.1, see answer and comments below._


Speeding up a function

This is un updated version of a previous (now deleted) post of mine. I need to marginalize a distribution. I was suggested to use the code in this thread. This works just fine, but the problem is that the construction of tab (see below) is very slow: I tried with a pTab[i] with 100 elements and it took 2 days on my dual core 2GHz laptop to build it, and my actual pTab[i] are 180000 elements long. I guess you understand why I am worried. Does anyone have any idea about how to speed it up? Or a different code, maybe? Here is the code I am using (only the slow part):               dat = (*Import data from dat.txt*)     mat = (*Import matrix from matrix.txt*)     nosys = Inverse[mat];     z = dat[[All, 1]];     mu = dat[[All, 2]];     H = ConstantArray[1, 580];     chi[{a_, b_, c_,         e_}] = (5/           Log[10]*(Log[z] + 0.5*z*(3 - b) +              1/24*z^2*(21 + 9*b^2 - 2*b - 4*c)) -           mu).nosys.(5/           Log[10]*(Log[z] + 0.5*z*(3 - b) +              1/24*z^2*(21 + 9*b^2 - 2*b - 4*c)) -           mu) - (H.nosys.(5/              Log[10]*(Log[z] + 0.5*z*(3 - b) +                 1/24*z^2*(21 + 9*b^2 - 2*b - 4*c)) -              mu))^2/(H.nosys.H) + ((a - 0.742)/0.024)^2 + ((e - 0.315)/          0.017)^2;          ClearAll[pTab];          val = (*Import values needed for Ptab from ptab_values.txt*)          d = 4;(*number of parameters*)     Do[pTab[i] = val[[All, i + 1]], {i, d}];     tab = Module[{T, n},         With[{F = chi},          Replace[Hold[            Array[Append[T, F[T]] &, Length[pTab[#]] & /@ Range[d]]] /.            T -> Table[Hold[pTab[n][[Slot[n]]]] /. n -> i, {i, d}],           Hold[x_] :> x, {0, Infinity}, Heads -> True]]];     Print["packing array"]     tab // Developer`PackedArrayQ;      The needed files are: for ptab (these are the numbers needed for building pTab (skip the first column: that is needed for another work)) matrix (a 580 x 580 matrix) for dat (only the first 2 columns are needed in this code) Those are rapidshare links: I hope you allow it because the matrix is 580 X 580, and dat is 580 rows long: I can't write them in a post. **EDIT:** I was thinking can `Parallelize` be of any help in this case?


Opening a pipe with OpenRead

My question is if it is possible to directly open a (named) pipe using `OpenRead`. **Introduction** In the docs of OpenRead, we have, under details and options, > If OpenRead does not succeed in opening a particular file or pipe, it > generates a message, and returns $Failed. suggesting that we can open a pipe with `OpenRead`. However, we also have > On systems that support pipes, OpenRead["!command"] runs the external > program specified by command, and opens a pipe to get input from it. This last text adds to my suspicion that maybe it is only possible to open a stream indirectly. For example using something like `OpenRead["!cat fifo"]` (this may actually be a terrible command, but you maybe you get the gist. I.e. it seems that cat sometimes "terminates" and but mostly it doesn't, so that the kernel gets stuck waiting for the command to finish). However, this answer by rcollyer quite explicitly does what I have failed to do. It reads a fifo using `OpenRead`. **My attempt** If I do (sorry about wasting your time with Pause, it is probably not necessary)               dir = FileNameJoin[{$TemporaryDirectory, "MMAIO"}];     CreateDirectory[dir]     Run["cd" <> " " <> dir <> " && mkfifo fifo"]     Pause[1]     OpenRead[FileNameJoin[{dir, "fifo"}]]      Then I simply get `$Failed` and a message that it cannot be opened. Also when I connect some input to the fifo or when I just append some string to the fifo, it wont work. **Questions** Am I doing something wrong or is this just impossible? Might it depend on the system? I am using Mac OSX and version 9. Also, is there any other way to get input from a pipe directly, or do we have to resort to something like `OpenRead["!cat fifo"]`? **Etc** This Q&A is related, but it is about MathematicaScript. _Background_ : The reason I bother with a fifo in the first place is to make a connection between Mathematica and other applications without writing on the hard disk. I am aware that MathLink might be something to look into.


Horizontally compress a picture with varying compression ratio

I have a function `c[x]` whose domain and range are both [0,1]. And I have a picture with width `W`, height `H`. Now I want the picture to be compressed horizontally, with `c[x]` being the compression ratio for the part of the picture whose x-coordinate is `x.W`. To achieve this I have to discretize `c[x]`, which could be fussy and problematic. Besides since it's compression, it's hard to decide which row of pixels should be abandoned. So is there any good way to do this?


How can I make a plot of data saved in a .txt file?

My file. Txt has only two columns, where the 1st column is the time that the data was generated by the 2nd column has decimal values 1-100. Example:               19/06/2013 at 14:31:43 ------ 75 .19     19/06/2013 at 14:31:54 ------ 62 .46     19/06/2013 at 14:32:04 ------ 55 .62     19/06/2013 at 14:32:14 ------ 48 .28     19/06/2013 at 14:32:24 ------ 33 .15      I would like to plot this data on a graph that represents the axis yo time on the x axis while the decimal values ... these graphics could be in columns in which the maximum value is 100.


Nest for large value of n

I am working on a problem to find the Feigenbaum constant. In this problem I have to get $f^{2^n}(1/2)$ with $f(x) = kx(1-x)$. I use `Nest` to get $f^{2^n}(1/2)$ but it takes Mathematica forever to run with $n>5$ but my goal is to get to $n=14$. Does any body know any function or trick to get $f^{2^n}(1/2)$ with large value of $n$? Thank you very much.


Conjugate and simplify

I want to get a cosine from taking the real part of a complex exponential: $cos(x) = Re(exp(i x))$. What I do in _Mathematica_ is               (1/2)*(Exp[x*I] + Conjugate[Exp[x*I]]) // TraditionalForm // FullSimplify      but this gives me `1/2 (E^(-I x^\[Conjugate]) + E^(I x))` instead of `cos(x)`. Why is that?


How can one type a box with "x" marked?

In some text portion of my notebook, I would like to be write check boxes which are empty, check marked or "x" marked. The following commands work for the first two:               \[CheckmarkedBox]     \[EmptySquare]      But I am unable to find the command that would place an "x" inside the box. Thanks.


Search the neighborhood area along a line in an image

I am trying to search for the black areas along a line (the horizontal line shown below). Though it is straight in this picture, it could be of irregular shape in other cases. It seems that the ImageTake function can only take rectangle areas. Can anyone tell me how to limit the processing within the line neighborhood area, and mark the black area in the left part? ![enter image description here](http://i.stack.imgur.com/4s4ji.png) Update: Several raw images without red marks: ![enter image description here](http://i.stack.imgur.com/KjTp9.png) ![enter image description here](http://i.stack.imgur.com/AuHP7.png) ![enter image description here](http://i.stack.imgur.com/jFkNM.png) Update2: Other cases with bigger black area somewhere else ![enter image description here](http://i.stack.imgur.com/Yksk9.png)


Is this the correct method in using bootstrapping to determine a lower confidence bound?

Quite often in industry, due to cost and schedule constraints, decisions must be made on small sample size data. I have 4 cycles-to-failure values resulting from running samples to failure in a fatigue test; 947, 1183, 1063 and 583. It is not possible to obtain any more samples to test. From this data I believe I can say : I am 95% confident that the probability of any given part in the population surviving to 500 cycles is 0.82 or greater. My code is below. Is my approach the correct way to accomplish this using Mathematica ? Can someone verify these results using another tool ? Many Thanks.               cycles={947,1183,1063,583};     plot1=BarChart[cycles,Frame->True,ChartLabels->{"Sample 1","Sample 2","Sample 3","Sample 4"},LabelingFunction->Above,FrameLabel->{None, "Cycles to Failure",None,None},PlotRange->1750,PlotLabel->"Plot 1"]      ![enter image description here](http://i.stack.imgur.com/3rx0b.jpg)               dist = TruncatedDistribution[{0, Infinity},      SmoothKernelDistribution[cycles]]  (* Nominal Distribution *);     pdf[x_] := PDF[dist, x];     ps[x_] := SurvivalFunction[dist, x];     plot2 = Plot[pdf[x], {x, 0, 2000}, Frame -> True,      FrameLabel -> {"Cycles to Failure", "PDF", None, None},      PlotLabel -> "Plot 2\nNominal PDF", PlotStyle -> Red]     plot2a = Plot[ps[x], {x, 0, 2000}, Frame -> True,      FrameLabel -> {"Cycles to Failure", "PS", None, None},      PlotLabel -> "Plot 2a\nNominal Probability of Survival",      PlotStyle -> Red]      ![enter image description here](http://i.stack.imgur.com/TuN0T.jpg) ![enter image description here](http://i.stack.imgur.com/GqpUs.jpg)               n = 1000;  (* number of bootstrapped samples *)     bSamp = RandomChoice[     cycles, {n,      Length[cycles]}]  (* bootstrapped samples, each sample is 4 \     values long *);     sampleddistributions =      TruncatedDistribution[{0, Infinity},       SmoothKernelDistribution[#]] & /@ bSamp;       (* n fitted distributions *)     psvaluesTable =      Table[SurvivalFunction[i, rng = Range[0., 2000]], {i,      sampleddistributions}]  (* n PS lists, each PS list coresponds to \     cycles to failure values that range from 0 to 2,000 on a 1 cycle \     increment producing 2001 PS values in each list *);          psdata=Table[Null,{n}];     psplot=Table[Null,{n}];     cyclelist=Range[0.,2000];     i=0;     Do[{     i=i+1;     If[i>n,Break[]];     psdata[[i]]=Transpose[{cyclelist,psvaluesTable[[i]]}];     psplot[[i]]=ListPlot[psdata[[i]],Joined->True,PlotStyle->Green];},     {n}]     Dimensions[psplot]     psplot;     combinedPSlistplot=Show[psplot,FrameLabel->{"Cycles to Failure (cycles)","Probability    of Survival"},Frame->True,FrameLabel->{"Cycles to Failure","PS",None,None},PlotLabel->"Plot    3\nCombined PS ListPlot"]     plotindex=Range[1,n];     psplotdata=Transpose[{plotindex,psplot}];      ![enter image description here](http://i.stack.imgur.com/DNre4.jpg)               lower=Table[Quantile[i,.05],{i,Transpose[psvaluesTable]}]  (* Determines the lower 95%     single-sided confidence limit values *);lowerdata=Transpose[{rng,lower}];     plot4=ListLinePlot[lowerdata,PlotRange->All,PlotStyle->{{Dashed,Blue}},Frame- >True,PlotLabel->"Plot 4\nLower 95% Single-Sided Confidence Level"]     lowerinterp=Interpolation[lower];     Show[combinedPSlistplot,plot4,plot2a,PlotLabel->"Final Plot"]      ![enter image description here](http://i.stack.imgur.com/Pac9p.jpg) ![enter image description here](http://i.stack.imgur.com/LXBuc.jpg)               cyclesOfInterest = 500;     {lowerinterp[cyclesOfInterest], ps[cyclesOfInterest]}      {0.821289, 0.918629}


ContourPlot3D using a Matlab function through MATLink

I have a Matlab function which accepts a 3 dimensional vector and returns a single number. I want to use this through MATLink to make a 3d plot. A unit sphere:               ContourPlot3D[      Norm[{x, y, z}, 2]^2 == 1, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}]      I now want to replace the Norm with my function:               myfunc= MFunction["myfunc"];     ContourPlot3D[myfunc[{x, y, z}] == 1, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}]      but I get errors: > MSet::unsupp: Unsupported data type. The expression "x" can't be converted. > MFunction::args: The arguments at positions {1} to "myfunc" could not be > translated to MATLAB.... I am fairly certain I'm missing something obvious but I this is my first time with MATLink.


NetLink Exporting Images doesn't work (Unknown string escape)

Exporting Image files (intermittently) doesn't work: ![enter image description here](http://i.stack.imgur.com/C18mr.png) I get messages back indicating the error is to do with escaping characters:               Syntax::stresc: Unknown string escape \\U.


Split A text-style cell to multiple cells by a fixed width

> Sample Cell 1               Cell["Much of point set topology consists in developing a convenient language to talk about when various points in a space are near to one another and about the notion of continuity. The key is that the same definitions can be applied to many disparate branches of math.", "Text"]      Split to multiple cells like > Sample Cell 2               Cell["Much of point set topology consists in developing a convenient", "Text"]     Cell[" language to talk about when various points in a space are near", "Text"]     Cell[" to one another and about the notion of continuity. The key is", "Text"]     Cell[" that the same definitions can be applied to many disparate ", "Text"]     Cell["branches of math.", "Text"]      Though, in this example, they are all plaint text, maybe much simpler, the problem might be harder when there are many inline math cells. * * * Here is an sample post for why I need this, I wanna make first light-green block text into multiple framed lines like what below `Definition 4.1.1`. http://quaternions.blog.163.com/blog/static/206082147201356102512774/ * * * Bill's present method will not able to deal with the inline cells. > Upadte sample Cell 3 with inline cells               Cell[TextData[{"Much of point set topology", Cell[BoxData[\(TraditionalForm\`\(\ consists\ \)\)], FormatType -> "TraditionalForm"], "in developing a convenient language to  talk about ", Cell[BoxData[\(TraditionalForm\`when\)], FormatType -> "TraditionalForm"], " various points in a space are near to one another and about the notion of ", Cell[BoxData[\(TraditionalForm\`\(continuity\^2\)\)], FormatType -> "TraditionalForm"], ". The key is that the same definitions can be applied to many disparate branches of math."}], "Text"]


How to check if a given expression is an "explicit algebraic number"?

The documentation for `PossibleZeroQ` says: >   * With the setting `Method``->"ExactAlgebraics"`, `PossibleZeroQ` will use > exact guaranteed methods in the case of explicit algebraic numbers. > Unfortunately, there is no formal definition of what expressions are considered _explicit algebraic numbers_. I noticed that trig functions of rational multiples of `π` are not considered explicit algebraic numbers. Neither are `RootSum` expressions with algebraic functions as a second argument, nor `Re`, `Im` parts of `Root` expressions.               In[1]:= PossibleZeroQ[      Root[-7 + 56 #1^2 - 112 #1^4 + 64 #1^6 &, 4] - Sin[π/7], Method -> "ExactAlgebraics"]          PossibleZeroQ::ztest1: Unable to decide whether numeric quantity Root[-7 + 56 #1^2 - 112 #1^4 + 64 #1^6 &, 4,] - Sin[π/7] is equal to zero. Assumіng it is. >>          Out[1]= True          In[2]:= PossibleZeroQ[      Root[25 + 3300 #1^4 - 530 #1^8 + 20 #1^12 + #1^16 &, 16] -        RootSum[5 - 20 #1^2 + 16 #1^4 &, Sqrt], Method -> "ExactAlgebraics"]          PossibleZeroQ::ztest1: Unable to decide whether numeric quantity Root[25 + 3300 #1^4 - 530 #1^8 + 20 #1^12 + #1^16 &, 16] - RootSum[5 - 20 #1^2 + 16 #1^4 &, Sqrt[#1] &] is equal to zero. Assumіng it is. >>          Out[2]= True          In[3]:= PossibleZeroQ[Re[Root[5 + 20 #1^2 + 16 #1^4 &, 1]], Method -> "ExactAlgebraics"]          PossibleZeroQ::ztest1: Unable to decide whether numeric quantity Re[Root[5 + 20 #1^2 + 16 #1^4 &, 1]] is equal to zero. Assumіng it is. >>          Out[3]= True      Could you suggest a function that can determine if a given expression is considered an explicit algebraic number from `PossibleZeroQ`'s point of view?


How accurate is GeoDistance?

Two years ago I tried an evaluation copy of _Mathematica_. I reported various inaccuracies in the `GeoDistance` routine to which I never received any fix. Could someone check whether `GeoDistance` is any more accurate now? Thanks. Here are the problems I reported on June 20, 2011:                                                    Mathematica   Correct     Error     GeoDistance[{30, 0}, {-30, 180}]  -> 19928486.7   20003931.5  -75444     GeoDistance[{0.4, 0}, {0.4, 180}] -> 19915473.0   19915472.0       1     GeoDistance[{0, 0}, {0.5, 179.5}] -> 19936426.5   19936288.6     138


Find subexpression to minimize leafcount after replacment with temporary variable

Given an expression `expr`, is there an automated way to find a subexpression `subexpr` such that replacing `subexpr` with a temporary variable `v` minimizes `LeafCount[expr//.subexpr->v]+LeafCount[subexpr]` over all possible `subexpr`? To provide a concrete example to work with, here is a cleaned up small fragment of an expression that someone asked an unrelated question about recently:               (1/Sqrt[2](Sqrt[((Sqrt[((-x3 - (1/2 Cos[a] (m-h Cos[a]) + x3 Tan[a] - x3 (-m Sec[a]/(x2-x3) + Tan[a]) - Tan[b])/(-m Sec[a]/(x2-x3) + Tan[a]))^2 + (-1/2 Cos[a] (m-h Cos[a]) - x3 Tan[a] + Tan[b])^2)] + Sqrt[((-x3 - Cos[a] (m-h Cos[a])/(2 (Tan[a]-Tan[b])))^2 + (-1/2 Cos[a] (m-h Cos[a]) - x3 Tan[a] -     (Cos[a] (m-h Cos[a]) Tan[b])/(2 (Tan[a]-Tan[b])))^2)] + Sqrt[((-(Cos[a] (m-h Cos[a]))/(2 (Tan[a]-Tan[b])) + (1/2 Cos[a] (m-h Cos[a]) + x3 Tan[a] - x3 (-m Sec[a]/(x2-x3) + Tan[a]) - Tan[b])/(-m Sec[a]/(x2-x3) + Tan[a]))^2 + (-Tan[b] -     (Cos[a] (m-h Cos[a]) Tan[b])/(2 (Tan[a]-Tan[b])))^2)])(-Sqrt[((-x3 - (1/2 Cos[a] (m-h Cos[a]) + x3 Tan[a] - x3 (-m Sec[a]/(x2-x3) + Tan[a]) - Tan[b])/(-m Sec[a]/(x2-x3) + Tan[a]))^2 + (-1/2 Cos[a] (m-h Cos[a]) - x3 Tan[a] +     Tan[b])^2)] + 1/2 (Sqrt[((-x3 - (1/2 Cos[a] (m-h Cos[a]) + x3 Tan[a] - x3 (- m Sec[a]/(x2-x3) + Tan[a])-Tan[b])/(-m Sec[a]/(x2-x3) + Tan[a]))^2 + (-1/2 Cos[a] (m-h Cos[a]) -x3 Tan[a] + Tan[b])^2)] + Sqrt[((-x3 - (Cos[a] (m-h Cos[a]))/     (2 (Tan[a]-Tan[b])))^2 + (-1/2 Cos[a] (m-h Cos[a]) - x3 Tan[a] -(Cos[a] (m-h Cos[a]) Tan[b])/(2 (Tan[a]-Tan[b])))^2)] +Sqrt[((-(Cos[a] (m-h Cos[a]))/(2 (Tan[a]-Tan[b])) +(1/2 Cos[a] (m-h Cos[a]) + x3 Tan[a] - x3 (-m Sec[a]/(x2-x3) +     Tan[a])-Tan[b])/(-m Sec[a]/(x2-x3) + Tan[a]))^2 + (-Tan[b] -(Cos[a] (m-h Cos[a]) Tan[b])/(2 (Tan[a]-Tan[b])))^2)])))]))      The original problem had a LeafCount of almost 6000. Fumbling with manual substitutions I was finally able to make the structure clear and that happened to enable `Simplify` to reduce the total LeafCount to about 250 in a few seconds. Is there a simple method of automating this? It would be even better if it could recognize and handle `-subexpr` and `1/subexpr` as containing `subexpr`, but that may be too much to ask. Note: I'm trying to actually see the result, not just have Mathematica do subexpression sharing behind the scenes where I cannot see what happened.


Common subexpression from two expressions

I am working with some unpleasantly tedious polynomials, which need to be manipulated in various ways (integrate with respect to some variable, differentiate with respect to another). Since these will eventually be part of numeric routines, I'd like to pull out common subexpressions that I can reuse, e.g.               (G u^2 (6 p (2 h + p) - 8 (h + p) u + 3 u^2))/(12 h^2)     (G (3 h + 3 p - 2 u) u^2)/(3 h^2)      should at least note that both have a common factor of               (G u^2)/(3 h^2)      Is there a convenient way to instruct Mathematica to look for this sort of computational-expense-reduction in pairs of expressions? Ideally it would notice even in the case where it's not just a factor multiplied by both, e.g. if I added `+ 1` to the second equation, I'd still like it to find that common subexpression. * * * Just for clarification, this is what I do by hand:               e1 = (G u^2)/(12 h^2) * (6 p (2 h + p) - 8 (h + p) u + 3 u^2))     e2 = (G u^2)/( 3 h^2) * (3 h + 3 p - 2 u)          A = (G u^2)/(12 h^2)     e1 = A * (6 p (2 h + p) - 8 (h + p) u + 3 u^2))     e2 = A * (12 (h + p) - 6 u)          B = u^2     C = h + p     A = (G B)/(12 h^2)     e1 = A * (6 p (2 h + p) - 8 C u + 3 B)     e2 = A * (12 C - 6 u)      to go from 6 additions, 20 multiplications, 2 divisions, and 2 assignments, to 5 additions, 14 multiplications, 1 division, and 5 assignments (the extra three of which are temporary so can be in registers and cost essentially nothing).


Find repeated groups in a long algebraic expression

I have an algebraic output (a solution to a de) similar to, but far longer than: {y->(x+3)^2/sin(7*(x+3))+(x+3)^3/7} I'd like to get Mathematica to notice that the group x+3 appears repeatedly, define a new parameter par1=x+3, and rewrite the original output as: {par1=x+3, par1^2/sin(7*par1)+par1^3/7} The new expression would be far simpler and faster to evaluate than the original if par1 is, say 40 characters long, and appears say 6 times in the original expression. Ideas on how to accomplish this? Eric


How to reduce the number of operations needed to evaluate an expression?

For some numerical calculations in C++ I have, for example, this complicated expression to evaluate. Given as Mathematica input, in its original form it is               w - 4(w - y)((w - y)^2 y + 6(1 + y)((w - y)y + (1 + y)^2)) /     ((w - y)^2 ((w - y)y + 6y^2 + 8y(1 + y)) + (1 + y)^2 (36(w - y)y + 24(1 + y)^2))      The goal is to reduce the number of required floating point operations to evaluate it in C++. Using useful code from Counting multiplications (complexity function) we can see it requires the following operations and their respective counts: `{{Times, 22}, {Plus, 18}, {Power, 7}}`. The `FullSimplify`'ed expression is a bit shorter               w - 4(w - y)(6 + y(18 + 6w + w^2 + 4(3 + w)y + y^2)) /     (24 + y(w^3 + w^2 (8 + 11y) + (2 + y)(48 + y(30 + y)) + w(36 + y(56 + 11y))))      and requires the following operation counts: `{{Times, 16}, {Plus, 18}, {Power, 5}}`. One way to reduce the number of operations is to identify common components and evaluate them beforehand as temporaries. After staring at the expression for an hour I could find the following substitutions:               f0 = w - y;     f1 = 1 + y;     f00 = f0 f0;     f11 = f1 f1;     f0y = f0 y;      and the expression now reads               w - 4f0(6f1(f11 + f0y) + f00 y) / (f11(24f11 + 36f0y) + f00(6y y + 8f1 y + f0y))      The operation count is now: `{{Times, 19}, {Plus, 9}, {Power, 0}}`. Is there a way to express this process of finding sub-expressions more formally in Mathematica? And automatize it at least for such simple expressions involving only multiplication and addition?


How to correct this, `f[a_] := FindRoot[eq == 0, {x, 0.5}]`, where `eq` contains a parameter $a$, without using `eq[a]`?

I want to solve an equation with a parameter $a$, and define the result as a function of $a$. It is something like this:               f[a_] := FindRoot[x^2 + 2 x + a == 0, {x, 0.5}]     f[0.2]     (* -> {x -> -0.105573} *)      The equation I want to solve is a large expression, so I do not want to put it explicitly inside the `FindRoot`. But this does not work:               eq := x^2 + 2 x + a;     f[a_] := FindRoot[eq == 0, {x, 0.5}]     f[0.2]     (* -> FindRoot::nlnum: The function value {1.25 +a} is not a list of numbers with dimensions {1} at {x} = {0.5}. *)      I do not want to define the equation as `eq[a]`, because this equation is also used to do other things, for which it is better to just use `eq`. The following ways also do not work:               f[a_] := FindRoot[Evaluate[eq] == 0, {x, 0.5}]     f[a_] := Evaluate[FindRoot[eq == 0, {x, 0.5}]]      (However, if we want to solve the above equation analytically, `f[a_] := Evaluate[Solve[eq == 0, x]]` works, and `f[a_] := Solve[Evaluate[eq] == 0, x]` does not. How to explain this?)


Import iTunes xml data and convert it into a dataset or table

I have an xml file with song data from iTunes (https://dl.dropboxusercontent.com/u/1012958/iTunes%20Library.xml) and I'd like to import it to _Mathematica_ to do some statistics. I get an XMLObject like this:               XMLObject[       "Document"][{XMLObject["Declaration"]["Version" -> "1.0",         "Encoding" -> "UTF-8"],        XMLObject["Doctype"]["plist",         "Public" -> "-//Apple Computer//DTD PLIST 1.0//EN",         "System" -> "http://www.apple.com/DTDs/PropertyList-1.0.dtd"]},       XMLElement[       "plist", {"version" -> "1.0"}, {XMLElement[         "dict", {}, {...}], {}, "Valid" -> True]      How can I convert it to a _Mathematica_ 10 dataset or table?


How to add rows to a Grid in front end?

I created a grid `g1` with `Grid[]` and then a separate grid `g2`. `g1` and `g2` have same number of columns. How to put the rows of `g2` at the end of `g1` purely using front-end? I tried to highlight `g2`, Ctrl+C, and move my curser to various positions in `g1` and Ctrl+V. But it always resulted in something not desirable such as the entire `g2` being copied into a cell of `g1`. Any suggestions?


Having Dynamic evaluated when off screen

As the title says, I want a cell containing the dynamic solution of a DAE- System to be available over the whole document. I use a lot of different Plots and Sliders scattered over the document and it is pretty annoying that after the cell scrolled off screen, the dynamic stuff stops working altogether (as this is the nature of `Dynamic` as the documentation explains it). If I copy `Dynamic[Solution]` and insert it all over the place everything works perfectly fine but does of course look unprofessional. Therefore I tried `DynamicWrapper["This is a text", Dynamic[Solution]]` to hide `Dynamic[Solution]` inside titles and texts that are scattered around anyway. This does however not work as I imagined it must. If someone has an idea how to comfortably solve the issue I would be glad. Edit: The system is a scale that works by compensation method; some code: This is my variable called solution               solution =      Dynamic[sol2 =      Quiet[NDSolve[{d1'[t] == d2[t],      d2'[t] == k*d1[t] + b*d2[t] + (ki*l)/\[Theta][t]*d3[t] + (l*g)/\[Theta][t]*              (mersatz - mass[t, offset, Mass]),      d3'[t] == -((ki*l)/L)*d2[t] - R/L*d3[t] + (U[t] + Uoffset)/L,      U[t] == kP*U2[t] + kI*IntegralPart[t] + kD*U2'[t],      U2[t] == -ks*l* d1[t],     D[IntegralPart[t], {t, 1}] == U2[t],     d1[0] == 0, d2[0] == 0, d1'[0] == 0,      d2'[0] == (l*ki)/\[Theta][0]*Uoffset/R + (l*g)/\[Theta][0]*               (mersatz - mass[0, offset, Mass]),        d3'[0] == 0, d3[0] == Uoffset/R , U[0] == 0, U2[0] == 0,        IntegralPart[0] == 0}, {d1, d2 , d3, U, U2, IntegralPart}, {t,        0, duration}      ]]]      After that follows a big plot of the measured / calculated load on my scale               PlotWeight =      Manipulate[     Quiet[Plot[{measuredweight[t] /. sol2,       If[referencew == 1, mass[t, offset, Mass], ""]} , {t, 0,       duration}, PlotStyle -> {Automatic, Darker[Green]},      ImageSize -> {1200, 400}, AspectRatio -> Full,       ExclusionsStyle -> {Darker[Green], None},      AxesLabel -> {Style["time [s]", FontFamily -> font1],        Style["measured weight [kg]", FontFamily -> font1]},      PlotRange -> {{0, duration}, If[scale == 1, Full, {0, scale}]}]],     Style["      +", 12]     , {{scale, 1,      Rotate[Style["AxisScale", FontFamily -> font1, FontSize -> 12],       90 \[Degree] ]}, 0.01, 1, ControlType -> VerticalSlider},      Style["      -",      12], {{referencew, 0,      Style["activate weight reference", FontFamily -> font1,       FontSize -> 12]} , {0, 1}},      ControlPlacement -> {Left, Left, Left, Top}, Alignment -> Center ]      Other variables displayed in interactive Plots are current, voltage, angular velocity, angle, etc. All those are coming from the DAE that is fitted in solution (in the variable sol2 inside of solution). ![Mathematica graphics](http://i.stack.imgur.com/wcadK.png) A full picture in this Pdf.


Remap Ctrl+Space?

The `Ctrl`+`Space` keyboard shortcut is really important in _Mathematica_ for using `Placeholder[]` boxes in input templates. Unfortunately, `Ctrl`+`Space` occupies the significantly more important role of the system-wide Quicksilver shortcut that I'm not really willing to part with, not even while _Mathematica_ is running. Can I change this shortcut in _Mathematica_ to some other key sequence?


Place symbols from small to big

I am wondering how to compare the different values of `ω` I derived in this code, and place them in order as follows. (use `Print` or something?) I would like to have `ω` placed in order in the output, instead of the values of `ω`. > $$\omega_{11} < \omega_{22} < \omega_2 < \omega_1$$ I would like to have `ω` placed in order in the output, instead of the values of `ω`.               Remove["Global`*"]          x1[t_] = A1 E^(I ω t);     x2[t_] = A2 E^(I ω t);          eqn1 = m x1''[t] + 2 k x1[t] - k x2[t] == 0 /. t -> 0;     eqn2 = m x2''[t] - k x1[t] + k x2[t] == 0 /. t -> 0;          org = k/m SparseArray[{{1, 1}, {1, 2}, {2, 1}, {2, 2}} -> {2, -1, -1, 1}];          eigena = Sqrt[org // Eigenvalues];          "The charactersitic frequencies are: "     Column[Subscript[ω, #] & /@ Range@2 == eigena // Thread,       Spacings -> 2]     For[i = 1, i < 3, i++, Subscript[ω, i] = eigena[[i]]]          "When the upper mass m1 is fixed, x1[t]=0, for all t values"          eqn11 = x2''[t] == -k/m x2[t];          "Just by observation, the frequency is:"          Subscript[ω, 11] == Sqrt[k/m]     Subscript[ω, 11] = Sqrt[k/m];          "When the upper mass m2 is fixed, x2[t]=0, for all t values"          eqn22 = x1''[t] == -2 k/m x1[t];          "Just by observation, the frequency is:"          Subscript[ω, 22] == Sqrt[2 k/m]     Subscript[ω, 22] = Sqrt[2 k/m];               Sort[{Subscript[ω, 1], Subscript[ω, 2], Subscript[ω, 11], Subscript[ω, 22]}             ] /. k -> 1 /. m -> 1


Symbolic integral including Hermite polynomial does not evaluate

I am trying to evaluate the following integral:               Integrate[HermiteH[n, Sqrt[a]* x] * Exp[- (c/2)* (x^2 + y^2) + b* x * y - (a * x^2)/2], {x, - Infinity, Infinity}]      but Mathematica just returns the function, e.g. does not evaluate it. It does evaluate for specific values of n, but I need a general result. I have considered using FindSequenceFunction, but I believe that this only works for integer sequences (?) Is there some way I can get Mathematica to evaluate this integral, or is it impossible to do? Thanks in advance for any replies.


How to Derive Tuples Without Replacement

Given a couple of lists like `a={1,2,3,4,6}` and `b={2,3,4,6,9}` I can use the built-in Mathematica symbol `Tuples [{a,b}]` and get all the arrangements easilly enough. But I am struggling with how to eliminate the generation of replacement results, for example: `{2,2}` and `{4,2}` and `{4,4}` are not desired but all the totally unique results like `{1,2}` and `{1,3}` are desired. So essentially I want to find all the combinations of numbers that do not have any ordering repeats such as `{4,2}` where I already have `{2,4}` and no number repeats such as `{2,2}` and `{4,4}`. Any ideas would be appreaciated!


How do I write "such that" in mathematica?

I have a mathematical statement as follows : > Tri := {(t1,t2): t1,t2>=0,t1+t2<=1} How can I tell _Mathematica_ that I need to define vectors `(t1,t2)` 'such that' (`:`) they satisfy the above condition?


converting between forms - symbols/subscripts - matrix products

If I have a vector of the form (xp+y, x+yp) do you have a simple way of creating the following matrix and vector from it: `{{p, 1}, {1, p}} * {x, y}`, such that after multiplying the matrix with the vector, I get the original vector back. If I have the following variables defined as such:               v1 = (a1 + 1) *(b1 + 1) *(c1 + 1)*(d1 + 1) *(e1 + 1)  -1          a1 = (x11*f11 + x21*f21 )          b1 = (x11*f12 + x21*f22 )          c1 = (x11*f13 + x21*f23 )          d1 = (x11*f14 + x21*f24)          e1 = (x11*f15 + x21*f25)      is there a fast way to convert all the numbers appearing next to letters for example 11 next to x in to subscript? My goal is to create a vector consisting of several elements that look like V1.


How can I prevent ColorFunction from disabling antialiasing in graphics?

When I use `ColorFunction`, the appearance of my plots is ruined, changing from this ![Nice antialiased plot](http://i.stack.imgur.com/y4be4.png) which has the normal smooth lines and antialiased fonts, to this ![Ugly plot](http://i.stack.imgur.com/BUDZm.png) in which the line for the plot has become jagged and thin, and the fonts have lost their clear appearance, and the points have become jagged and have even shifted position a bit. The latter figure is useless to me. How do I prevent this behavior? Is there a setting somewhere that I missed? Setting the "Antialiasing Quality" to "Highest Quality" in Preferences, partly remedies the problem with the line, but points, fonts, and axes still shift, as if the scale of the figure has been changed: ![enter image description here](http://i.stack.imgur.com/sEstj.png) * * *               Manipulate[Show[       {If[showcf,          ParametricPlot[{u, Sin[u]}, {u, 0, 2 Pi},           ColorFunction -> (White &), PlotStyle -> {Thickness[.02]}], {}],        ParametricPlot[{u, Sin[u]}, {u, 0, 2 Pi}],        Graphics[{Black, PointSize[Large], Point[{Pi, 0.5}], White,           PointSize[Medium], Point[{Pi, 0.5}]}]}],      {{showcf, False, "Show ColorFunction"}, {True, False}}]


Can Mathematica do two evaluations at the same time?

When one evaluation is running, if I want do another evaluation, Mathematica will put the second one in the queue and run it after the first evaluation finish. However, the first evaluation may take very long time and the second one may just a easy calculation. It is possible that running the second evaluation without giving up or waiting the first evaluation? BTW, I am using Mathematica 9 in Windows 8(64 bit), but I am also happy to use Ubuntu. Any suggestions are welcome.


How to plot multiple curve in a same plot with Manipulate

The manipulate function in _Mathematica_ allows the users to adjust the values of the parameters in a graphical way. How do I plot multiple functions in a same graph and also I can use manipulate at the same time?               Manipulate[      Row[{        Plot[f1(x+n)], {x,           0.0001, 1}, PlotRange -> {-10, 10}],        Plot[f2(x+n)], {x,           0.0001, 1}, PlotRange -> {-10, 10}]}],        {n, 1, 10}]      with give two independent plots with single curve in each. How should I do multiple curve in a **same plot?**


Inserting points along a linear interval between adjacent coordinates in an array

Say I have a list of coordinates in an array               {{0, 0}, {0, 1}, {1, 1}}      I'd like to create a new array where, between each pair of nearest-neighbor coordinates in the previous array, I place $k$ points equispaced on a linear interval between the points. For example, with $k = 3$ we would generate the array: > >     {{0, 0}, {0, 0.25}, {0, 0.5}, {0, 0.75}, {0, 1}, >        {0.25, 1}, {0.5, 1}, {0.75, 1}, {1, 1}} >   Is there a nice one-liner for doing this?


Intersection of Osculating Circle with a Parametric Curve

I have the following Parametric plot ![enter image description here](http://i.stack.imgur.com/hKVs2.jpg) Generated from the following:               Manipulate[      ParametricPlot[{(A*Cos[t]^2 + B)*{Cos[t], Sin[t]},         C*{Cos[t] + 1, Sin[t]}}, {t, 0, 2*Pi},        PlotRange -> {{-5, 5}, {-5, 5}}], {A, 1, 10}, {B, 1, 10}, {C, 1,        10}]      I would like to find the exact values of $C$ and $t$ such that the inner circle, with one point fixed to the origin is tangent to the outer curve. This would mean, if I'm not mistaken, for $t\in\left[0,\pi/2\right]$, solving the following system of equations for $t$ and $C$               x1 = (A*Cos[t]^2 + B)*Cos[t]     y1 = (A*Cos[t]^2 + B)*Sin[t]     x2 = C*(Cos[t] + 1)     y2 = C*Sin[t]     x1 == x2     y1 == y2      i.e. find the intersection of the curves, but also they should have the same tangent, so we have:               D[y1,t]/D[x1,t] == D[y2,t]/D[x2,t]      But, for some reason I can't find a solution. What am I doing wrong?


Sporadic bug in Mathematica 7.01.0 MatrixPower and/or Eigensystem functions on floating-point symmetric matrices with repeated eigenvalues

**Note: From the comments submitted below by other StackExchange users it appears that this apparent bug was fixed sometime after version 7.0.1.** I asked a vague variant of this question a few days ago, but now I will give a concrete example. Floating point matrices with repeated eigenvalues often arise as the solutions to optimization problems. The _Mathematica_ functions `MatrixPower` and `Eigensystem` appear to have sporadic difficulty dealing with such matrices. (It is not clear to me whether this is because of numerical instability when trying to determine whether such matrices have nontrivial Jordan blocks, or if there is some other problem.) I have had to write my own routines for matrix power (and more generally for the functional calculus) to handle such cases, but maybe someone knows a quick fix. In the notebook http://tinyurl.com/lhodpdv I generated the following matrix by random search: (I'm using Mathematica 7.0.1 on 32-bit Windows)                {{0.461964, -0.314388, -0.138647, -2.23115*10^-6},       {-0.314388, 0.510134, -0.128432, -2.06676*10^-6},       {-0.138647, -0.128432, 0.744719, -9.11454*10^-7},      {-2.23115*10^-6, -2.06676*10^-6, -9.11454*10^-7, 0.801359}}      This matrix was defined by taking the average of a matrix and its transpose, so it is exactly self-adjoint. (I searched for it by finding rare matrices for which my usual code for inverting the `Eigensystem` function acting on a Hermitian matrix failed.) The list of eigenvalues               {0.801359, 0.801359, 0.801359, 0.1141}      has three repeated elements. All eigenvalues are positive, so _Mathematica_ should have no trouble computing the unique positive semidefinite square root of this matrix. However, using `MatrixPower[%, 1/2]`, _Mathematica_ reports that the square root is               {0.690223, -0.170008, -0.477225, 0.},     {-0.189862, 0.737704, -0.442063, 0.},     {-0.0837305, -0.0694507, 0.700234, 0.},     {-1.34742*10^-6, -1.11762*10^-6, -3.13724*10^-6, 0.895186}      This matrix **is not even symmetric**. Much worse, _Mathematica_ computes the matrix product               (square root).(square root)       as               {{0.548644, -0.209616, -0.588406, 0.},      {-0.234095, 0.607187, -0.545053, 0.},      {-0.103238, -0.0856309, 0.560987, 0.},      {-1.66133*10^-6, -1.37799*10^-6, -3.86814*10^-6, 0.801359}},      which is nowhere near the original matrix:               {{0.461964, -0.314388, -0.138647, -2.23115*10^-6},      {-0.314388, 0.510134, -0.128432, -2.06676*10^-6},      {-0.138647, -0.128432, 0.744719, -9.11454*10^-7},      {-2.23115*10^-6, -2.06676*10^-6, -9.11454*10^-7, 0.801359}}


Optimization for complex inequalities

I want to check when the expression $$ \sqrt{\sqrt{\lambda^{2}\left(2E+\lambda^{2}\right)}+E+\lambda^{2}} $$ is real, when it is purely imaginary and when it is complex (with imaginary part not zero). Also I would like to know the sign of the imaginary part in the case it is non-zero. To check the last part, after some steps, I am using `Reduce` for inequalities like $\mathrm{Im}\left(\sqrt{\lambda^{2}\left(2E+\lambda^{2}\right)}\right)>0 $ but this is taking a lot of time on _Mathematica_. Is there a way to get the kind of results that I want more quickly? The variables are real and the code I ran is                 Reduce[ Im[ Sqrt[ e + λ^2  -Sqrt[ λ^2 (2 e + λ^2)]]] > 0, {e, λ}]


NIntegrate extremely piecewised functions

I often need to integrate extremely piecewised functions, like the following one (not extreme, but gives an idea):               q[time_?NumericQ] :=       Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, d2 = 870.,         p2 = 5000, ph2 = 0},       If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] +         If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]]      ![enter image description here](http://i.stack.imgur.com/3iWtV.gif) I know that I can list all the mandatory points in the NIntegrate interval `List`. But most of the time I don't know them. Running `NIntegrate`generally returns singularity, accuracy, etc, type of errors.               NIntegrate[q[t], {t, 0, 7*24*3600}]      I can play around with `WorkingPrecision`, `MaximumRecursion`, etc, but it is not that easy to arrive to something that returns no errors, or that runs in a reasonable time. I generally end up running something like:               NIntegrateBis[funct_, list_] :=       Module[{step = 0.1, time = list[[1]], int = 0},        While[time < list[[2]], int = int + funct[time]*step;         time = time + step]; int]          NIntegrateBis[q, {0, 10000}]      Simple and with no messages... but no error control, no variable step, etc (it can even overpass the boundaries, although it is easy to correct that part...) What is the best strategy to integrate my functions? Use `NIntegrate` with a specific set of options (that I don't know of)? Built a personal `NIntegrate`? PS - I'm running optimization simulations with those functions, and so, I need it to run pretty fast.


Trigonometry expansion of a product

The following command does what I want:               TrigExpand[ Cos[a + b]^2]          (* 1/2 + 1/2 Cos[a]^2 Cos[b]^2 - 1/2 Cos[b]^2 Sin[a]^2 -         2 Cos[a] Cos[b] Sin[a] Sin[b] - 1/2 Cos[a]^2 Sin[b]^2 +         1/2 Sin[a]^2 Sin[b]^2 *)      Unfortunately, it does not apply the distributive property of the product in another case, that is the one I am interested in:               TrigExpand[ Cos[c*(a + b)]^2]          (*  Cos[c*(a + b)]^2  *)      How can I tell _Mathematica_ to do that initial step?


Variable scope in nested NMaximize, NMaxValue

I'm trying to use NMaxValue inside other statements (FindRoot and NMinimize). Those statements should bind variable names, but I'm getting weird warnings which seem to indicate that the variables aren't bound inside the constraints of the NMaxValue statement? Minimal example:               NMinimize[{NMaxValue[{f[x,y],1<x<y},x],1<y},y]          NMaxValue::bcons: The following constraints are not valid: {1<x,x<y}. Constraints should be equalities, inequalities, or domain specifications involving the variables.     NMaxValue::bcons: The following constraints are not valid: {1<x,x<y}. Constraints should be equalities, inequalities, or domain specifications involving the variables.     NMaxValue::bcons: The following constraints are not valid: {1<x,x<y}. Constraints should be equalities, inequalities, or domain specifications involving the variables.     General::stop: "Further output of NMaxValue::bcons will be suppressed during this calculation."      Why are these constraints not valid? y should be in-scope because it's defined by NMinimize, right? Is this a bug?


Optimization problem with matrix positivity constraints

Is it possible for _Mathematica_ to parametrically find a local minimum of a given function (say of some variable $x$ where $(a,b,c)$ serve as parameters) subject to the constraint that a given symmetric matrix is positive semi- definite? The entries of the matrix are monomials of $(x,a,b,c)$. Namely, the function is: \begin{equation} f(q)=\log\bigg[\frac{(1-q)(1-r^2t^2)(1-x)}{1-q-t^2+qr^2t^2-x+2t\sqrt{qx}-r^2(1-x-t^2+xt^2-xt^4+2t^3\sqrt{qx})}\bigg] \end{equation} (where the logarithm is taken to the base of 2)                      f=Log2[((-1+q)(1-r^2*t^2)(1-x))/(-1+q+t^2-qr^2*t^2+x-2*t*Sqrt[qx]-r^2(-1+t^2+x-t^2*x+t^4*x-2*t^3*Sqrt[q*x]))]      and the matrix is: \begin{equation} S=\left( \begin{array}{cccc} \frac{1}{r^2} & 1 & 1 & t\sqrt{x}\\\ 1 & \frac{1}{t^2} & 1 & \frac{\sqrt{x}}{t}\\\ 1 & 1 & 1 & \sqrt{q} \\\ t\sqrt{x} & \frac{\sqrt{x}}{t} & \sqrt{q} & 1 \end{array} \right). \end{equation}               S={{1/r^2, 1, 1, t Sqrt[x]}, {1, 1/t^2, 1, Sqrt[x]/t},         {1, 1, 1, Sqrt[q]}, {t Sqrt[x], Sqrt[x]/t, Sqrt[q], 1}};      the parameters $(x,r,t)$ are arbitrary value in $(0,1]$, which is also the domain of the variable $q$. Thus I need to find the minimum of $f(q)$ subject to $S\succeq0$ (in the sense of positive semi-definiteness) and $q\geq0$. I have no clue how to do it. I've tried using the `FindMimimum`command but didn't manage to make it work.   If is it indeed possible, it would very much help me to know how to formulate such a command. Thanks!


How can we ensure the result of Mathematica is exactly correct?

This is an example, I plot a function and find it has a defect when x approximates 400.               Plot[Cos[.3 x] Exp[-0.01 x], {x, 0, 1000}, PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/d9OvW.png) Another example, we calculate the orbit of planet motion. As we know, the orbit of planet is ellipse when the total energy is negative. However, if we calculate it in a long time, the result will deviate from ellipse markedly - while _Mathematica_ has no any warning or message here! The code and result showed below:               M = 4; a = 700; (*a is the total time of this simulation*)     s =          NDSolve[{x''[t] == -((GM (x[t] + 1))/((x[t] + 1)^2 + y[t]^2)^1.5),                   y''[t] == -((GM y[t])/((x[t] + 1)^2 + y[t]^2)^1.5), y[0] == 2,                   x[0] == .3, x'[0] == .2, y'[0] == -.1}, {x, y}, {t, 0, a},                   MaxSteps -> 10^8];     ParametricPlot[Evaluate[{x[t], y[t]} /. s], {t, 0, a}]      ![enter image description here](http://i.stack.imgur.com/d2uOL.png) What I wonder is how to make sure _Mathematica_ 's result is exactly correct? When we find something special with _Mathematica_ , how can we know it is a new thing, or just a wrong result of _Mathematica_?


CPU usage remains at 13% even after I quit the kernel

I use _Mathematica_ 10.0.0, and after I run it for a while (a few simple commands for example) the CPU usage (Mathematica.exe) remains at 13% even after the calculations are over. I quit the kernel but the program continues to consume resources until I close the program entirely. Is it a bug? How can I suppress such behavior?


Non-convergance of the solution of the 1+1 partial differential equation

I am stacked with a partial differential equation as follows: This is the $\LaTeX$ expression for the equation $$ \frac{\partial y}{\partial t}=\frac{\partial^2 y(x,t)}{\partial x^2} -\left(a-\frac{1}{\cosh ^2(x)}\right) y(x,t)-y^3(x,t) $$ The _Mathematica_ code is here. This is the equation with with $a=0.2$ to be specific:               eq = D[y[x, t], t] ==         D[y[x, t], {x, 2}] - 0.2 *y[x, t] + Cosh[x]^-2*y[x, t] - y[x, t]^3;      and here are the boundary and initial conditions:               bc1 = y[-10, t] == 0;     bc2 = y[10, t] == 0;     ic = y[x, 0] == 0.001*(Exp[-x^2] - Exp[-10^2]);      Here I solve and plot it:               s = NDSolve[{eq, bc1, bc2, ic}, y[x, t], {x, -10, 10}, {t, 0, 20},         PrecisionGoal -> 2];          Plot[Evaluate[y[x, t] /. s /. t -> 20], {x, -10, 10},       AxesLabel -> {Style["x", 16, Italic], Style["y(t=20)", 16, Italic]}]      The result looks like this: ![enter image description here](http://i.stack.imgur.com/zFbkM.jpg) and qualitatively it is what I expect. It should be explained here that this equation has a fixed point. Depending upon the parameter $a$ it may be either $y=0$, or a solution like the one shown in the image above. I am only interested in the system behavior in the fixed point. Intermediate steps are of no interest. For this reason I plot the result at $t=20$, expecting that the solution is already close enough to the fixed point. Let us check the conversion of the obtained solution. The simplest way to do that is to look at the evolution of $y(0,t)$. Here it is: ![enter image description here](http://i.stack.imgur.com/DMi1N.jpg) The conclusion is that what we see is, so far, non-converging. I checked up to $t=200$ with the output of the same type showing non-convergence. It seems to be so for any time duration. However, I solved the same equation with Comsol, and there it nicely converges after only a small number of time steps (five or so). For technical reasons I would, nevertheless, prefer it solved with _Mathematica_ , rather than with whatever else. My question: do you see any workaround?


How to export data from excel specific cells into mathematica?

How to export data from excel specific cells into _Mathematica_? Given that the spreadsheet tab is named XYZ and that I have several cells at various locations in the same column in Excel that I want to export?


Just what kind of transformations can TransformedDistribution handle?

Why does the following command return an empty plot?               Plot[PDF[TransformedDistribution[(2 Z - 1) X,      {Distributed[X, ExponentialDistribution[1]],      Distributed[Z, BernoulliDistribution[0.5]]}], t], {t, -1, 1}]      Yet `RandomVariate` works just fine:               SmoothHistogram@RandomVariate[TransformedDistribution[(2 Z - 1) Abs[X],      {Distributed[X, ExponentialDistribution[1]],      Distributed[Z, BernoulliDistribution[0.5]]}], 1.*^5]      I merely give a particular example; don't focus unduly on it, I want to generalize.


How do I save a variable or function definition to a file?

Is it possible to save a function which was created via `Interpolation` of some data in such a way that I can use this function in a new _Mathematica_ session without repeated interpolation of the data? For example, I have some data which I interpolate in the following way:               exampleData={{1,1},{2,3},{3,4},{4,7},{5,5},{6,4},{7,2}};     interPolFunc[x_]:=Interpolation[exampleData,x]      Now one of the following would be nice:   * a way to save the interpolated function so that it can be used the next time when I work with _Mathematica_ (but I do not want to interpolate the data again, so that I can delete them).   * the data and `Interpolation` command are saved in a separated notebook which is executed when I want to use my `interPolFunc` in another notebook. Unfortunately I did not find any solution for that. But I hope that some of you have several suggestions!


How to save a list of analytic expressions in a file?

I use _Mathematica_ to calculate many analytic expressions, some of them are generated by a loop process, the result can be a vector with a index, e.g., `f[i]`. Now I want to save them in a file, for example _Mathematica_ package file `"result.m"`, and other expression may also want to be added into this file. The file should looks like this:               f[1] = ;     f[2] = ;     ...     f[10] = ;          fsum = ;     gxyz = ;      This should be a simple task, but I can't figure out the solution. Does anyone know how it can be done?


Import/Export Cluster Object

I want to export and then import back in a cluster object from Agglomerate. After the import, the imported object does not behave as a cluster - for example, ClusterSplit does not recognize it as a cluster object. Is there a data format that can be used, so that after export/import the imported object is a cluster?


Save and call matrices with large output in Mathematica

If we have the large matrix               A=RandomReal[{-10, 10}, {1000, 1000}];      and I need it for further calculation, how can I save it on hard disk and then call for further calculation? Output is very large and _Mathematica_ can not present it, so I can not copy/paste it? Is it possible to print it and then call from hard disk? Thank you in advance!


How to export/import function values

I have a function with two variables:               f[x_,y_]:=f[x,y] = ...      I calculated some values (they are fractions like 435345345/3424242424) and would like to store the values from x=1 to x=5000 with y=0 in a file, so that I can use them later again in a function g[x] I exported them:               Export["file.dat", Table[f[x,0],{x,1,5000}]      And then I import them in another file:               data = Import["file.dat", "List"]      Now I can access the fractions in data by using, for example:               ToExpression[data[[7]]]      Which gives me the fraction that was originally stored in f[7,0] So far so good, but I would again like to have the values stored in some function g, with the properties that (in new file) g[x] = f[x,0] (in old file) for x between 1 and 5000 I am not really sure how the notation for that would be :-( Thank you for your help.


How to store a SparseArray?

How to Export/Write a SparseArray?   How to Import/Read a SparseArray?   Is it always stored as a normal array?   How can it be stored in a dense form?   Is a numerical SparseArray different to   Export/Import from a string one?


How can I append Mathematica variables to an output file preserving both names and values?

I have a _Mathematica_ program that calculates a series of large vectors that I need to save for future reference (in addition to some scalar values). I want to save all these to a file, tagged by their _Mathematica_ names, as the calculation proceeds. `PutAppend` will not work because only the data values are stored, losing their associated names. `DumpSave` does not seem to append to the file, while it does store the values with their names. My goal is to be able to load back the expressions later for further analysis, with the names I gave them. I'm sure this is simple, but I have no experience with _Mathematica_ I/O and can't find what I need in the help.


Exporting large expression

I generated a huge mathematical expression (~200k terms, impossible to simplify yet) and want to save it for later analysis. Last time I did `Export` to *.nb file and it froze my whole system so I was forced to kill the kernel and generate it again from scratch. How should I do it correctly and then `Import` it back easily?


Transferring a list from one notebook to another

I have _Mathematica_ code split into two notebooks. The first part is supposed to run and output a list of numbers into a text file, using `Export`. The second part uses `ReadList` to read numbers from the text file, into a list. I don't like having to convert the list into text and then convert it back to a list. Is there any other way of exporting data which might make it faster for _Mathematica_ to import it again as a list? Edit: Suppose the list output from the second notebook has variables and numbers, is storing the result in a text file still ok? For such a case, here is an example of the output list (the way it looks on the text file):               {1}     {75 + 2*Subscript[x, 10] + Subscript[x, 11]}     {-201 - 4*Subscript[x, 10] - 3*Subscript[x, 11] + Subscript[x, 12]}     {157 + 2*Subscript[x, 10] + 3*Subscript[x, 11] - 3*Subscript[x, 12] + Subscript[x, 13]}     {-Subscript[x, 11] + 3*Subscript[x, 12] - 3*Subscript[x, 13] + 10*Subscript[x, 14]}     {-Subscript[x, 12] + 3*Subscript[x, 13] - 12*Subscript[x, 14]}     {-Subscript[x, 13] + 2*Subscript[x, 14]}      If I need to store expressions, which output format is more apt ?


Exporting arrays for storage

I have a set of arrays I would like to output to some file `ArrayStorage.txt` s.t. these arrays could be read-in to a separate notebook on a separate kernel. Is there an easy way to export a set of arrays?


WaveletScalogram in polar coordinates

For given dataset               data = Re[Zeta[1/2 + I Range[0, 100, 0.01]]];      It is nice that Mathematica can plot data in both Cartesian and Polar coordinates.               SetOptions[ListPolarPlot, Joined -> True];     #[data] & /@ {ListLinePlot, ListPolarPlot}      ![enter image description here](http://i.stack.imgur.com/TKZFN.png) WaveletScalogram is an insightful glance in temporal data:               cwd = ContinuousWaveletTransform[data, GaborWavelet[6], {4, 12}, WaveletScale -> 100];     ws = WaveletScalogram[cwd, All, Re, ColorFunction -> "CherryTones"]      ![enter image description here](http://i.stack.imgur.com/M3KD9.png) **Is it possible to somehow visualize it in Polar coordinates?** I would try to extract the data from underlying Graphics, but it is a raster               ws[[1]] // Head     ws[[1, 1]] // Dimensions      > >     Raster >     {48, 5001} >   The only thing that comes to mind is ImageTransformation but I don’t think it is an efficient way (will be hard to scale the axis, etc.). Any advice is appreciated.


How can I execute a sequence of statements interactively?

I'm fairly new to Mathematica. Suppose I have the following function:               f[x_Integer] := Module[{y, z, r},         y = 5;         z = 10;         r = x + y + z;         r     ];      and I would like to halt the execution after each of the statements `y = 5`, `z = 10` and `r = x + y + z`, and resume only after I press a key. (In other words, I'm looking for something like `Console.ReadLine()` in `C#` or `getline()` in `C++`.) Is there an easy way to do this in Mathematica? Thanks in advance for your help.


Cournot Equilibrium

I'm trying to determine reaction functions of a Cournot equilibrium for $n$ firms using the same optimal condition, using the fixed point method. This is the method I'm using:               fixedPoint[Gs_, X_, X0_, tol_, nmax_] :=       Module[{G, sol, oldsol, iter, n, i},       (*Vectors Gs and X must have the same length*)       n = Length[X];       G[s_] := Gs /. Table[X[[i]] -> s[[i]], {i, 1, n}];       infNorm[s_] := Max[Abs[s]];       sol = X0;       oldsol = sol + 2*tol;       iter = 0;       While[And[iter <= nmax, infNorm[sol - oldsol] > tol],        oldsol = sol;        sol = G[sol];        iter++];       Print["Performed ", iter, " iterations"];       If[iter >= nmax, Print["WARNING: Maximum number of iterations was reached"]];       sol]      The equilibrium condition is (the derivative of profit with respect to quantity):               (((qt)^(-1/eta)) - (1/eta)*((qt)^(-1/(eta - 1)))*qi )-ai*q1 == 0      Where `eta` and `ai` are parameters, `qt` is the sum of the quantities produced by the $n$ firms, and `qi` is the quantity produced by a single firm. So, my problem is determining the `Gs` argument of my method for $n$ firms. How do I generate $n$ optimal functions, each assuming its corresponding values for `ai` and `qi`?


Realtime audio processing using Dynamic

Can I make real time audio processing with Mathematica in the same way I can do with images using `Dynamic[CurrentImage[]]`. I know that is possible to use `SystemDialogInput["RecordSound"]` function, but you can't make real time dynamics on it. For example, I would like create one notebook that could make an alert when sound's beyond some level. It's possible?


Mathematica plots a discontinuity in piecewise function that does not exist

I have the following function defined:               IntImpTri[r1_, r2_, r_] :=        Piecewise[{         {((4/((r2 - r1)^2)) ((r^2 - r1^2)/2 - r1 (r - r1))),           r >= r1 && r < ((r1 + r2)/2)},          {(1/2 - (2/((r2 - r1)^2)) (r^2 - ((r1 + r2)/2)^2) +            (4/((r2 - r1)^2)) r2 (r - ((r1 + r2)/2))),           r >= ((r1 + r2)/2) && r < r2},          {1, r >= r2}}, 0];      I am using _Mathematica 9_ and I do not understand why, when I try to plot this function, which is the integral function of a triangle pulse, the figure shows an interruption in the line. If I try the following command: `Plot[IntImpTri[0, 4, r], {r, -1, 5}]`, I get the following output: ![enter image description here](http://i.stack.imgur.com/mjMV0.jpg) There is a discontinuity around `x=2` but the piecewise covers everything!


Why does Plot leave gaps in the graph of a continuous function?

I have plotted the overlapping area of the UnitBox and the triangle function as:               Plot[Evaluate[       Integrate[            Piecewise[{{1, -0.5 <= x < 0.5}, {0, Not[-0.5 <= x < 0.5]}}]             Piecewise[{{x + 1 - a, -1 + a <= x <= 0 + a}, {-x + 1 + a, 0 + a <= x <= 1 + a}}],        {x, -Infinity, +Infinity}]],      {a, -2, 2}, PlotRange -> All]      However, the result has gaps as you can see in the plot: ![enter image description here](http://i.stack.imgur.com/t1wCz.jpg) Why is this happening if the function is continuous? Thanks for your time.


Inaccuracy of Piecewise function?

I have the following issue and can't find a solution so far.               t1 = 60.0*{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,      17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,      33, 34, 35, 36, 37, 38, 39, 40, 41, 42};     T11 = 273.15 + {17.0, 20.5, 22.5, 24.0, 25.5, 27.5, 29.0, 30.5, 32.0,      33.0, 34.5, 36.0, 37.5, 39.0, 40.0, 41.5, 43.0, 44.0, 45.5, 47.0,      48.0, 49.5, 50.5, 52.0, 53.0, 54.0, 55.5, 56.5, 57.5, 58.5, 59.5,      61.0, 62.0, 63.0, 64.5, 65.5, 66.5, 67.5, 68.5, 69.5, 70.5, 71.0,      72};     nlm1 = NonlinearModelFit[Transpose[{t1, T11}],      a*x^2 + b*x + c, {a, b, c}, x, MaxIterations -> 1000];     T1[t_] = Piecewise[{{nlm1[t], t <= Max[t1]}, {nlm1[Max[t1]],       t >= Max[t1]}}];      Then I plot a narrow segment of T1[t]:               Plot[T1[t], {t, 2519.9999, 2520.0001}]      (note that 60*42=2520) and see this: ![plot](http://s2.postimg.org/far2rohax/Shot2.png) This inconsistency leads to more badly inconsistencies in my other calculations. I've tried to set Accuracy and Precision of initial data, those parameters of Piecewise function, WorkingPrecision, but with no result. Does anyone know how to solve this?


Enabled option for slider in Manipulate not updating dynamically

In a `Manipulate` expression I have a slider control which has the `Enabled` option               Enabled -> Dynamic[bool]      When `bool` changes from `False` to `True`, the content pane in the output cell of the `Manipulate` expression should change from ![enter image description here](http://i.stack.imgur.com/mfTZN.png) to ![enter image description here](http://i.stack.imgur.com/SUj6c.png) and the slider should go from disabled to enabled. The visual change takes place as expected, but the slider stays disabled. Can anyone explain this behavior and suggest a way to fix it? Here is my code:               Manipulate[       Column[{If[bool,           content = {Black, Circle[], Red, Disk[{0., 0.}, r]},           RunScheduledTask[bool = True, {2}]];         Graphics[{content}, ImageSize -> 200],         bool}],       {{r, 0.5}, 0., 1., 0.1, Enabled -> Dynamic[bool],                               Appearance -> "Labeled"},       {content, ControlType -> None},       ControlPlacement -> Bottom,       Initialization :>         (content = {Blue, Disk[]};          bool = False)]      I did test a slider that was not inside a `Manipulate` expression and that had a dynamic `Enabled` option. It worked fine. So why not in `Manipulate`? **Update** I contacted Wolfram Research support and got back a suggestion for a work- around. It wasn't what I was hoping for, but it did lead to me something better than I had before. Only problem remaining is that the _Mathematica_ editor's syntax checker doesn't like what I did. I'm living with that. Here are the details: ![enter image description here](http://i.stack.imgur.com/AjIla.png) The question now boils down to: Can the syntax checker be propitiated? **Another Update** I received another response form WRI tech support. > After talking to our developers, it seems that your original method of using > ControlType -> None should have worked after all. This now looks to be an > issue of bad interaction between RunScheduledTask and DynamicModule. This > issue has been filed into our database so that our development team can fix > it at the earliest.


What is the proper way to extract XMLElement values?

I have seen and tried many different versions of XML data parsing here on this forum, and even some in the documentation. Is there a tried and true "Best Practice" way to extract all the XMLElement values or is each new file type a hack a thon to extract the correct data and fields? Here's the code I'm using now, but it's not efficient and does not grab all the values needed. Is there a better way?               a=thePartIreallyneeded;     elements = Column@Cases[dat,      XMLElement[tag : _, _, value : _] :> (tag -> value), Infinity];     pairsE = List @@ elements;     gatheredE = GatherBy[pairsE, #[[1]] &];     propertiesE = Part[#, 1, 1] & /@ gatheredE;     targetPositionsE = gatheredE[[a]];      Here is a very small snippet of the section of values I'd like to extract. What I need to get are the Color Names, the Target Id values and the values for each color name. Thank you!               XMLElement[{"http://colorexchangeformat.com/CxF3-core", "Resources"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",      "ObjectCollection"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",        "Object"}, {"ObjectType" -> "Target", "Name" -> "Target1",        "Id" -> "c1"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "CreationDate"}, {}, {"2013-05-17T11:59:45-06:00"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "DeviceColorValues"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",            "ColorCMYK"}, {"ColorSpecification" ->             "Unknown"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Cyan"}, {}, {"0"}],            XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Magenta"}, {}, {"0"}],            XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Yellow"}, {}, {"0"}],            XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Black"}, {}, {"0"}]}]}]}],      XMLElement[{"http://colorexchangeformat.com/CxF3-core", "Object"}, {"ObjectType" ->   "Target", "Name" -> "Target11", "Id" -> "c11"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",      "CreationDate"}, {}, {"2013-05-17T11:59:45-06:00"}],       XMLElement[{"http://colorexchangeformat.com/CxF3-core",      "DeviceColorValues"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",        "ColorCMYK"}, {"ColorSpecification" ->         "Unknown"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Cyan"}, {}, {"11.596052607559"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Magenta"}, {}, {"25.435485248175"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Yellow"}, {}, {"0"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Black"}, {}, {"0"}]}]}]}]}]}]


Why does Plot[Hold[x], {x,0,1}] work?

It appears that, counter to my expectation, all of these (and probably many others) seem to work fine:               Plot[Hold[x], {x, 0, 10}]          FindRoot[Hold[x^2 == 2], {x, 1}]          NMinimize[Hold[x^2], x]      I would expect `Plot` or `NMinimize` to complain that e.g. `Hold[0]` is not a number. These were mentioned a few times on this site but didn't get any attention: (1) (2). Doing this does appear to solve problems which would normally require `_?NumericQ`. Is this usage of `Hold` supported? Is it _meant_ to work this way, does it work by design, or is it accidental? My guess is that these work accidentally because these functions use `ReleaseHold` internally.


How can I plot a loxodrome?

Can someone show me how to plot a rhumb line (loxodrome) in _Mathematica_ via the `ParametricPlot` function? Here is what I got so far:               ParametricPlot3D[       {Cos[λ]/Cosh[Cot[π/4]*λ], Sin[λ]/Cosh[Cot[π/4]*λ], Tanh[Cot[π/4]*λ]}, {λ, 0, π}]      I am trying to get this one: ![enter image description here](http://i.stack.imgur.com/AWb0q.gif)


Is there a function to generate a minimal clique cover?

This is a graph problem known as the "Clique Edge Cover" or "Intersection Number" problem, and the goal is to find, from a given graph like $E=\\{\\{a,b\\},\\{a,c\\},\\{b,c\\},\\{b,d\\},\\{c,d\\}\\}$ and $V=\bigcup E$, a representation $K=\\{\\{a,b,c\\},\\{b,c,d\\}\\}$ of the cliques in the graph that has the smallest $|K|$, where the relation from $K$ to $E$ is that $E=\\{x:|x|=2\wedge\exists y\in K\,x\subseteq y\\}$, i.e. $E$ is the set of all pairs in the elements of $K$, so that the elements of $K$ are interpreted as cliques in the graph. (This is the "clique edge cover" statement of the problem, which is the one I am directly interested in, but it may help to see the "intersection number" version of the problem, described in the links above.) This problem is known NP-hard, but that's never stopped Mathematica in the past, and I am not looking for a super-optimized implementation, just one that works reasonably well on small instances. Is there a Mathematica or Combinatorica function that directly implements a solution to this problem, and barring that, does anyone want to take a crack at implementing an algorithm to do this? This paper is an analysis of the problem that contains a few algorithms and may be helpful to this end. _I've asked this questionbefore at math.SE, in order to find out what the problem was called._


Control multiple locators along a plot

# Update 1 @ Michael E2, my effort - for what it is worth!:               f[x_] := Im[(-1)^(-1 - x/2) 2^(1 - x) \[Pi]^-x x! Zeta[x]];     f[a_] := -a Zeta[1 - a];     Manipulate[With[{{x0 = Clip[p[[1]], {3, 10}]}, {a0 = Clip[p[[1]], {3, 10}]}},     Plot[{f[x], f[a]}, {x, 3, 10}, ImagePadding -> 20, LabelStyle -> (FontFamily ->      "Ariel"), Epilog -> {PointSize[Large], Red, Tooltip[Point[#], #] &@{x0, f[x0], a0,      f[a0]}}]], {{p, {3, 0}}, Locator, Appearance -> None}, AppearanceElements -> None]      # Original question I would like to control two locators at once (both moving with same x value), outputting 2 sets of coordinates simultaneously. The plot I am working looks like this: ![enter image description here](http://i.stack.imgur.com/O1IaI.gif) generated by the following code:               Plot[{Im[(     N[Zeta[x]] x!)/(\[Pi]^x (2^(x - 1) (-1)^(x/2 + 1)))],      -x Zeta[1 - x]}, {x, 3, 10}, Epilog -> {PointSize[Medium], Red,      Point[{{5, -5 Zeta[1 - 5]},      {5, Im[(N[Zeta[5]] 5!)/(\[Pi]^5 (2^(5 - 1) (-1)^(5/2 + 1)))]}}]}]      Michael E2 and Timothy Wofford provided a code that controls one locator in this post. I would like to achieve the same thing with multiple locators (ideally by moving one locator with cursor & both locators moving with equal x values at the same time - both generating their separate coordinates). If possible also, I would like the manipulate cell to output the value of a function of each point as it moves, along with the sum of both functions. I hope I am making sense here!


Why is mathematica giving wrong and incomparable results for the integral?

1) Integration of Gaussian Distribution with $(x,y,z)$ ranging from $-\infty$ to $\infty$ gives 1 as expected using this command in mathematica. (Total Probability = 1) $\sigma = 200000$ and $\mu=1000000$               Integrate[(E^(-(x - 1000000)^2/(2*200000^2))*E^(-(y - 1000000)^2/(2*200000^2))*               E^(-(z -1000000)^2/(2*200000^2))/(200000*Sqrt[2*Pi])^3) , {x, -Infinity, Infinity},                {y, -Infinity,    Infinity}, {z, -Infinity, Infinity}]      2) Now I want to integrate over $(x,y,z)$ such that $$\frac{x}{1+0.1}+\frac{y}{(1+0.1)^2}+\frac{z}{(1+0.1)^3}\geq 2000000 $$ given that $$x,y,z\geq0$$ So I wrote this in mathematica:               Integrate[(E^(-(x - 1000000)^2/(2*200000^2))*E^(-(y - 1000000)^2/(2*200000^2))            *E^(-(z -1000000)^2/(2*200000^2))/(200000*Sqrt[2*Pi])^3) Boole[x/(1 + 0.1) + y/(1 + 0.1)^2              + z/(1+ 0.1)^3 - 2000000 >= 0], {x, 0,   Infinity}, {y, 0, Infinity}, {z, 0, Infinity}]      But the answer I am getting is some very big number ($1.7\times10^{17}$) Can anyone point out the mistake?


How to make "molbio-style heat maps" in Mathematica

> **Possible Duplicate:**   >  How to combine ArrayPlot's? [NB: This question is specifically addressed to those who have used (or attempted to use) Mathematica to generate "heat maps" (as the term is used in the context of high-throughput biology research).] The short version of this question is: > What functions does Mathematica have to produce "heat maps" like those used > by molecular biologists to visualize high-throughput gene expression data? (For reasons I describe in more detail below, `ArrayPlot` and `MatrixPlot` are _completely inadequate_ for the task.) * * * Long version: In the field of high-throughput molecular biology research, so-called "heat maps" have become a veritable _workhorse format_ for data visualization (even though the data never has anything whatsoever to do with heat). For example, here's a typical one (from the Wikipedia entry on heat maps): ![enter image description here](http://i.stack.imgur.com/uhScL.png) (In the example above, the heat map is decorated with dendrograms along the top and right edges. For the purposes of this question, please ignore these dendrograms. All I'm interested in is the central array of colored rectangles.) Initially "heat maps" were used for visualizing high-throughput gene expression data obtained from microarray-based experiments, but nowadays they are used for visualizing _any type of data_. Given that such "heat maps" are _so ubiquitous_ in mainstream biology research, I had expected that Mathematica would have by now implemented multiple specialized functions and/or packages for producing and manipulating them. After looking very hard for such functions, however, I'm beginning to suspect, in shock, that I may have been completely wrong about this. > _The purpose of this question is to get confirmation that this suspicion is > basically right, or (hopefully) information showing that it is not so._ The closest I have found are the functions `ArrayPlot` and `MatrixPlot`. At first blush these functions seem to fit the bill, until one tries to perform the simplest manipulations with the `Graphics` objects they produce. For example, just to _display side-by-side_ two `ArrayPlot`-generated heat maps of equal heights but unequal widths is a nightmare; e.g.: ![enter image description here](http://i.stack.imgur.com/zD6oA.png) Now, I'm not a Mathematica novice; I've been bashing my skull against it since the early 90's. Still, it took me _about 6 hours_ of mostly failed attempts, and of far more hacking at the internals of these `Graphics` objects than such a trivial task should ever require1. (BTW, the situation with `MatrixPlot` was not any better.) This humbling experience has convinced me that, whatever other utility `ArrayPlot` and `MatrixPlot` may have _they cannot possibly be considered adequate tools for making heat maps._ (I suspect that the reason why `ArrayPlot`\- and `MatrixPlot`-generated `Graphics` are so difficult to work with (as "heat maps" at least) is that they are based on `Raster` objects, but this is just a hunch, since the Mathematica documentation, as usual, remains safely oracular on what may be going on.) So the question at this point is the one at the top of this post. * * * 1I'd love to post the function that I eventually managed to implement to solve the problem, but the post I submitted about this problem was closed by the Gods.