Is it possible to lower the bitwidth of (floating point) numbers?

The answer to this question will most probably be a definite no. Nevertheless, I would like to know whether it is possible to represent reals in the memory on less than the standard 32 or 64 bits (depending on machine). This limits my exploration to $\sim 2^{14} \times2^{14}$ matrices, though with half or quarter precision I could venture a bit further. The matrix itself cannot be broken down to smaller pieces for further compuation, and it cannot be reworked to a simpler one, but high precision is of no importance. The question is not about refactoring matrices but about number representation and memory handling by _Mathematica_. **Warning, the following computation may eat through your memory limits.**               n = 14;     all = (2^n)*(2^n);     m = RandomReal[{0, 1}, {2^n, 2^n}];     {all, (ByteCount@m/1024./1024) "MB", ((ByteCount@m/all*8.) // N) "bit"}     ClearAll[m];      > >     {268435456, 1024. "MB", 64. "bit"} >   I am using 64-bit Win7, with 2 GB RAM, and (expectedly) my system almost chokes on this code. And then of course I hadn't calculated _anything_ with the matrix yet...


Why doesn't ReplaceAll work on Image?

`ReplaceAll` seems not to reach inside `Image`, and I don't see why it shouldn't. Here is an example. Create a black and white image with four pixels:               image = Image[{{1, 0}, {0, 1}}]      The full form of `image` is:               Image[List[List[1.`, 0.`], List[0.`, 1.`]], "Real", Rule[ColorSpace, Automatic], Rule[Interleaving, None]]      The following line switches the pixels as desired:               Image[ImageData[image] /. n_?NumberQ -> 1 - n]      My question is, in the following usage, why doesn't `ReplaceAll` reach inside `Image` and accomplish the same?               image /. n_?NumberQ -> 1 - n


BarChart without axes neglects the last zero of a list

Creating a BarChart with {1, 2, 3, 0} as               BarChart[{1, 2, 3, 0}, Axes -> False, Frame -> True]      gives me only the first three bars, a chart identical to just               BarChart[{1, 2, 3}, Axes -> False, Frame -> True]        1. Is this an intended behaviour or a bug?   2. (Originally I asked for a workaround. I think I can just use `Axes` instead of `Frame`. Let me ask this instead for the sake of knowledge.) What to do if I need `Frame` but not `Axes`? I'm using Mathematica 9.


NDSolve for a large system of simple ODEs

I am solving a system of many (more than 100) ODEs. It is the kind of standard rate equation encountered in semiconductor physics. Here is the system:               eqns := Table[       P[k]'[t] ==          Sum[-P[k][t] P[q][t] a[k,q,t] - P[k][t] (1 - P[q][t]) b[k,q,t] +              (1 - P[k][t]) P[q][t] c[k,q,t] + (1 - P[k][t]) (1 - P[q][t]) d[k,q,t],              {q, Drop[Table[i, {i, 1, M}], {k}]}]          - e[k,t] (P[k][t])^2 + f[k,t] (1 - P[k][t])^2,       {k, 1, M}];      where `P[k][t]` represent probabilities (bounded between 0 and 1). The form of the solution for every `P[k][t]` is very close to an analytical one, and it is very smooth (basically has just one maximum, quite like a gaussian). I am interested in gettign `Sum[P[k][t], {k, 1, M}]`. I solve the system with               functionlist = Table[P[k], {k, 1, M}];     initialconds = Table[P[k][t0] == initialvalue[[k]], {k, 1, M}];     eqnstosolve = Join[eqns, initialconds];          NDSolve[eqnstosolve, functionlist, {t, t0, tfin},        Method -> {"EquationSimplification" -> "Solve"}];      Question: is there a better way? I tried several method and this seems the faster. However, for my large system of equation evaluation takes hours. I would like, for example, to use a very fast and sloppily method at the beginning and then to refine the peak. Or I would just like to solve faster than this method by adjusting the steps. So far everything I've tried just make things worse. I not even sure what `EquationSimplification->Solve` really does. Any help is appreciated. EDIT: since I have suggested to paste a running code, here is my actual code. The problem is what I stated previously in a more polished way:               Ns = 40;     \[Alpha] = 0.01;     T=0.1;     v=0.0001;          kEven[n_, N_] := 2 \[Pi] n/N  - (N - 1) \[Pi]/N;     kPos[Ns_] := Table[kEven[n, Ns], {n, Ns/2, Ns - 1}];     \[Epsilon][g_, k_] := Sqrt[1 + g^2 - 2 g Cos[k]];          Jf = 1.0;     \[Theta][k_, g_] := ArcTan[g - Cos[k], Sin[k]];     J[\[Omega]_, \[Alpha]_, s_, \[Omega]c_] :=        2 \[Alpha] \[Omega]^         s Exp[-\[Omega]/\[Omega]c] HeavisideTheta[\[Omega]];     gOhm[E_, T_] :=       If[E == 0,        2 N[\[Pi]] \[Alpha] T, \[Pi] ((J[(E + 10^(-20)), \[Alpha], 1,               10^6] -              J[-(E + 10^(-20)), 0.01, 1, 10^6]) Exp[(E + 10^(-20))/             T] )/(Exp[(E + 10^(-20))/T] - 1)]               h[t_] := HeavisideTheta[1 - v t] (1 - v t);     tin = -2/v;     relaxfact = 1;     tfin = relaxfact/v;              eqnsPOS := Table[P[k]'[t] ==((1/(2 Ns)) Sum[                 -P[k][t] P[q][t] (W[+1, +1, k, q] + W[+1, +1, k, -q])                  - P[k][t] (1 - P[q][t]) (W[+1, -1, k, q] + W[+1, -1, k, -q])                  + (1 - P[k][t]) P[q][t] (W[-1, +1, k, q] + W[-1, +1, k, -q])                  + (1 - P[k][t]) (1 - P[q][t]) (W[-1, -1, k, q] +                      W[-1, -1, k, -q])                 , {q, Drop[Table[i, {i, 1, Ns}], {k}]}]               - (1/(2 Ns)) W[+1, +1, k, k] (P[k][t])^2               + (1/(2 Ns)) W[-1, -1, k, k] (1 - P[k][t])^2)           , {k, 1, Ns}];                             kPos[2 Ns];         Clear[W];         W[s1_, s2_, k_, q_] :=           W[s1, s2, k,             q] = (1 -               s1 s2 Cos[                Sign[k] \[Theta][kPos[2 Ns][[Abs[k]]], h[t]] +                  Sign[q] \[Theta][kPos[2 Ns][[Abs[q]]],                    h[t]]]) (gOhm[(s1 \[Epsilon][h[t], kPos[2 Ns][[Abs[k]]]] +                 s2 \[Epsilon][h[t], kPos[2 Ns][[Abs[q]]]]), T]);              functionlist = Table[P[k], {k, 1, Ns}];              thermalPsFD[j_, g_] := 1/(Exp[\[Epsilon][g, kPos[2 Ns][[j]]]/T] + 1);                   thermalPsInit =           Table[1/(Exp[\[Epsilon][h[t], kPos[2 Ns][[k]]]/T] + 1), {k, 1,          Ns}] /. t -> tin;          initialconds = Table[P[k][tin] == thermalPsInit[[k]], {k, 1, Ns}];          eqnstosolve = Join[eqnsPOS, initialconds];          time = AbsoluteTiming[       spos = NDSolve[eqnstosolve, functionlist, {t, tin, tfin},           Method -> {"EquationSimplification" -> "Solve"}];       ];     Print["time NDSolve" <> ToString[time[[1]]/60.] <> ToString[" min"]];


How to format output when using Manipulate

1. As in the title, I want to output the image of a 3D body with its volume and surface area shown nicely beside it. (Maybe in a table?) But how can I do it?   2. Is it possible to calculate the surface area for each specific facets?  For example, consider the simple case:               Manipulate[       {RegionPlot3D[x + y + z < A, {x, 0, 1 - A}, {y, 0, 1 - A}, {z, 0, 1 - A},           PlotRange -> {0, .5}],        NIntegrate[Boole[x + y + z < A], {x, 0, 1 - A}, {y, 0, 1 - A}, {z, 0, 1 - A}]},        {A, 0, .99}]      What I can get so far is showing both the plot and data but not formatting it well. ![Current progress](http://i.stack.imgur.com/Di2BY.png)


Define new number set

May seem strange at first, but can you make mathematica change the value of 0 to 10 and 11 to 1 for all occurrences. Let me explain: I'm looping through a matrix and for each element, I want something to happen depending on the values in each element above, below, to the left and to the right. When you're at the first element however there is nothing to the left, or above, so instead I would like to use the values on either side of the matrix as if you'd curled the matrix back round onto itself, as shown below. ![](http://i.stack.imgur.com/9i2Uo.png) X denotes what element you're looking at and then T,B,L & R, correspond to the cells at the Top, bottom, to the left & right respectively. Here's the code I wrote without thinking too much and it throws up an error because it asks for elements that do no exist. (e.g. "i-1" when i=1)               Do[       Do[     {n, m} = RandomChoice[{image[[i + 1, j]], image[[i, j + 1]],      image[[i - 1, j]], image[[i,j - 1]]} -> {{i + 1, j}, {i, j + 1}, {i - 1, j}, {i,j - 1}}];     newimage[[n, m]] = image[[i, j]];     , {j, columns}];       , {i, rows}];      So, without whacking loads of If statements in there, is there an elegant way to accomplish this? Hope I explained this half decently.


Stopping- threshold and stopping- time of stochastic processes.

Rod Lm helped me to generate the following code, which I want to extend a little bit. So my intention is to use the threshold (the green line) as boundary in the following way: as soon as the process hits the threshold (watermark) it stops and is also excluded from the calculation of the mean function. So all processes which equal or fall beneath the threshold should stop and all processes that remain beyond the threshold should continue and the mean should only be calculated from the processes that remain beyond the threshold. Is this or something similar even possible? Thank you. the code:               Manipulate[SeedRandom[seed];     meanvector := Mean[assets];     assets = Table[     RandomFunction[GeometricBrownianMotionProcess[μ, σ, S0], {0, time, 0.1}]["Path"], {P}];     G1 := ListLogPlot[     assets, GridLines -> {{}, {threshold}}, GridLinesStyle -> Directive[Green, Thick], Joined -> True, AxesLabel -> {"Time", "St"}, PlotLabel -> Style["Forecasted Stock Price\n (Brownian Motion)", Bold], PlotRange -> All, PlotStyle -> Directive[{Thin, Lighter@Gray}]];          G2 := ListLogPlot[     Mean[assets], Joined -> True, PlotStyle -> Directive[{Thick, Darker@Red}]];         Show[G1, G2],         {{S0, 25, "Initial Stock Value"}, 1, 500, 0.5, Appearance -> "Labeled"},         {{μ, 0.08, "Drift μ"}, 0.01, 0.2, 0.01, Appearance -> "Labeled"},           {{σ, 0.2, "Standard Deviation σ"}, 0.01, 1, 0.05, Appearance -> "Labeled"},             {{P, 6, "Paths"}, 1, 20, 1, Appearance -> "Labeled"},             {{time, 10, "Time t"}, 1, 20, 1, Appearance -> "Labeled"},             {{threshold, 25, "Watermark"}, 1, 500, Appearance -> "Labeled"},             {{seed, 1, "New Random Case"}, 1, 100, 1},     Button["Set Initial Values", {S0 = 25, μ = 0.08, σ = 0.20, P = 6, time = 10, threshold = 25}, ImageSize -> 150],                 ControlPlacement -> Left]


Running out of memory using FindMinimum with ParametricFunctions

I am running a pretty large optimization problem which actually consists of an outer an inner optmization problem. I use ParametricNDSolve for solving a ODE system. When the optimization is done, Mathematica uses almost all of my RAM memory. If I try Remove["Global`*"] the memory used is still the same. Is there an easy way to check where the RAM in used?


Plotting a Complex Valued Function

Suppose that a complex valued function `f[z]=f[x+i y]=u[x,y]+i v[x,y]`. I want to plot3d its real part by coloring it with respect to its imaginary part. For instance, if `m` and `M` are the smallest and greatest values of the imaginary part, I want to color the graphic from white to black depending on the value of the imaginary part (`m` is white, `M` is black). I would be very glad if you can help me.


Compile and "True should be a machine-size real number..." Error

I am trying to compile a little summation function. As far as I understand, because the built-in `Sum` function can also return `NaN` objects I have to make sure only numbers get out before returning.               X = Compile[{}, (        result = Sum[i, {i, 10}];        If[NumberQ[result], Return[result], Abort[]];        )];      The problem is that I keep getting the following two warnings... > CompiledFunction::cfse: Compiled expression True should be a machine-size > real number. CompiledFunction::cfex: Could not complete external evaluation > at instruction 2; proceeding with uncompiled evaluation. I guess the glitch is in the `NumberQ` function and its return type. Any ideas on how to handle this issue correctly and effectively? **EDIT:** When I omit the check for numeric values while inserting a Return[] statement Mathematica falls back to the uncompiled version (warning: Compile::cret).


Is there a way to recreate the typical Red/Blue-Postereffect using Mathematica?

I think nearly all of us have at least once seen an image like this: ![enter image description here](http://i.stack.imgur.com/Zxomk.jpg) So I wondered whether it is possible to recreate this effect using Mathematica because it seems like it wouldn't need that many processing steps. Any ideas? http://hplussummit.com/images/wolfram.jpg this can be used as a source image.


Can a Table iterator "leak" into a Module?

I want to repeatedly call a module by using a Table statement. When I use an `i` iterator in the Table command calling the module, I receive the error message "Table::itraw: Raw object 1 cannot be used as an iterator. >>" The module also contains a separate Table statement with the `i` iterator. I noticed that when I change the iterator in the Table statement calling the module to something else, say `v` I no longer get the error message above. This makes me think the `i` iterator is leaking into the module, so .... _Question 1_ : Am I correct that the value of the `i` iterator from the Table statement calling the Module is leaking into the module? _Question 2_ : Is this expected behavior? _Question 3_ : Why does this happen? _Question 4_ : Is there another way to solve this problem, other than to avoid the use of `i` as an iterator in both the Table calling the module and the module itself? Thank you for any advice! Todd * * * Here is a snippet of the offending code:               errorcorrection[signaltype_,chipid_,probesetpostocheck_]:=Module[{clusters,positions,loopindex,groupminuscurrent,similarprobesets},          loopindex=1; (* initialize while loop index to 1; this loop continues for the length of the number of probesets that need checked for unusual signal - which is the length of the probesetpostocheck *)          While[loopindex<=2(*Length[probesetpostocheck[chipid]]*),          clusters=Flatten[Drop[Sort[FindClusters[signaltype[chipid][[probesetpostocheck[chipid][[loopindex]]]],3,DistanceFunction->EuclideanDistance,Method->"Agglomerate"]],-1]]; (* locate probe signals within the current probeset being evaluated that are unreliable and need replaced *)          Print[clusters];          With[{i=i},positions=Flatten[Table[Position[signaltype[chipid][[probesetpostocheck[chipid][[loopindex]]]],clusters[[i]]],{i,1,Length[clusters]}]]]          Print[positions];          If[MemberQ[controlchips,chipid],          (groupminuscurrent=DeleteCases[controlchips,x_/;x==chipid];     similarprobesets=Table[signaltype[groupminuscurrent[[i]]][[probesetpostocheck[chipid][[loopindex]]]],{i,1,Length[groupminuscurrent]}]),          (groupminuscurrent=DeleteCases[experimentchips,x_/;x==chipid];     similarprobesets=Table[signaltype[groupminuscurrent[[i]]][[probesetpostocheck[chipid][[loopindex]]]],{i,1,Length[groupminuscurrent]}])]          Print[similarprobesets];          loopindex++]]      * * *               run2 = Table[       errorcorrection[pmsignal, experimentchips[[i]], pmpostocheck], {i,         1, 1}]               {11719.,1567.,2149.,2001.,1781.,1693.}          Table::itraw: Raw object 1 cannot be used as an iterator. >>          Table[Position[pmsignal[GSM356796][[pmpostocheck[GSM356796][[loopindex$112290]]]],clusters$112290[[1]]],{1,1,Length[clusters$112290]}]      * * *               run3 = Table[       errorcorrection[pmsignal, experimentchips[[v]], pmpostocheck], {v,         1, 1}]          {11719.,1567.,2149.,2001.,1781.,1693.}          {7,6,8,9,17,20}      * * * After considering everyone's responses below, I have been able to get my code to work better by replacing the `With[{i=i},positions=Flatten ....` statement inside the errorcorrection module with `Module[{i=i},positions=Flatten ....` As noted `Block` also works fine. I am still puzzled, however, why `i` takes on a value of 1 inside the `errorcorrection` module, when the module is called by this statement:               run2 = Table[errorcorrection[pmsignal, experimentchips[[i]], pmpostocheck], {i, 1, 1}]      An example of output showing the iterator `i` is here:               run2 = Table[errorcorrection14[pmsignal, experimentchips[[i]], pmpostocheck], {i, 1, 1}]               {11719.,1567.,2149.,2001.,1781.,1693.}      `i` equals 1               {7,6,8,9,17,20}      _Question 5_ : (continuing from numbering above): Doesn't the `Table` command in `run2=Table[errorcorrection14[pmsignal, experimentchips[[i]], pmpostocheck], {i, 1, 1}]` localize the iterator? _Question 6_ : If so, why does that value show up in the `errorcorrection` module? _Question 7_ : If `i` did NOT take on the value of 1 (or any value) in the `errorcorrection` module, would my original `With[{i=i},positions=Flatten` statement have worked ok? It seems to me (in my naivety) that the problem with using With in this case, is that `i` is taking on a value in the module from the `Table` statement calling the module .... but I thought Table should localize `i` and prevent its value from going into the module?? Thank you again, as I struggle to understand at a "deeper" level.


NDSolve Convergence test failure and significant effect of DifferenceOrder on eventual results

I am solving a non linear partial differential equation with what I call free boundary conditions (solid mechanicists would know this as _simply supported_ ). I realized that this boundary condition does induce a certain stiffness in my equation which is not so strong for, say, periodic boundary condition. How do I know this? The simulation runs longer for free boundaries with a stiff method such as `LSODA`. This tells me that the time step is being made smaller and smaller to accommodate this rapidly changing time variation. I also have various _structures_ forming as obvious from the plot of my result. So I use the `TensorProductGrid` spatial discretization method as I gather it would be useful to solve this equation with a preferential spatial grid treatment (denser grid in regions of necessity). As I increase the `DifferenceOrder` for my method/spatial discretization, I notice that I run into convergence issues `NDSolve::ndcf` at a later stage. Viz., for a smaller `DifferenceOrder` I have a convergence issue at a later time. This initially struck me as being a little strange as wouldn't a superior difference order help alleviate convergence? But then obviously, a greater difference order would catch the issue with convergence earlier! ## Here is my code:               m=0.05;     \[Epsilon]=10^-6;     Bo=1/300;     \[Delta]=10^-7;     Bi=1;     K1=1;     wn=2;          (*R=Ra/(Pr S1);*)     R=0*1/10;     {xMin,xMax}=wn{0,79.5788};     k=0.0677*92.389/(xMax/wn);     TMax=10000*100;     n=1;               uSolpbc[t_,x_]=u[t,x]/.NDSolve[{\!\(     \*SubscriptBox[\(\[PartialD]\), \(t\)]\(u[t, x]\)\)+\!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\(u[t, x]\), \(3\)]\      \*SubscriptBox[\(\[PartialD]\), \(x, x, x\)]u[t, x])\)\)-Bo \!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\(u[t, x]\), \(3\)]\      \*SubscriptBox[\(\[PartialD]\), \(x\)]u[t, x])\)\)+m  \!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\((     \*FractionBox[\(u[t, x]\), \(K1 + Bi\ u[t, x]\)])\), \(2\)]\      \*SubscriptBox[\(\[PartialD]\), \(x\)]u[t, x])\)\) +\[Epsilon]/(Bi u[t,x] + K1) +\[Delta] u[t,x]^3/(Bi u[t,x] + K1)^3 D[D[u[t,x],x],x] + R \!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\(u[t, x]\), \(3\)]\      \*SubscriptBox[\(\[PartialD]\), \(x\)]u[t, x])\)\)== 0,          u[0,x]==1-0.05 (Cos[k*x]),          (*PERIODIC BOUNDARY CONDITIONS-START*)     (*u[t,xMin]== u[t,xMax],     Derivative[0,1]u[t,xMin]==Derivative[0,1]u[t,xMax],     Derivative[0,2]u[t,xMin]==Derivative[0,2]u[t,xMax],     Derivative[0,3]u[t,xMin]==Derivative[0,3]u[t,xMax]*)     (*PERIODIC BOUNDARY CONDITIONS-END. Uncomment to run periodic case*)          (*FREE BOUNDARY CONDITIONS-START*)          Derivative[0,1][u][t,xMin]==0,Derivative[0,1][u][t,xMax]==0,Derivative[0,3][u][t,xMin]==0,Derivative[0,3][u][t,xMax]==0     (*FREE BOUNDARY CONDITIONS-START*)               },     u,     {t,0,TMax},     {x,xMin,xMax},     (*PrecisionGoal->Automatic,*)     Method->{"MethodOfLines","Method"->"LSODA","TemporalVariable"->t,"SpatialDiscretization"->{"TensorProductGrid","MinPoints"->10000,"MaxPoints"->10000,"DifferenceOrder"->1}}][[1]]      ## And the plotting function:               evapfbc2 = Plot[       uSolpbc[6981*100, x], {x, xMin, xMax},        PlotStyle -> {Black, Thick, Dashed},       AxesLabel -> {"\[Lambda]", "h"},       BaseStyle -> {FontWeight -> "Plain", FontSize -> 18},       PlotRange -> {{0, xMax}, {0, 3.5}}       ]      ## My questions are:   1. Should I be increasing the difference order for better results? (I understand that with a difference order set to `n`, it allows the stiff solver "elbow room" up to and including order `n`)   2. Is this the wrong method to use and is there something I could do in mathematica that would make this better? I am assuming that I would need to use a stiff solver for this problem. ## Note: With a difference order of 1, this runs for about 10-15 seconds on an i7/8GB RAM system. With a difference order of 12, it runs for about 20 **minutes** and consumes about 3-4 gigs of RAM.


How to display edge labels above edges?

The following code shows that edge labels "cover" edges in `GraphPlot3D`               GraphPlot3D[{{1 -> 2, "1\[Rule]2"}, 4 -> 1, {2 -> 4, "2\[Rule]4"},          1 -> 5, 2 -> 5, 5 -> 4},              EdgeRenderingFunction -> ({If[#3 =!= None,                  Text[#3, Mean[#1], Background -> Yellow], {}], Line[#]} &)]      But if I change `GraphPlot3D` to `GraphPlot`, the edges will go across the labels. How can I keep the labels with the highest z-index? Thank you. **Snapshot** `GraphPlot3D` ![enter image description here](http://i.stack.imgur.com/YHrfB.png) `GraphPlot` ![enter image description here](http://i.stack.imgur.com/k4Q3e.png)


Aligning a DensityPlot with a Plot

I am trying to show a gradient field behind a plot, and then its density in a separate plot below. I understand (as in this question) that this must normally be done using the ImagePadding directive. However, that does not quite align the plots in this case:               padding = {{20, 30}, {20, 30}};      GraphicsColumn[       {        Show[         DensityPlot[PDF[NormalDistribution[0, 1], Log[x/40]] ,            {x, 15, 60}, {y, 0, 30},            ColorFunction -> "SunsetColors"],          Graphics[{Dashed, Gray, Line[{{40, 0}, {40, 30}}]}],          Plot[If[x < 20, 10, If[x < 25, 2 x - 30, 20]], {x, 15, 60},            PlotRange -> {0, 30} ,            PlotStyle -> {RGBColor[0.5, .7, 0.2], Thickness[0.01]}],          ImagePadding -> padding, PlotRangePadding -> None        ],         Plot[PDF[NormalDistribution[0, 1], 5 Log[x/40]] , {x, 15, 60},            PlotStyle -> {RGBColor[1, 0.4, 0], Thickness[0.01]},           ImagePadding -> padding]       }     ]      ![Align me](http://i.stack.imgur.com/Nzm0g.png) Is there a way to get the abscissa ranges to match?


Random reals according to probability distribution

How do I generate a list a random real numbers that follow a probability distribution? If my pdf is $f(x)$, how do I "force" the random numbers to follow $f(x)$?


How to use ProbabilityDistribution for a posterior expression

I am performing a Bayesian updating on a Lognormal prior. After combining the prior and likelihood and dividing by the normalization constant I get the following expression as the posterior:               (0.805745 E^(-7.05*10^6 t - 0.255194 (15.576 + Log[t])^2))/t      I now want to use this as a distribution:               pdist = ProbabilityDistribution[posterior, {t, 10^-12, 10^-5}];      So far ok. I can now plot with the distribution               LogLinearPlot[PDF[pdist, t], {t, 10^-11, 10^-6}, PlotRange -> All, FrameLabel -> {"Failure Rate (f/hr)", "PDF"}]      But I cannot take the mean, Mean[pdist], or variance etc, they just return the input. Trying RandomReal[pdist] returns the following:               RandomReal::udist: The specification is not a random distribution recognized by the system      What am I missing in the assignment of the expression to ProbabilityDistribution[]. Clay


Random number generation from a given distribution

Is there any way to obtain random numbers from a user defined continuous distribution in Mathematica? Thank you very much


plotting hypergeometric functions

Does anyone know why a plot of a hypergeometric function turns out differently in _Mathematica_ than in _Maple_? The function I'm plotting between x=-30 and +30 is:               Re[Exp[-2 I p x]*(Conjugate[A]*Cosh[q - x]^(v + 1)*     Hypergeometric2F1[0.5 (v + 1 - I), 0.5 (v + 1 + I),       1/2, -Sinh[q - x]^2] +       Conjugate[B]*Cosh[q - x]^(v + 1)*Sinh[q - x]*      Hypergeometric2F1[0.5 (v + 1 - I) + 0.5, 0.5 (v + 1 + I) + 0.5,         3/2, -Sinh[q - x]^2])*(A*Cosh[q + x]^(v + 1)*       Hypergeometric2F1[0.5 (v + 1 + I), 0.5 (v + 1 - I),         1/2, -Sinh[q + x]^2] +       B*Cosh[q + x]^(v + 1)*Sinh[q + x]*       Hypergeometric2F1[0.5 (v + 1 + I) + 0.5, 0.5 (v + 1 - I) + 0.5,         3/2, -Sinh[q + x]^2])]      where `q=p=3`, `v=1`, `A=0.5+0.5I` and `B=-1+I`. I've attached both plots from _Maple_ (first image) and _Mathematica_ (second image) ![Maple plot](http://i.stack.imgur.com/SiiX1.jpg) ![Mathematica \[;pt](http://i.stack.imgur.com/5rreP.jpg)


Computing distance matrix for a list

Using functional programming in Mathematica, how can I compute a distance matrix for every element in a list of matrices... The distance would be computed between the item in the list and a "target matrix". For simplicity, let's consider that the list is a list of simple 3x2 matrices of integer with a range [0,4]. The target matrix is a matrix of that type as well. The reason I want to do that is to filter the list to find the matrix closest to the target one.


random number visualization without generator (Spectral Test)

Does anyone have codes for using only numbers to make this kind of random- number visualization and not requiring a number generator? http://demonstrations.wolfram.com/PoorStatisticalQualitiesForTheRANDURandomNumberGenerator/ http://en.wikipedia.org/wiki/Spectral_test


Pruning elements in an array based on the existence of similar elements in adjacent arrays

Imagine I have a series of particles floating around in $\mathrm{R}^3$, where, at any given time, particles can pop into and out of existence. Here, for some number of time points, $(t_1, \dots, t_N)$, I generate an unordered list of the positions of each of the particles present in the chamber: $(p_{(k,1)}, p_{(k,2)}, \dots) \in l_k$ s.t. I have a set of lists of particle positions, $(l_1, \dots, l_N) \in L$, each list corresponding to each time point. I would like to generate a set of pruned lists $(q_1, \dots, q_N) \in Q$, where each $q_i \subseteq l_i$ consists of the set of particle positions in $l_i$ that likely arose from measuring the same particle that   * existed and was measured at $\alpha$ previous time points. If, for example, we set $\alpha = 2$ and we measure a particle at time $t_i$, we would only place that measurement in $q_i$ if a very similar measurement was made at times $t_{(i-1)}$ and $t_{(i-2)}$.   * also existed and was measured for the next $\beta$ time points. If, for example, we set $\beta = 3$ and we measure a particle at time $t_i$, we would only place that measurement in $q_i$ if a very similar measurement was made at times $t_{(i+1)}$, $t_{(i+2)}$, and $t_{(i+3)}$.  If the particles were frozen in place, generating some $q_i \subseteq l_i$ would be a simple matter calculating a few intersections between $l_i$ (using the `Intersection[]` function in _Mathematica_ ) under the assumption that the probability one particle pops out of existence and another arises in exactly the same place in-between measurements is arbitrarily small. However, here the particles are moving, so we need to "guess" that some measured particle position at time $t_i$ and either times $t_{(i-\delta)}$ or $t_{(i+\delta)}$ (for small enough $\delta$) corresponds to the same particle if the Euclidean distance between the measured positions is below some threshold $\tau$. So if we set $\beta = 2$, we would need to see that the particle only moves a threshold distance $\tau$ from the current time point to the next, and then only moves a distance of at most $\tau$ in the interval between that time point to the one after (i.e., for some time point $t_k$ we require that some $\lvert p_{(k, \dots)} - p_{(k+1, \dots)}\rvert \leq \tau$ and that $\lvert p_{(k+1, \dots)} - p_{(k+2, \dots)}\rvert \leq \tau$). Said another way: Let $(l_1, l_2, \dots, l_N) \in L$ be an array of lists. For $\alpha = 1$ and $\beta = 1$, I'd like to remove all elements in each $l_i$ that are not within some threshold Euclidean distance $\tau$ of any element in the previous list, and any element in the next list in the array. If we set $\beta = 2$, I would like to prune away elements where there is no element, $p_j$ in list $l_{(i+1)}$ that is at most a Euclidean distance $\tau$ away, and where there is no element in list $l_{(i+2)}$ that is at most a Euclidean distance $\tau$ away from $p_j$. Provided a set of lists $(l_1, \dots, l_N) \in L$, and values for $\alpha$, $\beta$, and $\tau$, is there an elegant and fast way to generate my pruned lists $(q_1, \dots, q_N) \in Q$ (beyond writing a bunch of `Do` or `For` loops)? I am happy to handle the boundaries of the list, i.e., $l_1$ and $l_N$, in whatever manner is most convenient. ::: Let's generate a simple example ::: Let                l1 = {{87.02,892},{1,2},{65,23},{99,99}};      l2 = {{666,666},{777,777},{123,432},{876,28},{39,192},{87.01,892}};      l3 = {{87.0004,892},{8683,12},{7673,777},{7662,2120}};      l4 = {{40,40},{50,50},{87.002,892.001}};      Let $k = 3$, $\alpha = 2$, $\beta = 1$, and $\tau = 0.01$. Looking at list $l_2$, we notice that the only element in $l_3$ that is within a Euclidean distance $\tau$ of an element in $l_2$ is $p_0 = (87.0004, 892)$, displaced to the position $p_{(-1)} = (87.01, 892)$ in $l_2$. We now need to look at $l_1$ and check whether there is an element within a Euclidean distance of $\tau$ of $p_{(-1)} = (87.01, 892)$, and indeed we find that there is some $p_{(-2)} = (87.02, 892)$. Next, we need to check that there exists some $p_1$ in $l_4$ that is within a Euclidean distance $\tau$ of $p_0$, and indeed we find that $p_1 = (87.002,892.001)$ in $l_4$ satisfies this requirement. Looking through the rest of $l_3$, we find that no other elements satisfy the above set of requirements. Therefore, we can write $q_3 = (p_0) = ((87.0004, 892))$. We repeat this procedure to generate a pruned list $q_i$ for each $l_i$, and handle the boundary conditions in whatever manner is easiest. Please note that if we set $\tau = 0$, we could easily just write               q3 = Intersection[l1,l2,l3,l4]      To see this, try               q3 = Intersection[Round[l1], Round[l2], Round[l3], Round[l4]]      As expected, the result is               {{87, 892}}      If we want to grab the non-rounded value(s) in $l_3$ corresponding to this result, we can use the script               q3RealData = Flatten[Table[Nearest[l3, q3[[k]]], {k, 1, Length[q3]}], 1];      Which returns               {{87.0004,892}}      Dealing with $\tau > 0$ in the manner described above in an efficient way (rather than perhaps extending the rounding trick above) is the tricky part of this question.


Error/warning when using NSolve for simple equation

I am using NSolve to solve an equation, as shown here:               T == (0.000250709 E^(0.0269867/(0.0000734429 + 1. T)))/(1.00025 -          1. E^(0.0539734/(0.0000734429 + 1. T)))          NSolve[T == (0.000250709 E^(0.0269867/(0.0000734429 +                1. T)))/(1.00025 -           1. E^(0.0539734/(0.0000734429 + 1. T))), {T}, Reals]      It gives me the warning `Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >>`, but still displays the result. Is it wrong to use NSolve for for such a general task, or am I missing a parameter?


Formatting results of integral approximation methods comparison.

The integral is `Integrate[Sqrt[1+x^3], {x, -1, 1}]`. I want to create a `Table` with three columns and four rows that shows the midpoint, trapezoidal, and Simpson's rule approximations of the integral with $n=4,8,16$ and $32$ subintervals. I defined the three approximations as:               f[x] := Sqrt[1 + x^3]          midptApprox[func_, {x_, a_, b_}, n_] := Module[{f, h = (b - a)/n},       f[t_] := func /. x -> t; h*Sum[f[a + i*h], {i, 0.5, n - 0.5}]]          trapex[func_, {x_, a_, b_}, n_] := Module[{f, h = N[(b - a)/n]},       f[t_] := func /. x -> t; (1/2)*h*         (f[a] + 2*Sum[f[a + i*h], {i, 1, n - 1}] + f[b])]          simpson[func_, {x_, a_, b_}, n_] := Module[{f, h = (b - a)/n, wt},       wt[i_] := 3. + (-1)^(i - 1); f[t_] := func /. x -> t;        If[EvenQ[n], (h/3)*(f[a] + Sum[wt[i]*f[a + i*h],                 {i, 1, n - 1}] + f[b]), "n must be even"]]      I was thinking to use `Grid` and `TableForm@Table[{n,f[n]}, {n,4,8,16,32}]` somehow but I don't know how to include the interval `[-1,1]`.


Put webMathematica folder outside Tomcat webapps folder?

Is it possible to put the `webMathematica` folder outside the usual Tomcat `webapps` folder and still have webMathematica work? _webMathematica_ does work OK if its whole folder is placed inside `webapps`. (This is with Tomcat 7 under OS X 10.8.3.) Configuration details would be greatly appreciated! In asking this I have two aims:   1. Granularize things so that I can just back up the webMathematica folder, along with other documents of mine, separately from backing up Tomcat's own files such as those in its distributed `webapps` folder.   2. Be able to access webMathematica (and, eventually, some specific apps using it) on localhost by means of a simple URL "alias", such as `webmathematica`, rather than the usual complete URL `localhost:8080/webmathematica` \-- just as I can now access Tomcat's webapps by entering the URL `tomcat.local`.


How to calculate this integral? Integrate[BesselJ[0, x - BesselJZero[0, 1]]/x, {x, -Infinity, Infinity}]

I tried to calculate the following integral, but it returned unevaluated.               In[1]:= Integrate[BesselJ[0, x - BesselJZero[0, 1]]/x, {x, -Infinity, Infinity}]     Out[1]= Integrate[BesselJ[0, x - BesselJZero[0, 1]]/x, {x, -Infinity, Infinity}]      Any ideas how to make Mathematica calculate it?


Does LinearModelFit perform an ordinary linear regression (least squares)?

Does `LinearModelFit` give an ordinary linear regression? I see lots of options, but nothing like "least squares" or OLR.


Finding n-th term of a sequence of functions

Lets say, I have the following series of functions, $f_1=a+1$   $f_2=a^2+2a+1$   $f_3=a^3+3a^2+3a+1$   Assume that $f_4, f_5,$ and $f_6$ are also known. However $f_n$ is not known as a function of $n$. From $f_1 ...f_6$, is it possible to reverse engineer the formula for $f_n$ using _Mathematica_? For the sample sequence given above, I should get, $f_n=(a+1)^n$. Is such a feature available in _Mathematica_? If so, can you provide links to the relevant documentation.


Manipulate doesn't work for plotting a region where a matrix is positive semi-definite

I'm facing the following problem and would very much like you help. Thanks is advance! I have defined the following 4x4 matrix: \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} where $(t,r)$ are two parameters (which I can choose arbitrarily to be any value in the segment $(0,1]$) and $(x,q)$ are the variables (each over the domain $[0,1]$). Now, for a fixed pair of $(r,t)$ I want to plot a region of $(x,q)$ over which the matrix $S$ is positive semi-definite (I want it to be a valid covariance matrix). The thing is that when I try to use the Manipulate function (manipulation on $(r,t)\in(0,1]^2$), and plotting the region of $(x,t)$, nothing shows. Namely, Iv'e written the following:               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}};          Manipulate[       RegionPlot[PositiveDefiniteMatrixQ[S],                   {x, 0, 1}, {q, 0, 1}], {r, 0, 1}, {t, 0, 1}]      and I get an empty graph no matter what values I set for $(r,t)$. You might say that maybe this matrix is never positive semi-definite, but the strange this is that if I manually input numerical values to $(r,t)$ and plot the region, everything works fine. I really need to manipulate over all possible parameter value of $(r,t)$. What is wrong here and how can I fix it? Moreover, is it possible for _Mathematica_ to parametrically find a local minima of a certain function (of the variable $q$ where $(r,t,x)$ serve as parameters) subject to the constraint that the above matrix must be positive semi-definite? If so, it would very much help me to know how to formalize such a command.


Find root approximants for low-precision numbers

I want to be able to find low-complexity algebraic approximants to decimal numbers. For example, 1.41 can be approximated as a solution to the polynomial `x^2==2`. There is a Mathematica function `RootApproximant` that seems like it should be able to do this approximation. However, I can't get it to work. `RootApproximant[N[Sqrt[2]]` returns $\sqrt{2}$ correctly, but `RootApproximant[1.41]` doesn't - it prefers to approximate it as `141/100`. Presumably I need to tell it to lower the accuracy it's aiming for. There is an option called "DegreeCost" that can be passed, but I can't work out how to use that to achieve my goal.


Solving PDEs with complicated boundary conditions

The system I'm trying to solve is $$\nabla^2 C_{(r,\theta)} =0$$ $$C_{(\infty,\theta)}=C_0$$ $$ [ \frac{\partial C_{(r,\theta)}}{\partial r} \cos(\theta)+\frac{1}{r}\frac{\partial C_{(r,\theta)}}{\partial\theta} \sin(\theta) ]|_{r=a*\cos(\theta)}=\frac{k}{D}C_{(r,\theta)}|_{r=a*\cos(\theta)}$$ and I have no idea how to enter the bottom equation into Mathematica. The problem I have is the inclusion of the boundary condition. How can I indicate to Mathematica that I want the derivatives to be taken and then have everything evaluated on the sphere $r=a*\cos(\theta)$ ?


Is there a way to separate variables between multiple notebooks?

I often correct homework by checking the calculations in Mathematica. Sometimes you would like to have two solutions open at once. However often defined symbols such as `f` or `phi` regularly overlap between the two notebooks.   * Is there a way to separate them other than using different symbols in every notebook?   * Is it possible to separate some variables yet share others between notebooks?


How to restrict global variables to within a given notebook?

> **Possible Duplicate:**   >  Is there a way to separate variables between multiple notebooks? I assigned a global variable like `a=10;` It works in all my notebooks, but I want to restrict that global variable to that notebook only. How to do that?


Given a sequence of expressions, how can I convert them all into functions?

I have a sequence of expressions               1, x, x^2, ..., x^5      I want to define a sequence of functions out of it, what should I do? Namely I want to define a vector of functions with elements: $$ f_1 = 1, f_2 = x, ..., f_6 = x^5 $$ Any help is appreciated.


Threads vs Cores: How many kernels need to launch in parallel Mathematica?

I have a dual-core intel machine. I would like to test how many parallel local kernels should be launch to get the optimized performance. Knowing that the HyperThreading technology of Intel could run 2 "Threads" on 1 core. That means we could run 4 threads on a dual-core CPU. For informations about "Threads vs Cores", look at here.. AMD says "no" to HyperThreading, and after them, cores is much more important. view amd vs intel: " _Based on the results of the Cinebench® and PovRay® benchmark tests, we find that physical cores outperform enhanced threading software in certain applications."_ Function to evaluate:               mlength[z_] :=       Length[FixedPointList[#^2 + z &, z, 20, SameTest -> (Abs[#] > 2 &)]]      **1\. Sequential Evaluation (No parallel)**               CloseKernels[]; Kernels[]     ParallelTable[        mlength[x + I y], {y, -1, 1, 0.005}, {x, -2, 1,          0.005}]; // AbsoluteTiming      > During evaluation of ParallelTable::nopar: No parallel kernels available; > proceeding with sequential evaluation. > > {8.814056, Null} ![enter image description here](http://i.stack.imgur.com/aOIVc.png) Although no parallel kernel is used, we can see that the second core on the right shares about 50% the work with the first core. I think Windows automatically shares the work for multicore. **2\. Using 1 Slave kernel**               CloseKernels[]; LaunchKernels[1]; Kernels[]     ParallelTable[        mlength[x + I y], {y, -1, 1, 0.005}, {x, -2, 1,          0.005}]; // AbsoluteTiming      > {9.110458, Null} ![enter image description here](http://i.stack.imgur.com/zb4xB.png) By asking Mathematica add one slave kernel, this slave kernel runs on the first core mainly (on the left) and we can see that the work is mainly done in the first core. There are still some works on the second core. **3\. Using 2 slaves kernel**               CloseKernels[]; LaunchKernels[2]; Kernels[]     ParallelTable[        mlength[x + I y], {y, -1, 1, 0.005}, {x, -2, 1,          0.005}]; // AbsoluteTiming      > {4.820431, Null} ![enter image description here](http://i.stack.imgur.com/D6Ffm.png) Now, with 2 slaves kernels, the work is evenly distributed on 2 cores. That's the reason why, we get the results done in half of the time. We can see that Mathematica parallelizes better than Windows. **4.Using 4 slaves kernel**               CloseKernels[]; LaunchKernels[4]; Kernels[]     ParallelTable[        mlength[x + I y], {y, -1, 1, 0.005}, {x, -2, 1,          0.005}]; // AbsoluteTiming      > {5.023232, Null} ![enter image description here](http://i.stack.imgur.com/pAeic.png) ![enter image description here](http://i.stack.imgur.com/Tm0qP.png) I'm trying to add more kernels by supposing that, one core could maintain 2 "threads". But the results is slower. I think Multithreading does not help in Mathematica. So the rule of thumb is: the number of parallel local kernels = number of cores (not threads). Increasing number of kernel just increases the overhead of data transfer between kernels. Any suggestions? ================================================================= **Udate to another computer Intel i7, 4 CORES, 8 THREADS (TRUE HT).**               maxKernel = 8;     data = Table[       CloseKernels[];         LaunchKernels[n];         ParallelTable[          mlength[x + I y], {y, -2, 1, 0.002}, {x, -2, 1, 0.002}]; //          AbsoluteTiming // First, {n, 0, maxKernel}]      > {40.332307, 44.634553, 22.154267, 17.925025, 14.795846, 13.280760, \ > 12.369708, 13.218756, 12.701726} ![enter image description here](http://i.stack.imgur.com/fYOo7.png) We can see that, the time decreases up to 4 Cores, and then, up to 6 threads, time optimized only 1-2 second.


Suppressing Null output with sparse data? A lot of zeros and little nonzeros

I have sparse situation with a lot of zeros, related chat. I want to see only the nonzero things or nonnull things. **Example** > **Input** >   >   >     hello[ii_, jj_] := If[ii == 1, Return[True], Return[False]] >     Table[If[hello[ii, jj], {ii, jj} -> 1], {ii, 1, 5}, {jj, 1, 5}] >   > > **Output** >   >   >     {{{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1, {1, 4} -> 1, {1, 5} -> >        1}, {Null, Null, Null, Null, Null}, {Null, Null, Null, Null, >       Null}, {Null, Null, Null, Null, Null}, {Null, Null, Null, Null, >       Null}} >   > > **Intended Output** >   >   >     {{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1, {1, 4} -> 1, {1, 5} -> 1} >   where the full form of the intended output could be a 5x5 matrix with 1st row with ones and otherwise zeros.


Maintaining map dimensions after using Colorize

I am trying to beautify a map by using `Colorize` as demonstrated in the _Mathematica_ documentation. First, I import a shapefile from DIVA-GIS for France which contains polygons for the country, its regions and departments.               mapdata = Import["http://gadm.org/data/shp/FRA_adm.zip", "Data"];      I then extract the region data and (poorly) place a bounding region around the map:               Graphics[Rectangle[{-6, 41}, {9.7, 51.5}]];     Graphics@{EdgeForm[Thick], FaceForm[White], ("Geometry" /. mapdata[[2]])};     t1 = Show[%%, %]      I can then `Colorize`               t2 = Colorize[MorphologicalComponents[t1, CornerNeighbors -> False], ColorFunction -> "LightTerrain"]      which gives me the following `Image` (note, it is not a `Graphic`) ![France in terrestrial colors](http://i.stack.imgur.com/1CNXP.png) I'd now like to take the department information and lay it over the colored regional map               t3 = Show[Graphics@{Black, EdgeForm[Thin], FaceForm[], ("Geometry" /. mapdata[[1]])}]      ![enter image description here](http://i.stack.imgur.com/tbq72.png) However the `MorphologicalComponents` function rescaled the regional map, preventing me from overlapping t2 and t3 above. Is there a way to get the same or similar effect as obtained through `MorphologicalComponents` and `Colorize` without losing the x,y coordinate data?


Elegant operations on matrix rows and columns

## Question The Mathematica tutorial has a section 'Basic Matrix Operations', describing operations like transpose, inverse and determinant. These operations all work on entire matrices. I am missing a section on basic operations on matrix rows / columns. For example:   1. Extracting a row from a matrix   2. Inserting a row into a matrix   3. Adding two rows within a matrix together   4. Swapping two rows   5. Multiplying a row with a number And similar for columns. What is the most elegant way to implementation of these operations? Speed is not important for me, but simplicity is. ## Summary Here I summarize my personal taste. I will update it whenever someone suggests a way I like more.               m = Range@12 ~Partition~ 3;     m // MatrixForm      $\begin{pmatrix} 1 & 2 & 3 \\\ 4 & 5 & 6 \\\ 7 & 8 & 9 \\\ 10 & 11 & 12 \end{pmatrix}$ Insert a column at position 2:               v = Range[21, 24];     Insert[m // Transpose, v, 2] // Transpose // MatrixForm      $\begin{pmatrix} 1 & 21 & 2 & 3 \\\ 4 & 22 & 5 & 6 \\\ 7 & 23 & 8 & 9 \\\ 10 & 24& 11 & 12 \end{pmatrix}$ ### Extract row / column Extract row 2:               m[[2]]      $(4,5,6)$ Extract column 2               m[[All, 2]] // MatrixForm      $\begin{pmatrix}2\\\5\\\8\\\11\end{pmatrix}$ ### Insert a row / column Insert a row at position 2:               v = Range[13, 15];     Insert[m, v, 2] // MatrixForm      $\begin{pmatrix} 1 & 2 & 3 \\\ 13 & 14 & 15 \\\ 4 & 5 & 6 \\\ 7 & 8 & 9 \\\ 10 & 11 & 12 \end{pmatrix}$ ### Adding two rows / columns column 3 = column 3 + column 1:               m2 = m;       m2[[All, 3]] += m2[[All, 1]];     m2 // MatrixForm      $\begin{pmatrix} 1 & 2 & 4 \\\ 4 & 5 & 10 \\\ 7 & 8 & 16 \\\ 10 & 11 & 22 \end{pmatrix}$ row 2 = row 2 + row 3:               m2 = m;     m2[[2]] += m2[[3]];     m2 // MatrixForm      $\begin{pmatrix} 1 & 2 & 3 \\\ 11 & 13 & 15 \\\ 7 & 8 & 9 \\\ 10 & 11 & 12 \end{pmatrix}$ ### Swapping rows / columns Swap row 1 and row 3:               m2 = m;     m2[[{1, 3}]] = m2[[{3, 1}]];     m2 // MatrixForm      $\begin{pmatrix} 7 & 8 & 9 \\\ 4 & 5 & 6 \\\ 1 & 2 & 3 \\\ 10 & 11 & 12 \end{pmatrix}$ Swap column 1 and 3:               m2[[All, {1, 3}]] = m2[[All, {3, 1}]];     m2 // MatrixForm      $\begin{pmatrix} 3 & 2 & 1 \\\ 6 & 5 & 4 \\\ 9 & 8 & 7 \\\ 12 & 11 & 10 \end{pmatrix}$ ### Multiplying rows / columns Multiply row 2 with 2:               m*{1, 2, 1, 1} // MatrixForm      $\begin{pmatrix} 1 & 2 & 3 \\\ 8 & 10 & 12 \\\ 7 & 8 & 9 \\\ 10 & 11 & 12 \end{pmatrix}$ Multiply column 1 with 5:                ((m // Transpose)*{5, 1, 1}) // Transpose // MatrixForm      $\begin{pmatrix} 5 & 2 & 3 \\\ 20 & 5 & 6 \\\ 35 & 8 & 9 \\\ 50 & 11 & 12 \end{pmatrix}$ ## References   * What is the most efficient way to add rows and columns to a matrix?   * Thanks to nikie for suggesting Matrix and Tensor Operations tutorial   * Chris Degnen pointed out http://stackoverflow.com/questions/7537401/how-to-insert-a-column-into-a-matrix-the-correct-mathematica-way


Construct matrix B from columns of matrix A?

Starting with Mathematica and working with matrices, I am looking for a way to construct a new matrix B from columns of matrix A. For example, matrix a has 8 columns and 4 rows, I want matrix B to be columns 1,2, 7 and 8. Got this so far:               A12 = A[[All, 1;;2]];     A78 = A[[All, 7;;8]];      ... but have not yet found a way to properly join these two... I did find a way to insert a column in a matrix in the Mathematica documentation, by using a nested Transpose-Insert-Transpose, but did not return the correct new matrix B. Any suggestion is much appreciated. J.


Manipulating lists with constant values

let us assume we have some data in the following form.               Table[data[[1,i,{1,2}]],{i,1,Length[data[[1]]]}]      This would give all $x-y$ pairs of the first file. What I want to do now is to multipliy this table with constant factors but different factors for $x$ and $y$. I found a solution for this with               MapThread[ Composition[Flatten, List], {xlist, #}] & /@ ylist      where `xlist` is                Table[data[[1,i,1]],{i,1,Length[data[[1]]]}]*c1      and `ylist` is                {Flatten[Table[data[[1,i,2]],{i,1,Length[data[[1]]]}]]}*c2      Is there a more comfortable way to do this? Thank you in adavance Sincerely * * * EDIT:                test= {{0.0015856, -1486.76}, {0.00157776, -1483.45}}      I need :                test2= {{1.5856, -148.676}, {1.57776, -148.345}}      So the $x$ values should be multiplied with $1000$ and the $y$ values multiplied with $0.1$ EDIT2: Transpose is exactly what I need, thank you very much


Convenient methods to sum select rows (or cols) of a matrix?

What are some convenient methods to sum selected rows or columns in a matrix? This question Summing along rows or columns of a matrix only addresses how to sun entire rows or columns ie, by level. For example, suppose one wants to add columns 2 and 4 of:               M = Column@Table[RandomInteger[10], {3}, {4}];      Neither MapAt, nor ReplacePart appear useful in this regard. Of course `#[[2]] + #[[4]] & /@ M` works for summing columns and `Transpose` can be used for rows, but that seems like a hack to specify using such syntax. Any better solutions?


How to extract data from a list?

I have a long list of coordinates defined in some 8D space. I need to extract the first three coordinates only. How ? For example :               coords = {{0.1, 0.4, -0.2, 1.2, 3.2, 0.5, 0.8, 2.2}, ...};      I need to define the list of all first three components :               reducedCoords := {{0.1, 0.4, -0.2}, ...}      Please, notice that I'm working with _Mathematica 7_.


Swap elements in list without copy

I have a lists with 100,000 elements and would like two swap to entries without dublicating the list Example:               a = {11,2,7,31};     swap[2,4]; (* how to implement this? *)      a (* should print {11,31,7,2} *)      I can do               swap[i_,j_]:=(a=ReplacePart[a,{i->a[[j]],j->a[[i]]}])      but this copies the list and if there are many swaps this takes way too much time... **Edit:** The important point of my question is how to do it without having Mathematica creating a copy of the list. This is in no way answered by the alleged duplicate.


How to switch elements i,j in a list?

Are there any direct function to switch elements i,j in any list? or is necessary to create one with Do / If ? (I don´t ask for making me this function if it doesn´t exists) My target is can switching positions i,j in {1,4,3,2,5} for example I tell switch(2,5) an obtain {1,5,3,2,4}


List operation on specific elements

Let's consider two tables given by               T1 = Table[{i,j,f1[i,j]},{i,0,2},{j,0,3}];     T2 = Table[{i,j,f2[i,j]},{i,0,2},{j,0,3}];      The functions `f1` and `f2` are expensive to compute, so that I want to compute the tables `T1` and `T2` only one time. I now want to obtain the table `T3` defined as               T3 = Table[{i,j,f1[i,j] f2[i,j]},{i,0,2},{j,0,3}];      However, as I already know `T1` and `T2`, I want to estimate `T3` without any reevaluation of `f1` and `f2`, but using only operations on the already known tables `T1` and `T2`. How would you perform such an operation on the lists ?


Arithmetic operations on columns

I have imported a file, data.txt, then plotted columns 2 and 3 as function of column 1 using the commands below.               data = Import["/home/data.txt", {Data}]          ListlogLogPlot[       Transpose /@ {{data[[All, 1]], data[[All, 2]]}, {data[[All, 1]], data[[All, 3]]}}]      Now I have to add/subtract column 1 and column 2, then plot them together. Please help me to proceed


Column Operation - Subtract part of nested list from part of another nested list

I have two lists with x- and y-coordinates with different z-coordinates of the form               {{x0, y0, z0_1}, {x1, y1, z1_1}, ..., {xn, yn, zn_1}}        and               {{x0, y0, z0_2}, {x1, y1, z1_2}, ..., {xn, yn, zn_2}}.        I want to construct the list > >     {{x0, y0, z0_1 - z0_2}, {x1, y1, z1_1 - z1_2}, ..., {xn, yn, zn_1 - > zn_2}}   >   i.e. construct a list containing the difference of only the z-coordinates, for each x- and y-coordinate. Is it possible to do this with a few simple commands, or should I construct a loop and create a new list from scratch?


Subtracting list from list of same dimensions

This might seem like a basic operation I have already searched for similar answers but found none. I want to subtract the second elements of my list ct from the corresponding element in lt, and letting the first element to remain as they are the same.               lt={{{1, 1}}, {{2, 1}}, {{3, 1}}, {{2, 3}}, {{5, 1}}, {{2, 4}, {3, 2}}, {{7, 1}}, {{2, 7}}};               ct = {{{1, 1}}, {{2, 1}}, {{3, 1}}, {{2, 2}}, {{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}};      as you can see the first elements are the same I want them to remain. desired result               nt={{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5, 0}}, {{2, 3}, {3, 1}}, {{7, 0}}, {{2, 4}}};      also note that my resulting list nt is my list lt with the last previous first element. like element 4 in my nt is just my element 2 in lt. and where the second element is 0 that means there is no previous first element of the same value, that is a next way to look at it.


Efficient priority queues?

I'm trying to figure out how to transfer the concept of a priority queue to the functional world. Searches have turned up some implementations that use Append and other expense list copying techniques. I'm guessing there is a better way. An example of what I am trying to solve is consider the products of all pairs of N digit numbers in descending value order. For small N I can do something like...               Reverse[         Cases[             SortBy[                 Flatten[                     Table[{i, j, i*j}, {i, 1, 9}, {j, 1, 9}],                 1],              Last[#] &],          {i_, j_, k_} /; i <= j]     ]      Alternative solutions to the problem in particular are welcomed, but I am really looking for a generic answer of how to apply the priority queue concept to the functional world.


How do I plot a system with gain, first-order lag and time delay?

I want to plot the output response of a system with gain, first-order lag and time delay, where the transfer function is               tf = 2 Exp[-0.1 s]/(.1 + s)      To plot a time delay, we need to use an approximation, as _Mathematica_ 's `TransferFunctionModel` is restricted to rational transfer functions. We can use a Padé approximation               pa = PadeApproximant[tf, {s, 0, 5}]      and then determine the output response and plot it using               model = TransferFunctionModel[pa, s]     output = OutputResponse[model, UnitStep[t], t];     Plot[output, {t, 0, 10}, PlotRange -> All]      My output response looks very weird: ![time delay plot](http://i.stack.imgur.com/h9f6F.png) Can somebody please explain to me what I'm doing wrong?


Draw generalized k-ellipse using "the locus of points so that sum of the distances to the foci is constant" deffinition

My goal is to draw a family (for different distances) of _3-ellipse_ for equilateral set of foci. _3-ellipse_ definition is: > "the locus of points so that sum of the distances to the three foci is > constant" Eventually I want to generalize this to **k-ellipse**. Thanks for your help I am bloked.


How can I highlight and individually color the connected components of a graph?

I have a graph `G`, and I wish to individually highlight and color the different connected components of a graph. It is simple enough to do this for one component:               HighlightGraph[G, ConnectedComponents[G][[2]]]      But how does one do this for multiple components? I'd ideally like to be able to pass a color string to specify each highlighted component, something like `componentColorString = { Blue, Green, Red,...}`. Is this possible?


Permutations with restrictions

I have a problem that can be modeled as: there are 8 boxes in total, and 60 different items. I want to put all items into boxes (all of them can be put into a single box). Now I want to find: 1) the number of total posssible situations 2) the number of posssible situations when certain number of items are put into certain box (such are 6 different items are put into box #2). **Edit:** I found a somehow similar problem, but I think my data would be too large to enumerate. http://stackoverflow.com/questions/20721161/combinations-between- two-lists


Append CellTag to list of Cells

As suggested in this earlier post, I restate my question here about appending `CellTags` option to existing list of `Cells`. What I have for the moment:               listOef = {};          SelectionMove[this, Before, Notebook];     SelectionMove[this, Next, Cell];     SelectionMove[this, Next, Cell];     Do[      (       SelectionMove[this, Next, CellGroup];       AppendTo[listOef, NotebookRead[this]]       )       , {i, aantalVragen}]      This copies cells I give in the `EvaluationNotebook[]` to the list `listOef`. I now want to write this list to the new notebook `nb` after permuting its elements randomly with               allPermutations = Table[RandomPermutation[aantalVragen], {aantalToetsen}];      like this:                Do[       (NotebookWrite[nb,         Permute[listOef, allPermutations[[toetsNummer]]][[vraagNummer]]];        ),      {vraagNummer, aantalVragen}]      In this `Do[]` command, I would like to add Labels to every cell during the `NotebookWrite` command: its label would be `"vraagNummer"`, the counter which goes from `1` to `aantalVragen`, which is given at the beginning of the document. I'd like to have something like this:               SetOptions[ Cell, CellLabel->"vraag"<>ToString[vraagNummer] ]      but this doesn't seem to work. How can I address the cell which has just been written by `NotebookWrite`? Or how would you suggest to do this using this structure? Thanks for all help!


Algorithm in RandomChoice[{w1,w2,...}->{e1,e2,...},n]?

I wonder if someone happens to know the actual algorithm implemented in the particular overload of `RandomChoice` that handles explicitly presented discrete distributions, namely               RandomChoice[{w1, w2, ...}->{e1, e1, ...}]         gives a pseudorandom choice weighted by the w1.      It's blazing fast, as illustrated in my test notebook here: https://www.dropbox.com/s/rwm80fut60v926b/FastNonUniformPseudoRandoms002.cdf (btw, such things are really useful in, say, particle filters). I know of at least four algorithms for solving this problem. A greedy-space array of outcomes has O(1) time but O(S) space where S is the sum of the frequency counts (and only works when the weights are integers or can be scaled up to integers). Two algorithms explicitly invert the CDF, either by linear search -- O(N) time, O(N) space, or binary search -- O(log N) time, O(N) space. The best I know is Walker's Alias Method http://en.wikipedia.org/wiki/Alias_method which is O(N) space, O(1) time. I implemented this in my notebook and it beats the pants off the others (as expected) but is still 30 times slower than the built-in (though still just O(1)). I wonder if the built-in is just an optimized Walker's or is it something better?


ParallelTable and Precision

I'm using `ParallelTable[]` to calculate a function over a range of my parameters , ($\omega,\ell$). This seems to be working well (in terms of speed increase) except for some strange Precision issues. I set the `$MinPrecision=40` at the start of the notebook as well as my working precision, precision goal and accuracy goal for some computations later in the notebook as                wp=$MinPrecision;      ac=$MinPrecision-8;      pg=wp/2;      The rest of my code basically defines some helper functions before going on to the main function (that I feed into `ParallelTable`). This main function uses the helper functions along with `NDSolve` and `NIntegrate` to do some computations, and it's in these that I feed the `Working Precision->wp` ,`AccuracyGoal->ac`, `PrecisionGoal->pg`. I have used `DistributeDefinitions` on all my variables, helper functions, and the main function, and even on `$MinPrecision`, also all my initial conditions for NDSolve have `N[...,wp]` wrapped around them, but still when I use `ParallelTable[...]` I get errors:                Precision::precsm. Requested precision 39.153977328439204` is smaller than $MinPrecision.       I don't get any such error when I simply use `Do[...]` or `Table[..]` on my main function, and indeed the results differ at the 33rd decimal place, which is the decimal the above number is precision too. I have no idea what this number is unfortunately, it doesn't look like any of my outputs or inputs. I just don't understand how this could not crop up with the non-parallelized forms, but crop up with parallelized? **Minimal Example** This is much simpler than my code, but I think it still captures it and the problem: Definitions:               M = 1;     $MinPrecision = 40;         wp = $MinPrecision;     ac = $MinPrecision - 8;     pg = wp/2;     rinf = 15000;      The main function to be parallelized:               dGenBessE[\[Omega]_?NumericQ, l_?IntegerQ] :=      Block[{\[CapitalPhi]out, init, dinit},          init = 0.00006630728036817007679447778124486601253323 +      6.913102762021489976135937610105907096265*10^-6 I;     dinit = -6.958226432502243329110910813935678705519*10^-7 +      6.631148430876236565520382557577187147081*10^-6 I;            \[CapitalPhi]out[\[Omega], l] = \[CapitalPhi] /.        Block[{$MaxExtraPrecision = 100},            NDSolve[{\[CapitalPhi]''[r] + (2 (r - M))/(                r (r - 2 M)) \[CapitalPhi]'[                 r] + ((\[Omega]^2 r^2)/(r - 2 M)^2 - (l (l + 1))/(                  r (r - 2 M))) \[CapitalPhi][r] ==               0, \[CapitalPhi][rinf] ==               N[init, wp], \[CapitalPhi]'[rinf] ==               N[dinit, wp]}, \[CapitalPhi], {r, 30, 40},             WorkingPrecision -> wp, AccuracyGoal -> ac,             PrecisionGoal -> pg, MaxSteps -> \[Infinity]]][[1]];          Print["For \[Omega]=", \[Omega], " and l=", l, ": "];          Print["Kernel ID: ", $KernelID];      Print["Precision of init: ", Precision[init]];      Print["Precision of dinit: ", Precision[dinit]];      Print["\[CapitalPhi]out at 35=" ,      N[\[CapitalPhi]out[\[Omega], l][35], wp] ];      Print["Precision of \[CapitalPhi]out: ",       Precision[\[CapitalPhi]out[\[Omega], l][35]]];     ]      Do Paralleization prereqs:               LaunchKernels[4]     DistributeDefinitions[M, rinf, wp, ac, pg, $MinPrecision,dGenBessE];      Attempt to run it with Paralleize for two different values:               Parallelize[{dGenBessE[1/10, 0], dGenBessE[1/10, 1]}] // AbsoluteTiming      **Result** For me this leads to a               Precision::precsm: Requested precision 38.95475956978393` is smaller than   $MinPrecision. Using $MinPrecision instead.


Is there are any command to expand quaternion multiplication as below STEP by STEP.   Below is equation from my text.   I'm self learner and for some reason I can't wrap my head around quaternion multiplication.   I really need to see step by step workout.   I remember seeing step by step workout in wolframalpha but that's for calculus integration.   Just wondering if the same can be done in mathematica.   $$ \begin{equation} \begin{split} w =& qvq^* \\\ =& (q_0+\vec{q})(0+\vec{v})(q_0-\vec{q}) \\\ =&(2q_0^2-1)\vec{v}+2(\vec{q}\cdot\vec{v})\vec{q} + 2q_0(\vec{q}\times\vec{v}) \end{split} \end{equation} $$


Why can't I pass in a product of matrices in my modified matrixform?

In attempt to build a function that would work like `MatrixForm` but would wrap a matrix with brackets, I tried the following function:               matrixform[mat_] := TraditionalForm[DisplayForm[RowBox[{     StyleBox["[", SpanMaxSize -> \[Infinity]],      GridBox[mat],       StyleBox["]", SpanMaxSize -> \[Infinity]]}]]]       This does what I want on an ordinary matrix, say `a={{1,2},{3,4}}`, as well as on `2a` and `a+a`. But if I pass in a product such as `a.a` it does not work properly. I have tried wrapping the product in `Evaluate`, and tried executing `a.a` separately and then passing in `%` and this has made no difference. Note that a better function `Composition[bracketF,Grid]` suggested here lacks these issues. So the question is why can we not pass in a product of matrices into `matrixform`? This is my first time working with functions such as `StyleBox, GridBox, RowBox`, etc.


Slider with varying scales

I am trying to implement a slider whose control range varies depending on the current value:               {Dynamic@asd,      Slider[Dynamic[asd],      Dynamic @Which[asd < 10, {1, 10}, asd >= 10 , {9, 50, 1}]]}      However I now have the problem that the slider remains in place once the control scales change and thus the value "leaps" as soon as the scales change. To Illustrate: once i reach ten the scale changes but the slider remains in place and thus the value goes immediately to 50 (the "new" ten). Is it possible to have the slider jump instead of the value? Perhaps by briefly locking the value at ten?


plot Contourplot simple

demElev[path_, samples_] :=       Module[{elevUrl, x, y, markers, dem},        elevURL =         "http://maps.google.com/maps/api/elevation/json?sensor=false"; {x,          y} = path[[1]] - path[[2]];        pnts = Table[         path[[2]] + {i, j}, {i, 0, x, x/samples}, {j, 0, y, y/samples}];        markers =         StringReplace[           ToString[#], {"}, {" -> "|", "{" -> "", "}" -> "",             " " -> ""}] & /@ pnts;        dem = ToExpression@           StringCases[Import[elevURL <> "&locations=" <> #],             NumberString] & /@ markers; Partition[Flatten[dem], 4]]     path = {{41.334387, 104.574955}, {51.02568, 120.563405}}     dem = demElev[path, 120]          ListContourPlot[dem[[All, {3, 2, 1}]],       ContourStyle ->        Directive[GrayLevel[0], Opacity[0.946], AbsoluteThickness[2.5`]],       Contours -> {688, 1101}, PlotLegends -> Automatic,       ContourShading -> None, ColorFunction -> "Thermometer",       Epilog -> {AbsolutePointSize[10]}]      How to draw contour plot not a sharp angle this picture?? 2D![enter image description here](http://i.stack.imgur.com/Owq6o.png) ![enter image description here](http://i.stack.imgur.com/vtCBj.png)


Table with multiple iterators running parallel

I want to use `Table` to generate a list, but it only allows one iterator to increment at a time. So in               Table[i*r, {i, 0, 5}, {r, 0, 5}]      `r` will run `0` through `5` for `i = 0`, then change `i` and run through `r` again etc., giving 36 elements in a 6 x 6 array. But I want a list of only 6 elements, so that `i` and `r` are changed at the same time, in parallel. So it would give `0*0`, then `1*1`, `2*2` etc. Giving the output of:               {0, 1, 4, 9, 16, 25}  (* <-This is what I want. *)      Is this possible with `Table` or anything else? Also I know I could do:               Table[i*i, {i,0,5}]      But this is just an example, and in my project this way won't work. Also if at all possible I would like to use a list for one iterator's values, but this isn't so important.


Solving/Reducing equations in $\mathbb{Z}/p\mathbb{Z}$

I was trying to find all the numbers $n$ for which $2^n=n\mod 10^k$ using _Mathematica_. My first try:               Reduce[2^n == n, n, Modulus -> 100]      However, I receive the following error:               Reduce::nsmet: This system cannot be solved with the methods available to Reduce. >>      using $n^2$ instead of $2^n$ works just fine, where is the problem with $2^n\;$? On top of that, how do I keep the modulus $10^k$ variable and therefore, receive a solution dependent on $k\;$?


Verifying and deriving basic (block) matrix identities

How can I use the new symbolic matrix/tensor capabilities to verify matrix identities, such as ![enter image description here](http://i.stack.imgur.com/rbU71.gif) (1) or ![enter image description here](http://i.stack.imgur.com/YwVpc.gif) (2) Even better, how can I ask Mathematica to derive expressions for X, Y, Z, and U like the ones shown on the RHS of (2) (many equivalent forms exist) (and as a bonus, display them similarly).


Where does Workbench deploy to?

After a few months pause, I am using Workbench again and I cannot determine where is WB sending (deploying) my built package. WB does not ask for a destination folder, so I guess it must use some preference I set before... only I do not remember it! So, can someone please tell me how to find/set the destination folder for deployed applications? (Searching on my HDDs takes a long time.)


Is it safe to assign a variable and function of the same name for different things?

I'm writing out a notebook that goes through the van der Waals Equation of State for gases, and I run into a situation where I want to assign (simplified) Tc[b_]:=5b, use that to solve for b in terms of Tc with               b[Tc_]/.Solve[Tc==Tc[b],b][[1]]      Is it ok to assign Tc[b_] and still use Tc as a variable?   * If it is ok, is it possible to assign Tc[b_] and leave Tc blue instead of black, like other variables? What about assigning Tc[b_] and Tc to different things? How do the mechanics behind assigning things work in Mathematica such that I can assign Tc and not bother Tc[b_]? Here's my full code, it works fine, I'm just wondering down the road if evaluating like this will work in a more complicated situation.               RGas = Quantity["MolarGasConstant"];          Pvan[V_, T_] := (R*T)/(V - b) - a/V^2     Pvan[V_, T_]' := D[Pvan[V, T], V]     Pvan[V_, T_]'' := D[Pvan[V, T]', V]          CriticalValues =        Solve[{Pvan[V, T] == P, Pvan[V, T]' == 0 == Pvan[V, T]''}, {V, T, P}]          Pc[a_, b_] = P /. CriticalValues[[1]]     Vc[a_, b_] = V /. CriticalValues[[1]]     Tc[a_, b_] = T /. CriticalValues[[1]]          Zc[Pc_, Vc_, Tc_] := (Pc[a, b]*Vc[a, b])/(R*Tc[a, b])     Zc[Pc, Vc, Tc]          abCritical = Solve[{Tc == Tc[a, b], Pc == Pc[a, b]}, {a, b}]     a[Tc_, Pc_] = a /. abCritical[[1]] /. R -> RGas;     b[Tc_, Pc_] = b /. abCritical[[1]] /. R -> RGas;     \[Nu]c[Tc_, Pc_] := b[Tc, Pc]/4 /. R -> RGas;     \[Sigma][Tc_, Pc_] := ((3*\[Nu]c[Tc, Pc])/(4*\[Pi]*N₀))^(1/3) /.R -> RGas;          Solve[Eliminate[{P == Pvan[V, T], TR == T/Tc[a, b], VR == V/Vc[a, b],        PR == P/Pc[a, b]}, {P, T, V}], PR] // FullSimplify      It follows the first 3 pages of this.


How to find the maximum of a function on a set of discrete points? For example, what is the best way to find the maximum of               -2 a - 2 b - 2 c - 2 d - 2 e - 2 f + e (-2 + d + f) - 2 g + f (-2 + a + e + g) -       2 h + c (-2 + b + d + h) - 2 i - 2 j + a (-2 + b + f + j) + i (-2 + h + j) +       h (-2 + c + g + i + j) - 2 k + d (-2 + c + e + k) + j (-2 + a + h + i + k) -       2 l + g (-2 + f + h + l) + k (-2 + d + j + l) - 2 m + (-2 + b + l) m + l       (-2 + b + g + k + m) + b (-2 + a + c + l + m)      where $a,b,c,d,e,f,g,h,i,j,k,l, m \in \\{-1,1\\}$? Any help or suggestion will be appreciated!


LogLikelihood function from the Time Series package is apparently missing

The Time Series package for Mathematica comes with a function called `LogLikelihood`. It is discussed and used extensively in the documentation (pdf). So does Mathematica 8. First I though my inability to use `LogLikelihood` was that it was being shadowed by the `LogLikelihood` function in Mathematica itself, but apparently not. Loading the package with               Needs["TimeSeries`TimeSeries`"]      works for every other function, but the only `LogLikelihood`function I have access to is Mathematica's built in one. Trying to refere to it with the full context, like so               TimeSeries`TimeSeries`LogLikelihood      doesn't work either. It is as if this one function simply isn't there. I've also tried re-downloading the package and reinstalling in case I got a corrupt version the first time around, but this hasn't helped. **EDIT:** The way I am calling the function should be correct:               data = TimeSeries[ARModel[{0.5, -0.2}, 1], 20]     (*{0.775171, -0.0377616, -0.568652, 1.56771, 1.32269, -1.60302, \     -1.53275, 0.127154, 1.37393, 0.138493, -0.0484376, -0.506817, \     0.731963, 2.28373, 0.374458, 0.468365, 2.48781, 1.24375, 1.0746, \     -0.401619}*)          LogLikelihood[data, ARModel[{0.5}, 1]]     (*LogLikelihood[{0.775171, -0.0377616, -0.568652, 1.56771,        1.32269, -1.60302, -1.53275, 0.127154, 1.37393,        0.138493, -0.0484376, -0.506817, 0.731963, 2.28373, 0.374458,        0.468365, 2.48781, 1.24375, 1.0746, -0.401619}, ARModel[{0.5}, 1]]*)      **EDIT2:** Using full context in calling the function has the same result:               TimeSeries`TimeSeries`LogLikelihood[data, ARModel[{0.5}, 1]]     (*LogLikelihood[{0.775171, -0.0377616, -0.568652, 1.56771,        1.32269, -1.60302, -1.53275, 0.127154, 1.37393,        0.138493, -0.0484376, -0.506817, 0.731963, 2.28373, 0.374458,        0.468365, 2.48781, 1.24375, 1.0746, -0.401619}, ARModel[{0.5}, 1]]*)      **EDIT3:** This is the context path:               $ContextPath     (*{"TimeSeries`TimeSeries`", "PacletManager`", "WebServices`", \     "System`", "Global`"}*)


Animation: presenting events that persist in time

I have a list of events that occurred on specific moments in time. In the example below, the three events occurred at 23:09, 23:13 and 23:17. I was able to build an animation that flows from time 23:00 to 0:00 and shows at the right time the event by plotting a disc of a specified magnitude at the specified coordinates.               data = {{{2012, 3, 19, 23, 9}, 44.891, 12.202, 2.6, 2.5,         3541187340}, {{2012, 3, 19, 23, 13}, 44.898, 11.258, 6.2, 4.1,         3541187580}, {{2012, 3, 19, 23, 17}, 44.186, 11.496, 4.2, 2.2,         3541187820}};      Each event is specified by its time of occurrence, x and y coordinates, magnitude 1, magnitude 2, absolute time. First, I specified the start and end time of the animation in absolute time and build a list of times from start to end in steps of one minute:               start = AbsoluteTime[{2012, 3, 19, 23, 0, 0}];     end = AbsoluteTime[{2012, 3, 20, 0, 0, 0}];     time = Table[start + 60*i, {i, 0, (end - start)/60}];      For my convenience I reshuffled my data:               d3 = Table[{data[[i, 6]], data[[i, 2]], data[[i, 3]], data[[i, 4]],         data[[i, 5]]}, {i, Length[data]}];      and checked which values in the 'time' list are taken by the time of my events:               doubles =       Flatten[Table[Position[time, d3[[All, 1]][[i]]], {i, Length[d3]}]];      Lastly, I inserted my events in the 'time' list:               d4 = ReplacePart[time,         Table[doubles[[i]] -> d3[[i]], {i, Length[d3]}]];      I can then generate my frames:               frames = Animate[If[Length[d4[[i]]] > 1,       Graphics[{         White,         Rectangle[{10, 43}, {13, 46}],         Red, Disk[d4[[i, {3, 2}]], d4[[i, 5]]/10],         Black,          Text[Style[           DateString[            DateList[d4[[i, 1]]], {"Day", " ", "MonthNameShort", " ",              "Year", "   ", "Hour", ":", "Minute"}],            FontFamily -> "Helvetica", FontSize -> 20], {10.8, 45.85}]         }],       Graphics[{         White,         Rectangle[{10, 43}, {13, 46}],         Black,          Text[Style[           DateString[            DateList[d4[[i]]], {"Day", " ", "MonthNameShort", " ", "Year",              "   ", "Hour", ":", "Minute"}], FontFamily -> "Helvetica",            FontSize -> 20], {10.8, 45.85}]         }]       ], {i, Range[Length[d4]]}, AnimationRate -> 20];          Export["animation.gif", frames, "DisplayDurations" -> .03]      ![enter image description here](http://i.stack.imgur.com/ny6yA.gif) However, what I would like to achieve is a more complicated animation: once an event is plotted at the right time I would like to then present it also on subsequent frames, but slowly dimming (decreasing Opacity) for a specified time window. At the end of the animation all events would be thus dimmed and superimposed. I simplified a lot the example I provided, real data might span over several days and contain hundreds of events.


How do I prevent fonts sizes and line weights from scaling in exported graphics?

It's common to export graphics from _Mathematica_ that are subsequently scaled to various sizes that cannot (at least not conveniently) be anticipated. This is problematic in cases where (as is common) fonts and line weights need to fixed (e.g. throughout a document or presentation, or simply to prevent a figure from looking ridiculous). For example, if the default options for fonts and line weights are satisfactory, then               Plot[{Sin[x], Cos[5 x]}, {x, 0, 2 Pi}]      will produce a figure with correct font sizes an line weights ![enter image description here](http://i.stack.imgur.com/OAfFJ.png) and scaling this figure within _Mathematica_ (e.g. by dragging the resize frame) will preserve these font sizes and line weights: ![enter image description here](http://i.stack.imgur.com/f4hTI.png) However, if I export the original graphic in a resizable format (i.e., choosing "Save Graphic As..." and specifying a PDF "Vector Representation", which, as far as I can tell, is the only form suitable for subsequent resizing), the fonts and line weights scale with the graphic ![enter image description here](http://i.stack.imgur.com/5lfdw.png) which is not the desired result. Is there a way to generate and export graphics so that font sizes and line weights are preserved when the exported graphic is resized?


What are the Slot Names in a Dataset?

I have a dataset which are keyed on `{"Item", "Hour of Day", "Value"}.` In the examples, I noticed that it is possible to apply functions using such as               Select[(#a > 1 &)]      But what would the slot name be for my string values above? Is there a way to interrogate a dataset for its slots? Should I simply avoid the issue and rename them if I wish to perform such operations?


Nested list in PairedBarChart

I have a dataset consisting of 2 different parameters (`x` and `y`), that are evaluated for 3 different values of parameter `p` and within a set for `p`, there are, say, two groups (`G1` and `G2`, eventually to `Gn`) with again three values for a parameter q. `G1`, `G2` need to be displayed with the same `ColorFunction`. How do I display this using `PairedBarChart`? I believe this is a nested list, but `PairedBarChart` only seems to take two (`x` and `y`) _m-by-n_ (max number of dimensions = 2) matrices? Appreciate your hints! UPDATE: SAMPLE DATA BELOW and extra level added in description above. Data should be interpreted as data left = x, dataright = y. In both, there is three groups p1, p2, p3 each consisting of two lists (G1 and G2), which in turn each consist of {q1,q2,q3}.               dataleft = {{{22.1801, 30.9241, 27.3873}, {30.0898, 42.7793, 38.6847}, {81.5488, 164.131, 97.6132}}, {{28.5354, 30.1192, 26.7762}, {26.7111,27.5938, 25.8865}, {72.1467,91.9632, 53.7431}}};     dataright (*here identical to left, just for the idea*) = {{{22.1801, 30.9241, 27.3873},{30.0898, 42.7793, 38.6847}, {81.5488,164.131, 97.6132}}, {{28.5354, 30.1192, 26.7762}, {26.7111, 27.5938, 25.8865}, {72.1467, 91.9632, 53.7431}}};


Numerical Optimization Methods

I am curious if any one has comments on "specific characteristics" of a problem that will deem it to be best solved by a specific optimization method such as `SimulatedAnnealing`, `Random Search`, or `Diferential Evolution`, etc. **Edit** : I am familiar with the majority of the `Mathematica` resources which has some useful comments such as:`Random search` requires that the objective function be locally continuous, `DifferentialEvolution` is more suitable for discrete optimization problems since it needs a large gene pool, etc. I wanted a discussion expanding that knowledge based on peoples' experience on when they found one method to be more beneficial than other based on the problem characteristics such as size of solution space, non- linearity, processing speed(time), rate of convergence (iterations), etc. Ps. Thanks for the resources.


How can I get the number of slots in Function?

Suppose that I define               f = Function[#1 + #2];      And I want to define a new function, `argsNum`, so that it returns a number of arguments of input function:               argsNum[f]      > >     2 >   since `f` has 2 slots, `#1` and `#2`. I found the good Q&A, Function that counts the number of arguments of other functions but it does not work on functions of form like `Function[#1 + #2]` or etc. It works on `Function[{x, y}, x + y]`. But I need a function that works on slots. How can I modify the function in above link or define a new function which also works on slots?


Simplification of (Co)sine of a sum

I have a huge expression with (Co)Sine of a sum like Cos[[Theta] - 2 [Phi]] (after using \Simplify). I wanted to know if it exists a function which forces Mathematica to express the result in terms of multiplication of (Co)Sine instead of (Co)Sine of a sum ?


Why doesn't Mathematica use uniform criteria for validating Options?

Plot[Sin[x], {x, 0, 1}, pp -> 0]      Gives as expected: > Plot::optx: Unknown option pp in Plot[Sin[x],{x,0,1},pp->0]. >> However:               Import["http://i.stack.imgur.com/JrxBD.png", pp -> "HSB"]      returns no error. Is there a language design reason for this, or is it just lack of standards?


How to programattically create a hyperlink to a local html file?

I want to cause a button to open a local html file using the default web browser. When I use:               Hyperlink["Play","myfile.html"]      Clicking on the link opens the html file in a notebook. If I use               Hyperlink["Play","http://myfile.html"]      My browser (FireFox) opens and fails looking for "www.myfile.html". I know this may be trivial but can anyone help with this?


Quit Kernel Shortcut

How could I set a Keyboard shortcut for the Quit Kernel -> Local command? I find really disappointing to open the Evaluation menu any time!


How can I get better tick spacing for multiple ListLogPlots?

I am using `Show` with `PlotRange -> All` to overplot multiple `ListLogLogPlot`. The resulting plot has axis ticks that are unevenly clustered toward the top of the y-axis. (right image) When I use `Show` with `PlotRange -> All` to overplot the same data using `ListPlot`, the resulting plot has evenly spaced ticks along the y-axis (left image). ![enter image description here](http://i.stack.imgur.com/XocXU.png) How can I use `Show` with `PlotRange -> All` to overplot `ListLogLogPlot` and get even axis ticks along the y-axis? I can force a fix by specifying the entire range with `PlotRange` in the first plot, but in general I will not know ahead of time the plot ranges and would like to avoid editing the plots themselves.


Blank Output for Text Recognition

Please Anyone help Why am I getting Blank Output for TextRecognization for the this Image Is it because the size of image.??? Please help Neither am getting output for this code               x = Import["http://i.stack.imgur.com/RbqrD.jpg"];     TextRecognize[x]      Nor for this one:               x = Import["http://i.stack.imgur.com/RbqrD.jpg"];     img = ImagePartition[x, {50, 69}];     MatrixForm[img];     p=img[[4,1]];     TextRecognize[p]      ![enter image description here](http://i.stack.imgur.com/RbqrD.jpg)


How can I fill in a matrix at every iteration of a Do loop?

I have a matrix whose dimensions are 26x26x3. For my assignment I have written a program which is using a `Do` loop (maxx=maxy=10,maxz=2):                Do[       n = 0;       h=0.4;       k = Table[              If[a <= #1 <= a + h && b <= #2 <= b + h && c <= #3 <= c + h & @@ pts[[w, t]], 1, 0],               {w, 1, Length[pts]},               {t, 1, Length[pts[[w]]]}           ];       pls = Plus @@@ k;       For[i = 1, i <= Length[pls], i++, If[pls[[i]] > 0, n++]];       n,        {a, 1, maxx, h}, {b, 1, maxy, h}, {c, 1, maxz, h}     ]      At every iteration I get a new value for n and I have to assign it to the correct position of my matrix as efficiently and fast as possible. I don't have a counter. So, I am a bit confused. How can I solve this issue? On the other hand, can I create a matrix by saving n at the end of the `Do` loop? Any help is appreciated.


Wavelength, wavenumber, energy and frequency in a ruler

I would like to generate set of four axis relating wavelength, wavenumber, energy and frequency in an arbitrary range. Like in this image but without the labels such as "RADAR". ![example of ruler](http://i.stack.imgur.com/pd0oF.gif) The selection of the nice numbers could be done similar to plots with two x-axis with different units but without an ordinate "y axis".               range = {Quantity[0.1, "THz"], Quantity[10, "THz"]};     ticksmeV = FindDivisions[QuantityMagnitude@UnitConvert[Quantity["Planck's constant"] #, "meV"] & /@ range, 10]      > {0, 5, 10, 15, 20, 25, 30, 35, 40, 45} and so on. But I'm not clear how to put this in a graphic with correct scaling. What would be the best way to do this both in linear and logarithmic scaling? **Edit** Based in the answer by @ubpdqn I have done this:               rangeTHz = Quantity[{0.1,10}, "THz"];     rangemeV = UnitConvert[Quantity["Planck's constant"] #, "meV"] & /@ rangeTHz;     range\[Lambda] =  N@UnitConvert[Quantity["Speed of Light"]/#, "micrometer"] & /@ rangeTHz     rangeWn = N@UnitConvert[#/Quantity["Speed of Light"], "Wavenumbers"] & /@ rangeTHz     TableForm@Table[HorizontalGauge[Null, k, GaugeFrameStyle -> Transparent,  ScalePadding -> {0, 0}, ScaleDivisions -> 10, GaugeMarkers -> None, GaugeLabels -> Placed[QuantityUnit@First@k, Top], ImageSize -> 600, GaugeFaceStyle -> Transparent, LabelStyle -> 16,  AspectRatio -> 1/15], {k, {rangeTHz, rangemeV, range\[Lambda],      rangeWn}}]      > ![Mathematica graphics](http://i.stack.imgur.com/syGMH.png) but the problem is that the Wavelength scaling should be inverted. How can I fix that?


Preparing 2d plots for publication

When it comes to plotting a data my general attitude is to avoid post processing (say with adobe illustrator) as much as possible. To follow this strategy I would like to prepare **publication-ready** pdf plots with _Mathematica_. Here are my requirements   * Plotted lines should have width of **exactly 1pt**.    * The same should be true for the lines forming axes, frames, ticks.    * The ticks have a commensurate length. I find it is optically pleasing to have **major ticks of 4pt** lengths.   * The graph should have a dimension of one column, i.e. ~ **8.5cm** or 240pt.   * All the tick labels, axes labels, etc. should be done with **12pt Helvetica**.   * No white background. One can argue about the art value of this setup. I, personally, find it is a good compromise between the visibility and simplicity. I remember these numbers and keep them the same across different programs and publications. I tried to develop very easy solution that can be kept in mind. Since there is a known problem with tick length (it cannon be set explicitly) I decided to adjust the rest of parameters to this dimension. At first step I am just plotting the function               fx[x_] := 1/(Exp[-x - 7] + 1) + 1/(Exp[x - 7] + 1) - 1      with default settings and nice blue-apple color               blue = RGBColor[17.6/100, 41.6/100, 63.1/100];     u = Plot[fx[x], {x, -15, 15},            PlotRange -> All, AxesLabel -> {"x", "fx(x)"},            PlotStyle -> Directive[AbsoluteThickness[0.5], blue]]      The absolute thickness was set to 0.5pt because I am going to enlarge the graph on the second step:               Show[u,        AxesStyle -> Directive[AbsoluteThickness[0.5], 6, FontFamily -> "Helvetica"],        ImageSize -> 120]     Export[FileNameJoin[{$UserDocumentsDirectory, "u1.pdf"}], %]      As you see the graph has now the horizontal dimension of 120pt, i.e. 50% of the desired result. But I tolerate this since it is a vector graphics. All lines have the right thickness of 50%$\times$1pt=0.5pt and major ticks are of 50%$\times$4pt=2pt. The font sizes are also right: 50%$\times$12pt=6pt. The only problem in present approach is wrong placement of some tick labels. Numbers -10 and 10 are vertically misaligned: ![enter image description here](http://i.stack.imgur.com/ti7op.png) I would appreciate any help on this particular issue, or, on the production of publication ready graphs in general. I explicitly decline possibilities of drawing ticks manually, using additional packages or post processing. **Please, feel free to criticise my artistic style.** **Update** I would like to make some comments on my approach. The whole idea comes from the fact that it is unacceptable for me to use additional packages for very simple plots. At the same time I have **very modest requirements** on graphics parameters for visual appeal. Crucial parameters for me are the lines' thickness and the ticks' length. Since there is no simple way to set the ticks' length explicitly I am forced to rescale the image. That is, the image of 240pt is required, however, it is prepared at 120pt. Everything would be perfect provided ticks' labels are properly placed.


Saving a notebook without output lines

Is it possible to change the way Mathematica saves so that `Out[]` lines are never included? I have a `.nb` file that processes a lot of data, and displays most of it as standard output. These graphs, tables, and intensity plots almost double the size of the file. I'd like to easily save these files in a smaller form and also prevent accidentally sending confidential results to users outside my company or not under an NDA. That is, of course, without using `Cell -> Delete All Output` before each save. I can't be expected to remember to do that all the time! :-P


How to sort cells in a notebook based on cell tags?

Suppose I have a notebook with cells tagged with both numbers and words with numbers always list first, and some cells without cell tags e.g.:               Notebook[{     Cell[ ..., CellTags->{"1","cat"}],     Cell[ ..., CellTags->{"2","dog"}],     ...     Cell[ ...],     Cell[ ..., CellTags->{"7","cow"}],     ...     }, notebook options ...]      What is the easiest way to sort the cells based on 1) cell tag numbers, i.e. the first element in the cell tag list; and 2) cell tag words, i.e. the second element in the cell tag list? Note that there could be additional tags but the first and second tags are always number and single word. Note also there there is unlikely to be grouped cells (none at this stage), although a solution that took cell grouping into account and rendered a sorted ungrouped answer would be fine. I want a fast way to sort a notebook and render the newly sorted form. I'm thinking ideally I'd like a palette button for this.


How to sort Table/Matrix including legend(Labellings)

I want to sort table including its legend for graph I have table similar to               M1   M2   M3      1     5    2     3     1    4      4     2   -10     5     7    11     6    -2    1      I want the labellings `M1`, `M2` and `M3` to move with the first row of numbers while sorting by row basis.                   M1   M3   M2          1     2    5         ...........          ...........      OK The code is below               (* Initial matrix *)     h = {{M1, M2, M3}, {1, 5, 2}, {3, 1, 4}, {4, 2, -10}, {7, 5, 11}, {6, -2, 1}}      then sorting by basis `h1 = Sort /@ h` gives                M1,   M2,  M3      1,    2,  5      1,    3,  4      -10,  2,  4      5,    7,  11      -2,   1,  6      I want `M1`, `M2` and `M3` to be together with the fist row of numerical values since they are labellings attached to the first numerical values of each column AS               M1   M3   M2      1     2    5      ..... .... In that way it will be easy to put the legend in graphs


Ploting a 3D vector field using Manipulate, VectorPlot3D and NDSolve

My aim is to plot a vector field of the following system with a few trajectories: $$r'(t)=i-l.r(t)-\text{ux}. r(t). x(t)-\text{uy}. r(t). y(t) \\\ x'(t)=\text{ex}. \text{ux}. r(t). x(t)-\text{mx}. x(t)\\\y'(t)=\text{ey}.\text{uy}. r(t). y(t)-\text{my}. y(t)$$ $i,l,ux,uy,mx,my,ex,ey$ are parameters. Here is what I have managed to do so far:               Manipulate[       ParametricPlot3D[         Evaluate[           {r[t], x[t], y[t]} /.              NDSolve[{               r'[t] == i - l*r[t] - ux*r[t]*x[t] - uy*r[t]*y[t],                x'[t] == -mx*x[t] + ex*ux*r[t]*x[t],                y'[t] == -my*y[t] + ey*uy*r[t]*y[t],                r[0] == 1, x[0] == 1, y[0] == 1},                {r, x, y}, {t, 0, 100000},                MaxSteps -> Infinity,                AccuracyGoal -> 10]],          {t, 0, 10000},          PlotRange -> Full,          AxesLabel -> {"r(t)", "x(t)", "y(t)"},          PlotStyle -> {Green, Thickness[0.01]}],        {i, 0, 100},        {l, 0, 1},        {ux, 0, 1},        {uy, 0, 1},        {mx, 0, 1},        {my, 0, 1},        {ex, 0, 1},        {ey, 0, 1}]      This plot one trajectory and it works fine (although you might not think so looking at it but it is due to the equations. Then when I tried to plot the vector field alone and I got stuck.I do not know what is going wrong:               Manipulate[       VectorPlot3D[         Evaluate[           {r[t], x[t], y[t]} /.              NDSolve[{               r'[t] == i - l*r[t] - ux*r[t]*x[t] - uy*r[t]*y[t],                x'[t] == -mx*x[t] + ex*ux*r[t]*x[t],                y'[t] == -my*y[t] + ey*uy*r[t]*y[t],                r[0] == 1, x[0] == 1, y[0] == 1},                {r, x, y}, {t, 0, 100000},                MaxSteps -> Infinity,                AccuracyGoal -> 10]],          {r[t], 0, 100}, {x[t], 0, 100}, {y[t], 0, 100},          VectorColorFunction -> "DeepSeaColors"],        {i, 0, 100},        {l, 0, 1},        {ux, 0, 1},        {uy, 0, 1},        {mx, 0, 1},        {my, 0, 1},        {ex, 0, 1},        {ey, 0, 1}]      The next thing to do was to plot both the vector field and trajectories on the same plot, I have not tried as I could manage to plot the vector field, so if you can give me any piece of advice about this too, I would be extremely grateul. For 2D, without using `Manipulate`, I used `Show` but I guess it will not work if I use `Manipulate` as I need to make the parameters vary simultaneously for the vector field and the trajectories. (Do not expect any fancy trajectories with these equations, you can change them to have nicer things, I just would like the general way how plotting this for any system of three equations). EDIT: THE TWO ANSWERS BELOW GIVE DIFFERENT THINGS SO I DO NOT KNOW WHAT TO DO.


Speeding up export of a matrix to a dat file

I'm trying to export a 1000*100 matrix of numbers to a `.dat` file using `Export` (I want the numbers to be separated by a tab) and it's very slow, it takes several minutes, whereas when I export to an Excel file it takes a few seconds. Is there a way to speed this up ? Also how can I control the number of decimals I want to export ? **Edit**   I found the issue, this happens when I export my dat file on a network drive (at work), the export to an Excel file and a dat file must be implemented in different ways that produce different behaviours. Thank you though for the different interesting answers.


String replacement of special characters

The function               StringReplace["y\\/G", {"|<" -> "K", "\/" -> "V", "]" -> "J",        "><" -> "X", "_" -> "", "." -> "", "," -> "", "'" -> ""}]      fails to provide the expected answer `"y\VG"` and instead returns `"y\/G"` due to the unusual (to me) way Mathematica handles strings in order to allow for symbols and images in strings. How would one do a string replace where the symbols are literally replaced, in the order the string is shown?