Workflow in the Mathematica and Workbench IDE

After visiting one of the Wolfram presentations, I started writing code for my number theory research project in Mathematica because I found it to be faster than Sage. I downloaded Workbench and Mathematica, watched the video tutorials on the Wolfram website and read the tutorials in the manual. Then I started coding. After being at it for a week, I find the whole experience to be extremely clumsy as I can not figure out any reasonable workflow. What I do now is this: I open Workbench which in turn starts Mathematica notebook. I write a procedure spread over multiple cells in the notebook. When I am happy with the result, I copy the code into the workbench .m file where I make it into a function. Afterwards, I start using the function in the notebook to do my calculations or to use it in other procedures. I am very happy with the control I have over each step in the notebook and coding in workbench feels quite smooth. What really bugs me is the transition between the two. I just can not figure out how to achieve the smooth workflow I am used from IDEs like IntelijIdea in Workbench. Truth is, when I was downloading Workbench, I was expecting it to replace the notebook environment of Mathematica with more serious IDE. Yet it just launches Mathematica and the notebook each time I run the project anyway. So my question is this: What is the proper way to use Workbench to write code? Or is it just my inexperience that makes me think I am doing something wrong? The closest question I found was this: Working in a team in Workbench which talks mainly about version control (which I wanna look at in the next step as git does not seem to cut it). Links to articles or tutorials describing proper workflow in Workbench would be much appreciated as well.


How can I get Mathematica to simplify my expression?

4.`*^-12 Sqrt[3.0254210421890627`*^22 - 6.25`*^22 T6^2]      The above expression is equal to               Sqrt[0.48406736675024997` - T6^2]      How can I tell _Mathematica_ to simplify the first form into the second form?


How to embed a Mathematica demonstration in Google sites?

I want to have students submit articles that include Mathematica demonstration projects in a document that is on Google sites. I am having problems with embedding the JS code. Could you provide step-by-step instructions. Not sure of the tag for this question.


How to specify default style in Mathematica 9

In _Mathematica_ 8, I can use `GraphicsBoxOptions->{DefaultBaseStyle->{"Graphics", FontFamily -> "Helvetica", FontSize -> 14}}` to specify the default font for graphics. But this does not work for _Mathematica_ 9. How to specify the default style in _Mathematica_ 9 then? Using `BaseStyle` may be a solution. But it is not generalizable to other default styles like `DefaultAxesStyle`, `DefaultFrameStyle` etc. Originally `DefaultAxesStyle->{"GraphicsAxes", FontSize -> 12}` works in _Mathematica_ 8, but it runs into error in _Mathematica_ 9 (message: `The specified setting for the option GraphicsBoxOptions, DefaultAxesStyle cannot be used`). Does anyone know about the style specification grammar in _Mathematica_ 9?


Why can't an `Import[]` change $Path?

Does anyone know why `Import["http://**server**/file.m"]` can't make a change to `$Path`? It seems like `file.m` can set pretty much any other variable, but not `$Path`. I suspect `Get[]` would work, but I can't seem to get `Get[]` to fetch files over the web.


How to use Map inside MapThread?

Given this input               lst1 = {{a, b, c}, {d, e, f}};     lst2 = {1, 2};      and the goal is to generate this output               {  {{1, a}, {1, b}, {1, c}},         {{2, d}, {2, e}, {2, f}}     }      Perfect candidate for MapThread So I made this diagram first to figure what the function I want to map should be ![enter image description here](http://i.stack.imgur.com/IsGuG.png) So the function to use inside `MapThread`, needs to also use `Map` itself (in order to map each item into the other list). So I came up with this:               lst1 = {{a, b, c}, {d, e, f}};     lst2 = {1, 2};     foo[i_, lst_List] := List[i, #] & /@ lst     MapThread[foo[#1, #2] &, {Range[Length@lst2], lst1}]     (*  {  {{1,a}, {1,b}, {1,c}},       {{2,d}, {2,e}, {2,f}}   }  *)      _Now here is the question_ : Is there a way to do the above without having to define an explicit function but using pure function inside `MapThread`? I was getting conflict with `#` mapping. This is sort of the thing I was trying to do, but can't get the syntax right               (*invalid, for illustration only *)     MapThread[       Function[{idx, lst},List[idx, #] & /@ lst] &  ?? ??    ,{Range[Length@lst2],lst1}]      Or if you know of a better approach to do this, that will be fine as well.


Problem overloading D[] using UpValues

First I define an entry of `UpValues` overloading `D[]` for expressions with head `ftest`:               ftest /: D[ftest[aaa_, bbb_], r] := ftest[D[aaa, r], D[bbb, r]]      When I try:               D[ftest[r, r^2], r]      the result is as I expect it to be: > ftest[1, 2 r] However, when I try:               D[(r + ftest[r, r^2]), r]      Mathematica gives not the result I expect: > 1 + 2*r*Derivative[0, 1][ftest][r, r^2] + Derivative[1, 0][ftest][r, r^2] **edit** The result I expect is: > 1 + ftest[1, 2 r] (this clarification was suggested by Mr.Wizard, thanks!) **end edit** **How should I understand this?** **How can this be fixed?** * * * I tried               TreeForm@Unevaluated@Unevaluated@D[(r + ftest[r, r^2]), r]      and understand the result: ![img_1 for question on overloading D\[\] ](http://i.stack.imgur.com/SVA0m.jpg) I also tried               TreeForm@Unevaluated@Unevaluated@D[(r + ftest[r, r^2]), r]      and I don't understand what does Mathematica do in the meantime to produce this result: ![img_2 for question on overloading D\[\] ](http://i.stack.imgur.com/tiXSX.jpg)


Graph two interpolations together

I have created two functions, `inter1=Interpolation[points1]` and `inter2=Interpolation[points2]`. This creates two functions, I then created a graph `Manipulate[ListLinePlot[inter1, InterpolationOrder -> n],{n, 0, 6, 1}]`. However I need to combine these functions together. I want to be able to graph each function together and manipulate each function separately based on `InterpolationOrder`. Can someone please help? This is how far I've come               points = {{1,79},{2,181},{3,181},{4,52},{5,49},{6,8},{7,137},{8,79},{9,112},{10,164}};     inter1 = Interpolation[points];     inter2 = Interpolation[points];     Manipulate[ListLinePlot[inter1, InterpolationOrder -> n], {n,0,6,1}]      Regards New to Mathematica


Grain(Particle) Size Distribution (PSD) Analysis with Mathematica

I would like to do an analysis of the grain size distribution of a Monte Carlo Grain Growth simulation I implemented based on the nice example by Rituraj Nandan (see Link). The result of this calculation is a 2D integer matrix, where every point represents a certain grain orientation. Thus a cluster of similiar values represents a grain. Converting this information into a graphical representation by assigning a similiar color to every similiar integer gives an image which shows the grain distribution of the simulation clearly. Here is an example of such an simulation result (I converted the initial implementation in Java into Mathematica syntax): ![enter image description here](http://i.stack.imgur.com/USIZQ.png) The code used for generating this image is as follows (see above link to the java implementation for the details of the physics behind it):               meshgen[xmax_:0.01,ymax:0.01,nx_:60,ny_:60]:=Module[{hx,hy},     hx=xmax/nx;     hy=ymax/ny;     Return[{{xmax,ymax},{nx,ny},{hx,hy},{Table[i hx,{i,0,nx-1}],Table[j hy,{j,0,ny-1}]}}];     ];          temperature[mesh_,torch_,vel_]:=Module[{x,y,xc,yc,nx,ny,rad,al,t,     q0=500(*net power*),     d=0.002(*thickness of plate*),     \[Rho]=7800(*density*),     cp=600(*specifc heat capacity*),     k=45(*thermal conductivity*),     t0=298.0(*Initial temperature*)},(*quasi-steady thermal profile*)     al=k/(\[Rho] cp);(*thermal diffusivity*)      {nx,ny}=mesh[[2]];     {x,y}=mesh[[-1]];     {xc,yc}=torch;     rad=Outer[Norm[{#1,#2}]&,x-xc,y-yc];     t=Table[t0+q0/(d 2 \[Pi] k) E^(-(1/2)vel (x[[i]]-xc)/al) BesselK[0,1/2 vel rad[[i,j]]/al],{j,1,ny},{i,1,nx}];     Return[t];     ];          tmc[mesh_,t_,vel_]:=Module[     {K1=1.01,(*Model constant*)     n1=0.42,(*Model constant*)     A=1,(*Accommodation probability*)     \[CapitalNu]=1.53 10^19,(*Average number of atoms per unit area at the grain boundary in #/m\.b2*)     Na=6.022 10^23,(*Avogadro's number*)     Vm=7.11 10^-6, (* ??? *)     h=6.62 10^-34(*Planck's constant m\.b2kg/s*),     R=8.314, (*Gas Constant J/molK*)     \[CapitalDelta]Sf=9.48, (*Activation entropy of grain boundary migration J/molK*)     Q=93400, (*Activation enthalpy for grain boundary migration in J/mol*)     \[Gamma]=1.77, (*Grain boundary energy J/m\.b2*)     \[Lambda], (*Grid Size*)     L0,  (*Initial Grain Size*)     dt,time,expt,C1,x,nx},(*monte-carlo time at each location (i,j)*)     x=mesh[[-1,1]];     nx=mesh[[2,1]];     \[Lambda]=mesh[[3,1]];     L0=mesh[[3,1]];     C1=(4 \[Gamma] A \[CapitalNu] Vm^2)/(Na^2 h) E^(\[CapitalDelta]Sf/R);     time=x/vel;     dt=Append[Differences[time],time[[-1]]];     expt=Table[Exp[-Q/(R*t[[;;,i]])]*dt[[i]],{i,1,nx}];     expt=Reverse[Accumulate[Reverse[expt]]];     Return[(Sqrt[C1 expt+L0^2]/(K1 \[Lambda])-1/K1)^(1/n1)];     ];          energypart[indx_,{nx_,ny_},reflect_:True]:=     Module[{ii,jj,it,ib,jl,jr},(*get part specification of nearest neighbours of location (ii,jj). If reflect is set True then at the array boundary reflecting boundary conditions are assumed. Otherwise periodic boundary conditions are used*)     ii=indx[[1]];jj=indx[[2]];     (*rows of top and bottom neighbours*)     it=If[reflect,If[ii==1,1,ii-1],If[ii==1,ny,ii-1]];     ib=If[reflect,If[ii==ny,ny,ii+1],If[ii==ny,1,ii+1]];     (*rows of left and right neighbours*)     (*rows of top and bottom neighbours*)     jl=If[reflect,If[jj==1,1,jj-1],If[jj==1,nx,jj-1]];     jr=If[reflect,If[jj==nx,nx,jj+1],If[jj==nx,1,jj+1]];     {it;;ib,jl;;jr}     ];          pottsenergy[osub_]:=Total[Map[1-KroneckerDelta[#,osub[[2,2]]]&,osub,{2}],2];(*Potts-Function of 3x3 Array with relevant grain in the center at {2,2}. The total of this array gives the Energy of the grain at {2,2}*)          energy[o_,indx_,nmax_,reflect_:True]:=pottsenergy[o[[Sequence@@energypart[indx,nmax,reflect]]]];(*Select relevant block with center element and all neighbours and apply Potts-Function to it. The result of this function gives the Energy of the grain at position indx*)          RemoveNoise[frame_,limit_:2]:=Module[{emap,nx,ny,result,i},     {nx,ny}=Dimensions[frame];(*Set all grain size orientations for grains which just consist of one or two pixels (set by limit) (E=8) equal to -1 (with the color function defined below they will be set to black*)     emap=MapIndexed[energy[frame,#2,{nx,ny}]&,frame,{2}];     i=5;     emap[[1,;;]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[1,;;]],limit];(*Correct for lower number of neighbours at boundaries*)     i=5;     emap[[nx,;;]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[nx,;;]],limit];     i=5;     emap[[;;,ny]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[;;,ny]],limit];     i=5;     emap[[;;,1]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[;;,1]],limit];     i=8;     result=Nest[ReplacePart[#,Position[emap,i--]->-1]&,frame,limit];     Return[result];     ];          grainsize[mesh_,o_]:=Module[{dist=Table[0,{10}],avg,size,sum=0,num=0,nx,ny,hx,hy,i,j,k,xmax,ymax},(*measurement of grain size distribution and average grain size*)     {xmax,ymax}=mesh[[1]];     {nx,ny}=mesh[[2]];     {hx,hy}=mesh[[3]];     For[i=1,i<=nx,i+=5,(*measurement of average grain size using mean lineal intercept method*)     For[j=1,j<=ny,j++,     If[o[[i,j]]!=o[[i,Mod[j+ny-1,ny,1]]],(*periodic boundary*)     num+=1     ];     ]     ];     avg=nx ymax/num;(*average grain size*)     For[i=1,i<=nx,i++,(*grain size distribution*)     For[j=1,j<=ny,j++,     If[o[[i,j]]==o[[i,Mod[j+ny-1,ny,1]]],     sum+=1     ,     size=sum hy/avg;     sum=0;     For[k=0,k<10,k++,     If[(size<If[k<9,k+1,1000]/2)&&size>=k/2,dist[[k+1]]+=1];     ];     ];     ];      ];     Print["Grain size distribution : "];     For[i=0,i<10,i++,Print[i/2//N," - ",If[i<9,i+1,1000]/2//N,"    ",dist[[i+1]]]];     Print["Average grain size : ",avg];     Return[avg];     ];      The above routine grainsize is the one still to be optimized since there I did not do much conversion so far. Finally with the following statements the Graph above can be generated:               mesh = meshgen[0.01, 0.01, 500, 500];     temp = temperature[mesh, {0.0070001, yc = 0.0050001}, 0.005];     tmcs = tmc[mesh, temp, 0.005];     o = Table[RandomInteger[{0, 31}], {mesh[[2, 1]]}, {mesh[[2, 2]]}];     frames = {};     If [! FileExistsQ [NotebookDirectory [] <> "Graingrowth.dmp"],       For[i = 1, i < 250, i++,        tempc = PrintTemporary["Frame " <> ToString[i] <> "/250"];        If[i > 1,          tempp = PrintTemporary[           ArrayPlot[RemoveNoise[frames[[-1]]], PlotRange -> {-1, 31},             ColorFunction -> Function[v, If[v == 0, Black, Hue[v]]]]]];        on = potts[mesh, o, tmcs, 5000000];        AppendTo[frames, on\[Transpose]];        o = on;        If[i > 1, NotebookDelete[tempp]];        NotebookDelete[tempc];        ];       AppendTo[frames, o\[Transpose]];       DumpSave[NotebookDirectory[] <> "Graingrowth.dmp", frames];       ,       Get [NotebookDirectory[] <> "Graingrowth.dmp"];       ];     ArrayPlot[RemoveNoise[frames[[-1]]], PlotRange -> {-1, 31}, ColorFunction -> Function[v, If[v == 0, Black, Hue[v]]]]     Export[NotebookDirectory[] <> "FinalGrainStructure.png", %];ColorFunction -> Function[v, If[v == 0, Black, Hue[v]]]]      Of course there are multiple sources on the web of how to do PSD analysis, however I did not find any details about the potential of using Mathematica for this application. There is a very interesting Reference in the Wolfram Library, but it could not manage to get a hard or soft copy of this work. I guess the statistical routines within Mathematica would make it perfectly suitable for such an analysis. Any ideas/help/advice?


How do you express a function of x,y,and z as a function of the parameter t in a vector?

If I have a vector say for example $\vec{r}(t)=<t,t^2,3t^2>$ and a function $f(x,y,z)=\sqrt{1+30x^2+10y}$ whats the best way to express $f(x,y,z)$ as a function of the parameter $t$?


Simple ways to evaluate a derivative at a point?

The contrast in behavior between, say,               f[x_] = Sin[x^2];     f'[2]      vs.               u[x_, y_] = Cos[x + y^2];      ![enter image description here](http://i.stack.imgur.com/1uqai.png) has always bothered my students---and me! (Why _does_ it do it this way?) Anyway, I tell them to handle ${\partial u\over \partial x}\Big|_{x=2}$ via ![enter image description here](http://i.stack.imgur.com/V1BAQ.png) Is this the "simplest" way? How else might we accomplish this? I realize that this is a subjective question, but our context is this is a class where we use _Mathematica_ as a tool rather than a class centered on _Mathematica_ itself. Thus, I want to keep the commands and code required as reasonably elementary as possible (and preferably resembling their paper-and- pencil mathematical work).


How to perform fuzzy lookup between lists?

I have two big lists with 10,000 lines each, with product names from different databases. They have a lot of common products (50%), but they are not typed in the same way. For example there is one sample of 20 items that match: List One               Refresco em Pó TANG de Pêssego 30g     Refresco em Pó CLIGHT de Maracujá 9g     Refrigerante ANTARCTICA Soda Limão Garrafa 600ml     Refresco em Pó CLIGHT de Abacaxi com Hortelã 8g     Refrigerante ANTARCTICA Guaraná Lata 350ml     Refresco em Pó CLIGHT de Lima Limão 9g     Refrigerante ANTARCTICA Zero Guaraná Garrafa 600ml     Ração para Gatos Sabor Peixe e Frutos do Mar WHISKAS 500g     Refresco em pó TANG de Tangerina 30g     Refresco em Pó CLIGHT de Uva 9g      List Two               SUCO PO PESSEGO TANG 30G     SUCO PO DIET MARACUJA CLIGHT 8G     REFRIGERANTE SODA LIMONADA ANT 600ML     SUCO PO DIET ABACAXI C/HORTELA CLIGHT 8G     REFRIGERANTE GUARANA ANT LT 350ML     SUCO PO DIET LIMAO LIMAO CLIGHT 8G     REFRIGERANTE GUARANA ZERO ANT PET 600ML     RACAO PEIXE E FRUTOS DO MAR WHISKAS 500G     SUCO PO TANGERINA TANG 30G     SUCO PO DIET UVA CLIGHT 8G      In the original list they are out of order. In SQL Server Integration Services (SSIS) they have Fuzzy Lookup Transformations to do things like that. Question: What is the best way to make the match as automatically as possible in Mathematica? I tried something very incipient with `EditDistance`, but it's not enough. I know that some human intervention will be needed in the end, but currently the whole process is done manually. You can import a bigger list version with 400 lines each, direct in Mathematica using:               list1=StringSplit[Import["http://arquivo.rodrigomurta.com/Fuzzy_list1.txt"],"\n"]     list2=StringSplit[Import["http://arquivo.rodrigomurta.com/Fuzzy_list2.txt"],"\n"]      The lines 001 to 200 have the elements that are not equivalent, and don't match. The lines 201 to 400 have the elements that are equivalent, and are in the same order. So 201 in list 1 is equivalent in 201 in list 2. Thanks in advance


Both Sin[x]==0 && Cos[x]==0 as a solution

If I do               FullSimplify[Reduce[Sin[p1] == 0 && Cos[p1] == 0, Reals]]      I get                Cos[p1] == 0 && Sin[p1] == 0      while I would expect False. why? is there a way to have mathematica compute that both sin and cos cannot be 0?


Limit won't compute

Does anyone know why the limit:               Limit[(α*(E^((t*ϵ)/(λ*τ))*t*ϵ*(-1 + 2*λ) - E^((t*ϵ)/(λ*τ))*ϵ*(-1 +          2*λ)*τ + E^((t*ϵ*(-1 + 2*λ))/((-1 + λ)*λ*τ))*ϵ*(-1 + λ)*(1 + (-2 + ϵ)*λ)*τ +          ϵ*λ*(-1 + ϵ + 2*λ - ϵ*λ)*τ))/(E^((t*ϵ)/(λ*τ))*ϵ*(-1 + 2*λ)),        λ -> 0     ]      won't compute? Sorry about the weird formatting.


My mistake or error in NDSolve?

I try to solve the following equation $$y'=y-2ye^{-0.8y}, \quad y(0)=0.7.$$ By some aruments I expect to have a positive solution $y(t)\geq0$, for all $t>0$, however, NDSolve shows that starting from $t\approx 25$ there are some oscilations arround $0$. Their amplitude is quite small, less than $10^{-7}$. A similar result I can obtain using Maple. Is it surely means that my theoretical arguments are wrong or it may be an error in NDSolve algorithm due to some bad properties of this equation?


Random walk on a sphere

I'm trying to programme a random walk on a sphere with _Mathematica_. I found this code while I was searching, but I'm not getting results from it. I waited an entire day, but my pc didn't finish evaluating `rw`. I would like some help please (:               rotateWithAxis[p_, a_, theta_] :=        #/Norm[#] & @ ((1 – Cos[theta]) (a.p) a + p Cos[theta] + Cross[a, p] Sin[theta]);      Using the function, the random walk on a unit sphere is written as follows:               rw =        With[{stepLength = 0.03, num = 10000},         Module[{rotateWithAxis, p, a, q},           rotateWithAxis[p_, a_, theta_] :=              #/Norm[#] &@((1 – Cos[theta]) (a.p) a + p Cos[theta] + Cross[a, p] Sin[theta]);           a = {1., 0, 0};           q = {Cos[stepLength], Sin[stepLength], 0};           Table[p = a; a = q; q = rotateWithAxis[p, a, RandomReal[{0, 2 Pi}]], {num}]]];


Definite Integral over a path

What does               Integrate[f[z], {z, a, b, c, d}]      exactly calculate? Is it $$\int_a^b f(z)\, \mathrm{d}z +\int_b^c f(z)\, \mathrm{d}z +\int_{c}^d f(z)\, \mathrm{d}z ?$$ That was my first idea but               Integrate[f[z], {z, a, b, a}]      isn't simplified to 0 (even with a `FullSimplify`). For example                  Integrate[1/z, {z, 1, I, -1, -I, 1}]      gives as result $2\cdot \pi \cdot i$, which is the value of any closed path around zero. Which path does it take in the complex plane? Because there has been an Integral, where I thought it would converge, but I got an error with this one.


Select record when third column matches certain criterion

I've a table with 3 columns. The table looks like this:               test = {       {"john", {"suzan", "jan"}, {"new", "job", "policies"}},        {"carla", {"john", "piet"}, {"route", "suggestion"}},        {"jan", {"john", "suzan"}, {"re", "new", "job", "policies"}},        {"john", {"piet", "carla"}, {"re", "route", "suggestion"}}}      I would like to select the records with has no `re` in the third column. When I select the third column like this:               test1 = Select[test[[All, 3]], #[[1]] != "re" &]      The result is: > >     {{"new", "job", "policies"}, {"route", "suggestion"}} >   But I want to select also the columns one and two. When I write:               Select[test[[All, {1, 2, 3}]], #[[3]] != "re" &]      The result is empty > >     {} >   Who has a suggestion to solve this?


GPU user experiences

**Edit** Thanks to all who have responded! I now have plenty of information on the GeForce 650M GPU as found in most new, mid-range Mac laptops; the Mandelbrot code below runs in comfortably under a tenth of a second. I'm still quite curious how that compares to the GeForce 675MX GPU, which comes in new, high end iMacs. If someone provides that information as an answer, I'll happily accept! * * * **Original** When V8 came out, I was very excited about the introduction of GPU support. So far, however, I've not really been able to take advantage of it the way I would like to, simply because I haven't had a computer with an adequate GPU. Even when CUDA and/or OpenCL are supported, one might not see significant gains when using the GPU due (I think) to limited block size. Well, now it appears that I'll be getting a new computer in the not so distant future and I'd like to make sure that I'm happy with the GPU. To that end, I wonder if I could receive some feedback on actual user experiences. I am specifically interested in how CUDA and OpenGL work with midline Mac Laptops and Desktops. Laptops seem to run NVIDIA GeForce 640M or 650M GPUs, while desktops are more flexible going up to the 675 or higher in iMacs. So, does CUDA run on these machines? Specifically, does at least the following return True:               (* Warning - a large package is loaded from Wolfram Research *)     Needs["CUDALink`"];     CUDAQ[]          (* Out: False *)      I am aware, of course, of the systems requirements documentation here: http://reference.wolfram.com/mathematica/CUDALink/tutorial/Reference.html#1803279895 That page indicates that CUDA does _not_ run on 600 level GeForce GPUs, but I have a hard time believing that CUDA still is not running on main-line Macs at this point. Furthermore, NVIDIA's information seems to conflict with this here: https://developer.nvidia.com/cuda-gpus Hence, the question. * * * Also, I wonder if folks wouldn't mind trying a little test - say, generate a Mandelbrot set, since I'm quite curious about the relative speed of GPUs as accessed through Mathematica. To that end, here's a simple OpenCL program that generates escape times counts to generate a Mandelbrot image. Note that the `blockSize` parameter can be changed. I'm not an expert on GPU programming, but I believe that higher end GPUs generally allow higher block sizes and that larger block sizes permit more parallelization. My computer allows a `blockSize` of 16 or lower; lowering the `blockSize` generally slows down the computation.               Needs["OpenCLLink`"];     blockSize = 16;     code = "       __kernel void mandel_kernel(__global Real_t *mSet, int xRes, int yRes,           Real_t xMin, Real_t xMax, Real_t yMin, Real_t yMax) {          int xIndex = get_global_id(0);          int yIndex = get_global_id(1);          int i;               Real_t cx = xMin + xIndex*(xMax-xMin)/xRes;          Real_t cy = yMin + yIndex*(yMax-yMin)/yRes;          Real_t x = cx;          Real_t y = cy;          Real_t tmp;               if (xIndex < xRes && yIndex < yRes) {              for (i = 0; i < MAX_ITERATIONS && x*x + y*y <= BOUND_SQUARED; i++) {                 tmp = x*x - y*y + cx;                 y = 2*x*y + cy;                 x = tmp;             }             mSet[xIndex + yIndex*yRes] = i;           }       }       ";     If[OpenCLQ[] === True,       mandelCalculate = OpenCLFunctionLoad[code, "mandel_kernel", {{_Real, _, "Output"},          _Integer, _Integer, _Real, _Real, _Real, _Real}, {blockSize, blockSize},          "Defines" -> {"MAX_ITERATIONS" -> 100, "BOUND_SQUARED" -> "4.0"}],       Print["I'm sorry, your computer is even lamer than Mark's!"]     ];      Assuming your computer actually passes the test, the following will actually run the program for an `xRes` by `yRes` square.               xRes = 1500; yRes = 1500;     (mSet = OpenCLMemoryAllocate[Real, {xRes, yRes}];      mandelCalculate[mSet, xRes, yRes, -2.0, 0.6, -1.3, 1.3];      data = OpenCLMemoryGet[mSet]); // AbsoluteTiming          (* Out: {0.065236, Null} *)      Yeah, that's pretty fast. The computation was performed on the following GPU.               "Renderer" /. ("OnScreen" /. ("OpenGL" /.       SystemInformation["Devices", "GraphicsDevices"]))          (* Out: "ATI Radeon HD 6750M OpenGL Engine" *)      Again, the point is to compare GPUs but, if you want to generate an image, here's one way to do so:               colors = Map[{(100 - #)^2/10000, (100 - #)^3/1000000, (100 - #)/100} &, data, {2}];     Image[colors]          (* Out: Groovy picture *)


How to partition a list according to a nested table structure?

This question is related to this quesion. The goal is to use `ParallelMap` to map a function to a nested `Table` to get the FinestGrained distribution of calculation. But after that, I want to recover the original nested data structure instead of a flat one. For example, say I have a nested `Table` like this               Table[      Table[{line, honeycombnum, distance}, {line, 1,         honeycombnum + 1}, {distance, 1, 4}], {honeycombnum, 2, 5}]      as you can see, this nested table structure is **not of equal length** . Then **what is the general way** to recover the data structure after using               ParallelMap[f[#[[1]], #[[2]], #[[3]]] &, Flatten[Table[        Table[{line, honeycombnum, distance}, {line, 1,           honeycombnum + 1}, {distance, 1, 4}], {honeycombnum, 2, 5}], 2], Method -> "FinestGrained"]      **By the word "general ", I mean the method should be suitable for arbitrary complex`Table` structure.**


Problem with adding vector to symbolic function (for NDSolve)

I'm trying to set up a system of differential equations for passing to NDSolve. Note that my initial conditions are vector valued so Mathematica _should_ know that `raptor[[i]]` is a vector valued function. However, Mathematica seems to think that that `raptor[[i]]` is a scalar valued function (this is indicated by my output, which is included below). Input:               human[\[Theta]_, t_] := 0 t*{Cos[\[Theta]], Sin[\[Theta]]} + {0, 10 Sin[\[Pi]/3]}          V = {25, 10, 25};     P = {{-10, 0}, {0, 20 Sin[\[Pi]/3]}, {10, 0}};     \[Theta] = 0;           Flatten[       Table[       {        raptor[[i]]'[t] == Normalize[human[\[Theta], t] - raptor[[i]][t]]        raptor[[i]][0] == P[[i]]       }, {i, 3}]      ]      Output:               { Raptor[[1]]'[t]=={ first component of human - raptor[[i]][t],                          second component of human - raptor[[i]][t]},       Raptor[[1]][0] =={-10,0},        Raptor[[2]]'[t]== ...      }      Furthermore, changing the raptor indexes into subscripts does not change anything. When I try to use this system in NDSolve I get the error "Computed derivatives do not have dimensionality consistent with the initial conditions." After talking to my TA for the course, we got this to work by defining `human[theta, t]` as one of the differential equations. However, my TA didn't know why my code failed (it seemed very reasonable to both of us) and said I could ask the Mathematica stack exchange. So, could anyone explain why my code fails? Namely, why does Mathematica think that `raptor[[i]]` is a scalar valued function even though its initial condition is clearly vector valued? Is there a better way to do this then putting `human[theta, t]` into the list of equations for NDSolve? PS: for those wondering, this is solving a variant of problem #2 from http://xkcd.com/135/


Why do certain fractional values in TriangleWave not evaluate?

While answering another question I discovered that `TriangleWave` does not automatically evaluate when given certain fractional values, specifically fractions with a denominator of 20:               TriangleWave[ Range[8] / 20 ]      > >     {TriangleWave[1/20], 2/5, TriangleWave[3/20], 4/5, 1, 4/5, > TriangleWave[7/20], 2/5} >   These are reduced by `Simplify`:               TriangleWave[ Range[8] / 20 ] // Simplify      > >     {1/5, 2/5, 3/5, 4/5, 1, 4/5, 3/5, 2/5} >   This appears to be the only denominator under 10,000 that does not automatically evaluate:               Cases[TriangleWave[1/Range[1*^5]], _TriangleWave]      > >     {TriangleWave[1/20]} >   Is there a reason to believe that this behavior is anything other than a bug in `TriangleWave`?


Symbol resolution for contexts inside packages

Say I create `$UserBaseDirectory/Autoload/MyPackage/init.m` containing:               BeginPackage["MyPackage`"];     Symbol1 = 1;     Begin["`MyContext`"];     Symbol2 = 2;     End[];     EndPackage[];      When I run Mathematica:   * `Symbol1` resolves to `MyPackage`Symbol1` and is colored black, indicating it has a value assigned.   * `MyContext`Symbol2` does not resolve, but `MyPackage`MyContext`Symbol2` does. However, there is no autocompletion and the symbol is colored blue (indicating no value assigned) even after evaluation. Is it possible to configure my package such that `MyContext`Symbol2` will resolve and have all the front-end niceties?


Overloading ClearAll[] to take no arguments

I use the command > ClearAll["Global`*"] so much that I thought it would be nice to have a function that called it. Since by default `ClearAll` requires an argument, I decided to overload it and have it so when no arguments are passed to `ClearAll` it clears Global. > `Unprotect[ClearAll]` > > ClearAll[]:=ClearAll["Global`*"]; > > `Protect[ClearAll]` However, mathematica still expects an argument to the function, resulting in this ![enter image description here](http://i.stack.imgur.com/WQlgX.png) It still works fine, but is there any way to remove the red arrow? I've tried `SyntaxInformation[ClearAll] := {"ArgumentsPattern" -> {___}}` which should allow it to accept 0 arguments, but it still complains about it.


How to generate nonperiodic tilings?

I need to generate nonperiodic tilings which are similar to the attached figure (kite-domino tiling). I was thinking the code is similar to the code for the Penrose tiling. However, that code is too complicated for me to digest at this time. ![Kite-Domino Tiling](http://i.stack.imgur.com/VBoUN.png)


HoldForm doesn't hold form

In _Mathematica_ version 10, `HoldForm` no longer produces the same results as in version 8 ( **edit:** I only have versions 10 and 8 installed, so can't compare to version 9 directly). Here are some examples (on Mac OS X): **Formatting of`\\[ScriptCapitalE]`** This symbol is output correctly:               InputForm[ℰ]      > `ℰ` But when wrapped as follows, I get gibberish:               HoldForm[InputForm[ℰ]]      > `â °` **Arguments in`HoldForm`aren't held** Why would I want to use `InputForm` inside `HoldForm` in the first place? Here is one example, using the constant `E`. I would like it to be displayed as `E`:               HoldForm[InputForm[E]]      > `E` On the other hand, the constant is formatted differently if I leave out `InputForm`:               HoldForm[E]      > `` So why not use `InputForm` without `HoldForm`? Because then I can't write assignments like this:               HoldForm[InputForm[E = 1]]      > `E = 1` Here, I get no error because of `HoldForm`. So far, so good. But now things become inconsistent again if I put the same construct into a `Plot`:               Plot[x^2, {x, -2, 2}, AxesLabel -> {x, HoldForm[InputForm[E = 1]]}]      ![plot error](http://i.stack.imgur.com/i4D08.png) This used to work in version 8, but now it throws an error. The resulting plot is still correct, but the messages seem to indicate that `HoldForm` was ignored at some stage. Indeed, I then proceeded to do a more basic test:               Clear[x];     Plot[Sin[x], {x, 0, 1}, AxesLabel -> {"x", HoldForm[x = 3]}];     x      > `3` Yes, that's right. `HoldForm` was completely ignored. What can be done to fix this? **Edit** I tried to report the issue, but am currently receiving web form errors at the Wolfram site, so will have to try again later.


How can access to curated data needed by GeoRegionValuePlot be speeded up?

Seems that `GeoRegionValuePlot` requests data from the internet multiple times to process its plot. As an example, let's graph smoking per capita worldwide.               smokers =        Import["http://en.wikipedia.org/wiki/List_of_countries_by_cigarette_\         consumption_per_capita", "Data"];     table = Rest@smokers[[1, 1, 2]][[All, 2 ;;]];      rule = "Republic of Macedonia" -> "Macedonia";      GeoRegionValuePlot[       {CountryData[StringTrim@#[[1]] /. rule], Interpreter["Number"][#[[2]]]} & /@ table,        ImageSize -> Large,        PlotLabel -> "Cigarrete Consumption Per Capita"]      While waiting for the plot to be graphed, you can see that mathematica accesses servers for information at least twice (Message below shows up twice, then takes additional time to process). ![enter image description here](http://i.stack.imgur.com/Qee3k.png) ![enter image description here](http://i.stack.imgur.com/WRYwj.png) How can the GeoRegionValuePlot performance be improved? Is there a way to cache the information retrieved by the function (maps, polygons, etc) in the local drive so subsequent calls to the GeoRegionValuePlot will perform better?


Why does MakeBoxes mess up RowBox ordering?

When I use RowBox for MakeBoxes the order of the elements is changed for TraditionalForm, if there is a plus (+) in the list of elements.               MakeBoxes[x, form_] = RowBox[{"b", "+", "a"}];     MakeBoxes[x, StandardForm]     MakeBoxes[x, TraditionalForm]     (* Out[2] = RowBox[{"b", "+", "a"}]        Out[3] = RowBox[{"a", "+", "b"}] *)      Sometimes Mathematica really makes me wonder. Does this only happen when there is a plus in RowBox? Is there any way to fix this?


Mathematica unable to solve equation numerically while Wolfram|Alpha can

I want to solve the following equation               2 x == Sinh[x]      _Mathematica_ is unable to do so               In[1]:= Solve[2 x == Sinh[x], x]     During evaluation of In[20]:= Solve::nsmet: This system cannot be solved with the methods available to Solve. >>     Out[1]= Solve[2 x == Sinh[x], x]      However, Wolfram|Alpha can successfully solve the equation ![Wolfram|Alpha query](http://i.stack.imgur.com/i87NA.png) How can I achieve the same in _Mathematica_?


Green's Function in Mathematica

The equation I am trying to solve is: $$q \, T_1''(x)-T_1(x)(f-b \, g+i\,w \, p)=T(f_1-b \, g_1)-g_1\tag{1}$$ My professor says that $(1)$ can be solved by using Green's function $G(x,y)$, where $G(x,y)$ is the solution of this equation: $$q\,G''(x,y)-G(x,y)\,(f-b\,g+i\,w\,p)=\mathrm{Dirac}(x-y)\tag{2}$$ The boundary conditions are: $$G(L/2,y)=0 , G(-L/2,y)=0\tag{3}$$ And I tried to solve $(2)$:               eq1 = D[g[y], {y, 2}] - a*g[y] - DiracDelta[x - y]     ans1 = DSolve[{eq1 == 0, g[-L] == 0, g[L] == 0}, g[y], y]     greenfunction1 = g[y] /. ans1[[1]]      But it does not work. However when I take out the constant $a$, it works:               eq1 = D[g[y], {y, 2}] - g[y] - DiracDelta[x - y]     ans1 = DSolve[{eq1 == 0, g[-L] == 0, g[L] == 0}, g[y], y]     greenfunction1 = g[y] /. ans1[[1]]      Why does _Mathematica_ fail to evaluate my first query? Also, when I get the Green's function, I have to into solution of equation (1)which is;               Integrate[(T[y](f_1-bg_1)-g_1)g[y],{y,-L/.2,L/.2}]      where T(x) is; T(x)= 2*C1*cosh(x*((f_0-b*g_0)/q)^0.5)+g/(f_0-b*g_0) (4) Then C1 has to be determined from boundary condition. T(+L/2)=0 T(-L/2)=0 The g_zero has to be determined from constant temperature condtion. 1/L*integral[T(x),{x-L/2,L/2}]=Tw-Tam Then I found T(x) in Matlab. When I tried to solve Green Function part, I could not do it in Matlab. I deceided to move Mathematica. Now I want to solve all parts in Mathematica. This is my Matlab code for T(x);               clc;     clear all;     Tw = 250;          Tam = 27;          resist=5.6e-8;          diameter=5e-6;          h=5700;          k=190;          f = pi()*diameter*h;          b = 0.0044;          q = 0.25*pi()*k*diameter^2;          L = 1.25e-3;          syms c x g          T = 2*c*cosh(x*((f-b*g)/q)^0.5)+g/(f-b*q);          c = solve(subs(T,'x',L/2)==0,c)          z = simplify(int(subs(T,'c',c),x,-L/2,L/2))          g = solve(z==L*(Tw-Tam),g)          T      I want to solve T and T_1 in Mathematica. Above I tried to solve Green Function code , but I could not put Green function and T into integration of T_1. Sorry about text writing. I tried a lots of time copying from Mathematica , however its format did not match with here. Thank you Yusuf


Locator Appearance

I am using `LocatorPane` with `LocatorAutoCreate -> True`. **I would like to have the appearance of each new locator be different**. Ideally I would like to use a dot with a numeric superscript that would be incremented as they where created, but just using the incremented number as the locator would be good too. Is this possible?


Produce a 1-dimensional list of all unique matrix elements

We have some symbolic matrix m, e.g.               m={{1, x, 4 x + y},{0, x y + 4x, 4x},{7 x, x, 4x + x y}}      and we want to produce as output a list of all the unique elements present in m:   desired output:               {1, x, 4 x + y, 0, x y + 4x, 4x, 7 x}      I've tried to use ArrayReshape and ArrayFlatten to convert the matrix into a 1-dimensional list, and then I would hopefully be able to conclude with Union, but so far it isn't working properly.


Controlling the plot range of a PairedBarChart

I would like to adjust the plot range of a PairedBarChart along the 'bar' direction. However,               PairedBarChart[RandomReal[10, 10], RandomReal[10, 10],        PlotRange ->          {{0, 20} (*along bar/ labeled axis*),           Automatic (*along center axis*)}]      doesnt work.


How to plot the Euler's formula in 3D?

In Von Neumann's stability analysis of Finite Difference Equations, the Euler's formula is used to describe a perturbation. Now the finite difference equation is stable if this perturbation does not grow in time. Now, my question really is: how do I plot the perturbation (Equation 1) three- dimensions(?)/Im vs Real dimensions? $$\epsilon(x,t) = \sum_{m=1}^{M} e^{at} e^{ik_m x} \ldots \ldots \text{(1)}$$ I realize that the the Euler's formula $e^{ik_m x}$ describes a circle. Clearly the multiplicative amplitude factor $e^{at}$ either "grows" this circle or decreases it whether or not $e^{at}$ is greater than 1 or not. I would like to describe that as a `Manipulate` or a `ListAnimate` in _Mathematica_ but I don't understand which function to use. So far I have understood that `PolarPlot` and `ParametricPlot` draw this circle in 2D. **Parametric Plot example**               ParametricPlot[G {Re[Exp[I x]], Im[Exp[I x]]}, {x, 0, 2 \[Pi]},       PlotRange -> {{-1, 1}, {-1, 1}}]      ![enter image description here](http://i.stack.imgur.com/ByXKJ.png) **Polar Plot example**               PolarPlot[{Re[Exp[I x]], Im[Exp[I x]]}, {x, 0, Pi}]      ![enter image description here](http://i.stack.imgur.com/QW20n.png)


Possible bug in Dynamic

The code below crashes the Mathematica kernel in version 10 (not in V9) every time I run it on Windows and on Mac OS. I've sent it to WRI, but was told that they could not reproduce the crash. Does this really only crash on my computers? Could somebody else test it with Mathematica 10?               pts = Flatten[        Table[Through[{Cos, Sin}[α]] r, {α, 0.,           360 ° - 10^-5, 60 °}, {r, 1, 2}], 1];          LocatorPane[Dynamic[pts],       Dynamic@Show[        Graphics[{Arrow /@ Partition[pts, 2]}], {a, b} =          Transpose[Map[Module[{p1, p2, d}, {p1, p2} = #;             d = p2 - p1;             {d, p1.d}] &, Partition[pts, 2]]];        RegionPlot[And @@ Thread[a.{x, y} < b], {x, -2, 2}, {y, -2, 2}]]]          ContourPlot[      Total[Log[Clip[b - a.{x, y}, {10^-10, ∞}]]], {x, -2,        2}, {y, -2, 2}, PlotRange -> {-10, 0}]


2D random walk within a bounded area

I want to simulate a random walk on two dimension in a bounded area such as a square or circle. I am thinking of using `If` statement to define a boundary. Is there a better way to define a bounded region?


Resources for Sound Synthesis & Design

Are there any resources for sound synthesis using Mathematica? This page, Mathematica: Audio Synthesis Software, refers to other software packages, e.g. Max/MSP and Csound, for real-time synthesis. However, I would like to use Mathematica's signal processing capabilities for analysing the sound effects of various filters, before I have to delve into some other package. `Play` and `Sound` do not seem to have any real-time capability. _Max/MSP features image_ ![enter image description here](http://i.stack.imgur.com/nxJAc.jpg) **Edit** The immediate stumbling block is the lack of real-time control when using `Play`, e.g.               EmitSound[Play[Sin[500 t^2], {t, 0, 10}]]      For instance, the played sound wave doesn't seem to be easily manipulated.                Manipulate[EmitSound[Play[Sin[500 a t^2], {t, 0, 10}]], {a, 1, 4}]      Note. You may need to quit Mathematica to stop the above command. If the emitted sound can be manipulated then filter effects could be applied in variable magnitudes.


Finding the perimeter, area and number of sides of a Voronoi cell

Does anyone have any suggestions how to determine the perimeter, area and number of sides of each Voronoi cell in Voronoi diagram?


Why can't Mathematica solve these non-linear equations?

$l_{2}$ and $\theta$ are the variables. All other parameters are constants. I need to find $l_{2}$ and $\theta$ in terms of these constants. $\frac{\mu_{0}\sin(\theta-\theta_{0})}{\sqrt{l_{2}^2 +\beta_{0}l_{2}+\mu_{0}l_{2}\cos(\theta-\theta_{0}) +\lambda_{0}}} + \frac{\mu_{1}\sin(\theta-\theta_{1})}{\sqrt{l_{2}^2 +\beta_{1}l_{2}+\mu_{1}l_{2}\cos(\theta-\theta_{1}) +\lambda_{1}}} =0 $ and $\frac{2l_{2}+\beta_{0}+\mu_{0}\cos(\theta-\theta_{0})}{\sqrt{l_{2}^2 +\beta_{0}l_{2}+\mu_{0}l_{2}\cos(\theta-\theta_{0}) +\lambda_{0}}}+ \frac{2l_{2}+\beta_{1}+\mu_{1}\cos(\theta-\theta_{1})}{\sqrt{l_{2}^2 +\beta_{1}l_{2}+\mu_{1}l_{2}\cos(\theta-\theta_{1}) +\lambda_{1}}} =\frac{-2}{1+Vr^{l_{2}/D}}$ Here's the _Mathematica_ code I used:               Solve[{(μ0 Sin[t - t0])/Sqrt[ l2^2 + β0 l2 +μ0 l2 Cos[t - t0] + λ0] +          (μ1 Sin[t - t1])/ Sqrt[l2^2 + β1 l2 + μ1 l2 Cos[t - t1] + λ1] ==  0,          (2 l2 + β0 + μ0 Cos[t - t0])/Sqrt[ l2^2 + β0 l2 + μ0 l2 Cos[t - t0] + λ0] +          ( 2 l2 + β1 + μ1 Cos[t - t1])/Sqrt[  l2^2 + β1 l2 + μ1 l2 Cos[t - t1] + λ1] +          2/( 1 + V r^(l2/D0)) == 0}, {t, l2}]      This didn't work. How can I use Mathematica techniques to solve this equation?


Sort matrix by columns and rows without changing them

I would like to sort a matrix in descending order first by the total of each column, then by the total of each row, but without changing their content. For example, if I had:               TableForm[{{0, 0, 1, 1}, {0, 0, 0, 1}, {1, 0, 1, 1}, {1, 1, 1, 1}},       TableHeadings -> {Range[1, 4], Range[1, 4]}]      I want to sort first the columns:               TableForm[{{1, 1, 0, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 1, 1, 1}},       TableHeadings -> {Range[1, 4], {"4", "3", "1", "2"}}]      Then the rows:               TableForm[{{1, 1, 1, 1}, {1, 1, 1, 0}, {1, 1, 0, 0}, {1, 0, 0, 0}},       TableHeadings -> {{"4", "3", "1", "2"}, {"4", "3", "1", "2"}}]      The goal is to get as many 1's as possible to the upper-left corner. I added `TableHeadings` to this mockup of the desired result simply to show the content of the columns/rows remains the same. If there is a better way other than using the `Total` for each column/row that is fine too. Any help is much appreciated!


How to Debug Missing[NotAvailable] error for Social Media Data

I get a `Missing[NotAvailable]` error message when trying to access Social Media Data using `SocialMediaData["Facebook", "Friends"]` in _Mathematica 9_ on Linux. Now, I don't know how to find the source of the error. I don't have the same error for twitter. Is there a way to get verbose error information?


Circular AngularGauge does not roll over boundaries

I am using the Mma9 `AngularGauge` function to develop a controll for a rotating stage. I am experiencing several problems:   1. I am unable to get the values {0°, 90°, 180°, 270°}.   2. I am unable to align those values at arbitrary locations, e.g. 0° at the top.   3. I cannot make the needle roll over the 0° / 360° boundary, i.e. to get from 10° to 350° I have to "roll back". In particular the function `ScaleDivisions` drives me nuts. In the figure below the 0 in 360 is drawn twice, not clearly visible here but obvious on my screen. I am not concerned about the "°" right now and my Mma9 installed without any error messages (unitil now). `AngularGauge[Dynamic[x], {0, 360}, ScaleDivisions -> {20, 2}, ScaleOrigin -> {0, 2 \\[Pi]}, ImageSize -> {256, 256}, GaugeLabels -> "Value", GaugeMarkers -> "InsideScale"]` ![enter image description here](http://i.stack.imgur.com/Nwzex.png)


How can I style text like in the documentation?

I'm writing an article, and I really like this style that you get when you type `?AnyFunction`. ![I want to achieve style like this](http://i.stack.imgur.com/4JCyR.png) Is it possible to achieve this?


Isolate a specific contour without Contour Shading

I have a contour plot that took a few hours to evaluate. Is there a way that I can show only the contour lines of a specific value without re-evaluating the contour plot?


How does MakeBoxes handle an n-ary operator?

I want to format results from `Reduce` using the $\cup$ symbol instead of the $\lor$ symbol. For example, `Reduce[x^2 > 4, x, Reals]` produces $x<-2\lor x>2$ while I would like it to produce $x<-2\cup x>2$. My current solution is to add the head `xO` to use in place of the `Or` head and associate the appropriate formatting with the `xO` head using `MakeBoxes`.               xO /: MakeBoxes[xO[x_, y_], form_] :=                                                                      RowBox[{MakeBoxes[x, form], "\[Union]", MakeBoxes[y, form]}];      When I want to invoke the special formatting, I simply substitute `xO` for `Or`.               Reduce[x^2 > 4, x, Reals] /. Or -> xO      This produces the desired result of $(x<-2)\cup (x>2)$. I am feeling like a master bit-twiddler at this point. Of course, my next test case didn't work.               Reduce[x^3 + 2 x^2 - x - 2 == 0] /. Or -> xO     (* xO(x==-2,x==-1,x==1) *)      My `MakeBoxes[xO[x_, y_]]` definition above does not match the case when `xO` has three arguments. I added the following to limp along a little further.               xO /: MakeBoxes[xO[x_, y_, z_], form_] :=                                                                  RowBox[{MakeBoxes[x, form], "\[Union]", MakeBoxes[y, form], "\[Union]", MakeBoxes[z, form]}];      This works for three arguments, but is clearly not a robust solution. What is the general method for an n-ary function? I tried several variations of the following:               xO /: MakeBoxes[xO[x_, y__], form_] :=                                                                     RowBox[{MakeBoxes[x, form], "\[Union]", MakeBoxes[y, form]}];           which produced the error:               MakeBoxes::argt: "MakeBoxes called with 3 arguments; 1 or 2 arguments are expected"      when applied to the `Reduce[x^3 + 2 x^2 - x - 2 == 0] /. Or -> xO` test case. I am probably missing something obvious. Any ideas?


Using Manipulate with a control variable for selective recalculation

I'm trying to adapt **Nasser** 's method for using a _control variable_ inside Manipulate to selectively choose what part of the code should be recalculated depending on the controls changed. I've also read his previous notes but the last version seems much more simple and something I can follow. I need this functionality for a simulation I'm working on about the field lines of an electric dipole. In the simulation it should be possible to move the two charges q1 and q2 generating the field and also to move a third point P. The point P only serves to see the field line passing through P. Since the single field line originating from P should have different graphical parameters than the field lines of the "background field" I created two different Streamplots: " _fieldlines_ " is for the general field and " _fieldpoint_ " is for the single line through P. They are combined together with the " _Show_ " command. So my problem is similar to the one addressed in the first link. If I move the point P I don't want the Streamplot _fieldlines_ of the electric field lines recalculated, but just the Streamplot _fieldpoint_ (dealing with the single line through P). On the contrary both Streamplots should be recalculated when the two charges generating the field are moved or changed. Up to now, following Nasser's model I've come up with the following "example" code (my intended simulation is much more complicated):               Manipulate[tick;      Show[f1, f2],      Grid[{        {"q1pos",          Slider2D[          Dynamic[q1pos, {q1pos = #; f1 = fieldlines[q1pos, q2pos];              f2 = fieldpoint[q1pos, q2pos, pt];             tick = Not[tick]} &], {{-6, -6}, {6, 6}}], Dynamic[q1pos]},        {"q2pos",          Slider2D[          Dynamic[q2pos, {q2pos = #; f1 = fieldlines[q1pos, q2pos];              f2 = fieldpoint[q1pos, q2pos, pt];             tick = Not[tick]} &], {{-6, -6}, {6, 6}}],          Dynamic[q2pos]}, {"pt",          Slider2D[Dynamic[pt, {pt = #; f2 = fieldpoint[q1pos, q2pos, pt];             tick = Not[tick]} &], {{-6, -6}, {6, 6}}], Dynamic[pt]}        }],      {{tick, False}, None},      {{q1pos, {-2, 0}}, None},      {{q2pos, {2, 0}}, None},      {{pt, {-2.5, 2}}, None},      {{f1, fieldlines[{-2, 0}, {2, 0}]}, None},      {{f2, fieldpoint[{-2, 0}, {2, 0}, {-2.5, 2}]}, None},      TrackedSymbols :> {tick},      Initialization :> (        {         field[x_Real, y_Real] := Module[{},           (*heavy computation goes here*)           {(2 (x - q1pos[[1]]))/             EuclideanDistance[q1pos, {x, y}]^3 + (-2 (x - q2pos[[1]]))/             EuclideanDistance[q2pos, {x, y}]^3, (2 (y - q1pos[[2]]))/             EuclideanDistance[q1pos, {x, y}]^3 + (-2 (y - q2pos[[2]]))/             EuclideanDistance[q2pos, {x, y}]^3}];         fieldlines[q1pos_, q2pos_] := Module[{},           (*heavy computation goes here*)           StreamPlot[field[x, y], {x, -5, 5}, {y, -5, 5},            StreamPoints -> pnts,            StreamScale -> 1/20, ImageSize -> 600]];         fieldpoint[q1pos_, q2pos_, pt_] := Module[{},           (*heavy computation goes here*)           StreamPlot[field[x, y], {x, -5, 5}, {y, -5, 5},             StreamPoints -> {{{pt, {Thickness[0.005], RGBColor[1, 0, 0],                  Arrowheads[0.02]}}}, Automatic, {ForwardBackward, 400}},             ImageSize -> 600]];         pnts = Tuples[{-3, -2, -1, 0, 1, 2, 3}, 2]         }        )      ]      But there are problems with this code:   1. The first run is very slow; the second run is ok (there must be some problem with the inizializaton).   2. When I move the point P I can see that the Streamplot of the "background" field lines is not recalculated. That's fine and that's what I wanted. Anyway the single field line loses some of the specifications (arrows). The same thing happens when one of the charges q1 or q2 are moved.   3. I'd like to use three **Locator** instead of three **Slider2D** for q1, q2 and P in my simulation, but I haven't found yet if that's possible and how to do that. Any help?


Clever use of DownValues, or failure to understand the "Mathematica Way."

I needed to look at the changes in the values of about 4000 items from one year to the next. I have a table with identifiers and values for each year. Not all of the items are in each list. The tables contain the following rows, with more data to the right. ![enter image description here](http://i.stack.imgur.com/FVM1i.png)   So I did the following:               govnew = Select[data[[2 ;;, {2, 3, 4, 6}]], #[[4]] > 0 &];       govold = Select[dataold[[2 ;;, {2, 3, 4, 6}]], #[[4]] > 0 &];       intersection = Intersection[govnew[[All, 1]], govold[[All, 1]]];        Clear[both];       Map[(both[#] = 1) &, intersection];       govnew2 = Select[govnew, both[#[[1]]] == 1 &];        govold2 = Select[govold, both[#[[1]]] == 1 &];          Which reduced the two lists to the intersection of the identifiers in both lists. It worked. But it reduces a list of Down Values to a dictionary. Doesn't use a _Mathematica_ function in a secret and powerful way. Is there a more _Mathematica_ like approach.


How to symbolically do matrix "Block Inversion"?

Consider a block (partitioned) matrix               matrix = ArrayFlatten[{{a, b}, {c, d}}]      where, `a`, `b`, `c` and `d` are each matrices themselves. Say, for example,               a = {{a11, a12}, {a21, a22}}     b = {{b11, b12}, {b21, b22}}     c = {{0, 0}, {0, 0}}     d = {{d11, d12}, {d21, d22}}      How can you find the _block_ inverse of this matrix? A desired solution is, using the example above               {{Inverse[a] , -Inverse[a].b.Inverse[d]},{0,Inverse[d]}}      which is easily verified using               Simplify[Inverse[ArrayFlatten[{{a, b}, {c, d}}]] ==      ArrayFlatten[{{Inverse[a], -Inverse[a].b.Inverse[d]}, {0,       Inverse[d]}}]]      which yields `True`. How can you solve the block inverse problem for arbitrary submatrices, and for block matrices of larger sizes (i.e. 3x3, 4x4, etc)?


How to expand multiple cells at once?

Is there a simple way to expand multiple cells simultaneously? At the moment I am primarily interested in fully expanding "in one fell swoop" all the cells in a documentation window, although I can imagine situations in which I'd want to open several cells only one-level deep, so I'm interested in this case as well. Finally, it would also be useful to know how to collapse multiple cells at once. EDIT: My immediate interest is for ways to do this interactively, rather than programmatically. I.e. keyboard (+ mouse) shortcuts, or (second best), menu commands.


Passing list of options to Plot

I'm looking for a way to create a variable that I can use to hold all of the graphics directives for, say, a plot command. For example, I have 8 plots with variations on the following:               Plot[{Im[eppar[400*10^12, t, 0.1]],           Im[eppar[400*10^12, t, 0.2]],            Im[eppar[400*10^12, t, 0.5]],            Im[eppar[400*10^12, t, 0.8]]          }, {t, tlow, thigh}, (**directives**)]      There's a fairly long list of directives I'm using for the plots, and I'd like to avoid having to modify 8 long, complicated expressions every time I want to change anything. Does anybody know of a solution to this? It would make my code much cleaner.


How to thread lines through the n-th roots of unity in a given order

n = 8;     Initial = ToCharacterCode["bgehadfc"] - 96;     RootsOfUnity = Table[E^((2 k I \[Pi])/n), {k, n}];          Line1 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[5]]], Part[Im[#] & /@ RootsOfUnity, Initial[[5]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[6]]], Part[Im[#] & /@ RootsOfUnity, Initial[[6]]]}}]];     Line2 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[6]]], Part[Im[#] & /@ RootsOfUnity, Initial[[6]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[7]]], Part[Im[#] & /@ RootsOfUnity, Initial[[7]]]}}]];      Line3 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[7]]], Part[Im[#] & /@ RootsOfUnity, Initial[[7]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[8]]], Part[Im[#] & /@ RootsOfUnity, Initial[[8]]]}}]];     Line4 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[8]]], Part[Im[#] & /@ RootsOfUnity, Initial[[8]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[1]]], Part[Im[#] & /@ RootsOfUnity, Initial[[1]]]}}]];     Line5 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[1]]], Part[Im[#] & /@ RootsOfUnity, Initial[[1]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[2]]], Part[Im[#] & /@ RootsOfUnity, Initial[[2]]]}}]];      Line6 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[2]]], Part[Im[#] & /@ RootsOfUnity, Initial[[2]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[3]]], Part[Im[#] & /@ RootsOfUnity, Initial[[3]]]}}]];      Line7 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[3]]], Part[Im[#] & /@ RootsOfUnity, Initial[[3]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[4]]], Part[Im[#] & /@ RootsOfUnity, Initial[[4]]]}}]];      Line8 = Graphics[ Line[{{Part[Re[#] & /@ RootsOfUnity, Initial[[4]]], Part[Im[#] & /@ RootsOfUnity, Initial[[4]]]}, {Part[Re[#] & /@ RootsOfUnity, Initial[[5]]], Part[Im[#] & /@ RootsOfUnity, Initial[[5]]]}}]];          VerticesNumbers = Graphics[Table[Text[Style[FromCharacterCode[i + 96], Large], {Cos[(i 2 \[Pi])/n], Sin[(i 2 \[Pi])/n]}], {i, n}]];          Show[Line1, Line2, Line3, Line4, Line5, Line6, Line7, Line8, VerticesNumbers, Axes -> False]      ![enter image description here](http://i.stack.imgur.com/57wBZ.jpg) Code on the above has irrelevant repetition. I need to put some thing (like For Loop or array), but When I add I don't get the graph. Do you have any idea how to get rid of this repetition?


Default position and size of front-end windows (in Windows 7)

I'm running _Mathematica_ 8 on Windows 7. When I start the _Mathematica_ front end, I would like the menu bar and the blank notebook that opens to appear at a different position and with a different size from what they do by default. (By default the menu bar appears at the top of the screen and the blank notebook appears below it on the left side of the screen. I would like to try having the menu bar and notebook appear resized to about 350px wide and positioned in the upper right corner of the screen: ![enter image description here](http://i.stack.imgur.com/tqznd.png) .)


How to syntax highlight a code cell in another language?

I'm learning c/c++/objective-c and I wanted to write my notes in a mathematica notebook. But without the proper syntax color highlighting it looks terrible....


Can Mathematica be regarded as a software prototyping environment?

I am an undergraduate student, starting to use Mathematica to model simple physical chemistry problems, as a prelude to a summer internship in a computational/theoretical chemistry group. The solution to a problem I was given (and walked through) now needs to be incorporated in the group's program, which contains >17 Kloc. Before seeing this big program, my experience with Mathematica gave me the impression that it was a very sophisticated graphical calculator. Mathematica is fast, extremely versatile, but its code cannot be compiled and made executable (for what I know). I know one can use the CDF player, but that means the program is not really standalone. Considering my example, I am wondering if there is a point at which one would be better off using another programming language than Mathematica to do the computation. Are there disadvantages or obstacles present when Mathematica programs grow bigger than a certain size?


Combining Image3D and Graphics3D

I want to combine an `Image3D` and a `Graphics3D` using `Show`. Here is the code:               data = Table[        Abs[((3 - 3 z) (.5 Sign[3 - 3 z] + .5)) (x Sin[x] + y Cos[y])],        {x, 0, 15, .1}, {y, 0, 10, .1}, {z, 0, 3, .1}        ];     Show[Image3D[data/Max@data],       Graphics3D[{AbsoluteThickness[5], Blue,         Line[{{0, 0, 0}, {2, 2, 2}, {3, 3, 2}, {8, 5, 2}, {14, 9, 2}, {15,            10, 0}}]}]]      While the coordinates are aligned, the output is not. ![3d path overlap](http://i.stack.imgur.com/yQHsn.png) See the blue line on the right corner. How can I fix the problem? **Edit:** The issue is resolved. There are two answers below. Both are helpful but neither of them is complete. Once any of them is competed, I'll mark it as accepted. I write one possible answer to the question here (I added `{#[[3]], #[[2]], #[[1]]}/delta & /@ pointList` to my code):               With[{delta = .1},      data = Table[        Abs[((3 - 3 z) (.5 Sign[3 - 3 z] + .5)) (x Sin[x] + y Cos[y])],        {x, 0, 15, delta}, {y, 0, 10, delta}, {z, 0, 3, delta}        ];      Show[Graphics3D[{AbsoluteThickness[5], Blue,          Line[{#[[3]], #[[2]], #[[1]]}/            delta & /@ {{0, 0, 0}, {2, 2, 2}, {3, 3, 2}, {8, 5, 2}, {14, 9,              2}, {15, 10, 0}}]}], Image3D[data/Max@data]]      ]


Cannot save file

Hello I have a problem in saving files in Mathematica. I can't save not only notebooks but also figures. When I choose to save the notebook it open a window that says: > Mathematica could not find enough disk space to save the file > `C:\Users\Διονύσης\Documents\science\mathematica\Untitled-1.nb`. The file > was left unchanged. The disk is full, or if you are using a file server you > may have reached your disk space quota. Although I have notebook saved from a friend. I can save on it. When I want to use it i simply copy-paste it, delete the code, wright mine and then I can save it without any problem. But still I cannot save figures. To save them I can only copy-paste them to Word from where I can save them as figures. If anyone could tell me the source of my problem it would be helpfull! Thank you very much!


Get Coordinates in Image Processing

I'm new to Mathematica. I'm very impressed about it's abilities. It's very easy to achieve complex tasks. But I fail the simple ones. **How can I get coordinates in image processing?** I'd like to detect one of the following things   * absolute vertical center of the rectangle surrounding all white parts   * gravity center of all white parts e.g.: for this picture ![http://i.stack.imgur.com/0GFCv.png](http://i.stack.imgur.com/opzqB.png) I want to find the green point (center of outbound box). ![http://i.stack.imgur.com/AcMp5.png](http://i.stack.imgur.com/HftUl.png)


Customize your FrameTicks in a MATLAB way

The figure below is made by MATLAB. However, the scientific form of numbers in `FrameTicks` that how MATLAB deals with is quite different from that of _Mathematica._ ![MATLAB plots with nice ticks](http://i.stack.imgur.com/9YfBV.png) By default, I plot the second figure based on the same data in a _Mathematica_ way. ![Mathematica plots](http://i.stack.imgur.com/Tan6p.png) However, what is messy in the second figure is the overused ZERO in the vertical axis. So my first question is how to transform the number on the `FrameTicks` into some suitable scientific form. Well, after we transform them into scientific form, my second question arises: how to make the plot in the MATLAB way? For example, if one of the frame ticks is 2*10^-4, I hope to put only 2 on the vertical axis and 10^-4 on the left top of the figure (Like the first one in the second column in the first figure). I think we can test the idea based on               Plot[10^5 * Sin[x], {x, 0, 10}, Frame -> True]      I think I can solve this problem in a stupid way: multiply/divide every number on the frame ticks by some number _x_ , then place a graphics object of text which writes _x_ to the left top side of the figure. But really what I need is a general way to do that. Any help will be appreciated.


How do I extract the contents of a selected cell as plain text?

My aim is to extract the contents of an Input cells as plain text. Ideally I would like to be able to select one or more Input cells and press a button which would then extract the text from these cells as a string and assign it to a variable. However, this turns out to be harder than it seems (to me at least). One way which was suggested in a chat conversation was to copy the cell as plain text by doing something like this               Button["Set x to selection",       FrontEndTokenExecute[SelectedNotebook[], "CopySpecial", "PlainText"];       x = (NotebookGet@ClipboardNotebook[])[[1, 1, 1]]       ]      This seems to work; for example, if I type this into an input cell, select the cell, and press the button               a + b == c;     d = "x";      then `x` is set to the string `"a+b==c;\nd=\"x\";"` which is what I want. The only downside of this method as far as I can tell is that it destroys the clipboard. To preserve the clipboard I tried using `NotebookRead` instead to copy the contents but I only got that to work if I changed the display form of the selected cell to `"TextForm"` first, e.g.               Button["Set x to selection 2",      Module[{tmpnb, nb},       nb = SelectedNotebook[];       tmpnb = CreateDocument[WindowSelected -> False];       NotebookWrite[tmpnb, NotebookRead[nb], All];        FrontEndTokenExecute[tmpnb, "SelectionDisplayAs", "TextForm"];       SelectionMove[tmpnb, All, CellContents];       x = ToString[NotebookRead[tmpnb]];       NotebookClose[tmpnb]]]       Of course the downside of this approach is that it creates a temporary notebook every time I press the button. **Question** Both methods seem to do their job, but they both rely on the FrontEnd manipulating the contents of the selected cell before being able to extract the string. This made me wonder if there is an easier way to get the same result.


How to make the plot from geotiff format

I have a `"GeoTIFF"` format map, and I have imported it into Mathematica, then I used the `Graphics` to plot a point on the map. But I don't know how to plot the X_axle and Y_axle?               tif = Import["E:\\Yan.tif", "Graphics"];     Graphics[{First@tif, PointSize[0.05],        Point[{400, 250}, VertexColors -> Red]}]      And I tried the command               Import["E:\\Yan.tif", {"GeoTIFF", "SpatialRange"}]


Finding the intersection of two date lists

I've got two lists that look like this               list1={{"1/01/2010 6:15", 0.0565625}, {"11/06/2010 0:15",0}, {"11/06/2010 0:30", 0},{"11/06/2010 0:45",0}, {"11/06/2010 1:00", 0}}          list2={{"01/01/2010 06:15", 0.04375}, {"01/01/2010 06:30",0.04375}, {"01/01/2010 06:45", 0.04375}, {"01/01/2010 07:00",0.04375}, {"01/01/2010 07:15", 0.04375}}      What I want to do is create a list that looks like this;               list3={{"1/01/2010 6:15", 0.0565625, 0.04375},{{"01/01/2010 06:30",,0.04375},......}      Either list may have gaps in it. It's not important that all the gaps be filled (if the date is missing from both list1&2 then it can be missing from list3). What is important is that it's fast, the data set is about 100,000 records.


Make legend same height as plot

One common style for density plots is to have a vertical legend that is the same height as the plot itself. Some example density plots from Google Image search: ![Density plots from Google Image search](http://i.stack.imgur.com/ClayN.jpg) How can we make DensityPlots with legends whose height matches the height of the plot? By default the heights are different:               DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3},       PlotLegends -> Automatic]      ![Default DensityPlot with legend](http://i.stack.imgur.com/n4ona.png)


can the color in MeshStyle be specified by a ColorFunction, such as "SunsetColors" for example. If so, what is the correct syntax?

This is an example given in Help:               Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, MeshStyle -> Gray]      Could this be changed to something like               Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, MeshStyle -> "SunsetColors"]      The above obviously does not work, but is there a way to modify syntax so that it can be done?


Inversion algorithm for Laplace Domain

Skin = 1;     ET = 0.3;     φ = 0.1;     ω = 10^-6;     τ = 0;     Cd = 100;          PD[s_] = (BesselK[0, Sqrt[s]] + Sqrt[s] BesselK[1, Sqrt[s]]               {Skin - (ET φ I ω Exp[s I ω τ])/(s - I ω)})/(Cd s^2 (BesselK[0, Sqrt[s]] +                   Skin Sqrt[s] BesselK[1, Sqrt[s]]) + s Sqrt[s] BesselK[1, Sqrt[s]]);           tmax = 25000000;     T = 4*tmax;     e = 10^-8;     a = -(Log[e]/(2 T));          ad[tmax_, alpha_, tol_] := ad[tmax, alpha, tol] =         alpha - Log[tol]/(8 tmax) // N          cd[PD_, s_, tmax_, alpha_, tol, k_] := PD /. s -> ad[tmax, alpha, tol] +             I Pi k/(4 tmax) // N          sd[F_, s_, t_, j_, tmax_, alpha_: 0, tol_: 0.00000001] :=                     Inv[PD, s, t, j, tmax, alpha, tol] =             Exp[ad[tmax, alpha, tol] t]/(4 tmax) * Sum[Re[cd[PD, s, tmax, alpha, tol, k]]             Cos[k Pi t/(4 tmax)] - Im[cd[PD, s, tmax, alpha, tol, k]] Sin[k Pi t/(4 tmax)],             {k, 0, j}] // N          LogLogPlot[{PD[y], y*PD'[y]}, {y, 10, 1000000000},                 PlotRange -> {0.01, 100}, PlotStyle -> {{Black}, {Dashed, Blue}},                 Frame -> True, FrameLabel -> {"tD", "PD e tD*PD'"},                 BaseStyle -> {FontSize -> 12}]`      I'm trying to invert an equation in the Laplace domain using Stehfest algorithm. It works very fine, but since I'm trying to represent a sinusoidal behaviour I need a different algorithm that makes use of the Fourier Series. Does anyone have experience in programming such algorithms? Here, I'm trying to use Durbin-Crump Method, but no success so far...


Mathematica Workspace

> **Possible Duplicate:**   >  Is there equivalence within Mathematica to view currently used variables > similar to Matlab? In Matlab, I can type:               >> whos     >> x=4          x =               4          >> y=7          y =               7          >> whos       Name      Size            Bytes  Class     Attributes            x         1x1                 8  double                     y         1x1                 8  double         And I get a list of all variables in my workspace. Is there something similar in Mathematica so I know what variables to Clear?


Is it possible to embed a Youtube video in a CDF?

I'd like to embed a Youtube tutorial video inside a CDF. I'm guessing this is not possible as my search for how to do this has been in vain. I'm imagining an embedded Youtube video like one sees on a blog.


Find equal elements on a list

Consider the following code to produce the sequence $x_1,\ldots,x_{n+1}$ where $x_i=11\cdots1$ ($i$ digits 1). Is there an easier way to do this?               n = 7     X = Table[Sum[10^i, {i, 0, k - 1}], {k, 1, n + 1}]     R = Table[Mod[X[[k]], n], {k, 1, n + 1}]     X      R      Also, the code defines the list `R` of remainders on division of $x_i$ by $n$. The output of `R` is `{1, 4, 6, 5, 2, 0, 1, 4}`. **I'd like to do the following:** determine the indexes producing the first two equal elements of `R` (for example, since `R[[1]]=R[[7]]` I'd like to do some math with `X[[1]]` and `X[[7]]`).


Image Processing: Concrete test blocks

**Background** Concrete is mixture of aggregates and cement. Aggregates are composed of different sizes and colors. Core samples are taken by drilling in order to test the strength of concrete . They are usually in cylindrical form. See the image below. I want to detect the circle of the cylinder and aggregates as well as calculate the areas. **Question** ![concrete blocks](http://i.stack.imgur.com/tNcYK.jpg) I have many images similar to this one. May Questions are :   1. How can I remove the background and detect the circle?    2. How can I find the shape of aggregates calculate the areas? PS: I'm well aware of related Questions on this site but most of them end up with failure. **Edit 1** Thank you shrx for the first part of the Q Code               img= Import["http://i.stack.imgur.com/tNcYK.jpg"]          circles = SelectComponents[MorphologicalComponents[         LaplacianGaussianFilter[          ColorNegate@DeleteSmallComponents@Closing[EdgeDetect[i, 3], 11],           2], 0.0056`],        "Count", # > 600 &];     cm = ComponentMeasurements[circles, "MeanCentroidDistance"]     ct = 1 /. ComponentMeasurements[FillingTransform@i1, "Centroid"];     Show[i, Graphics[{Thick, Red, Circle[ct, cm[[1, 2]]]}]]      ![enter image description here](http://i.stack.imgur.com/rMl49.png)


Converting datasets to nested lists

Imagine the Shipments relation:               SP = Dataset[{     <|"SNO" -> "S1", "PNO" -> "P1", "QTY" -> 300|>,     <|"SNO" -> "S1", "PNO" -> "P2", "QTY" -> 200|>,     <|"SNO" -> "S1", "PNO" -> "P3", "QTY" -> 400|>,     <|"SNO" -> "S1", "PNO" -> "P4", "QTY" -> 200|>,     <|"SNO" -> "S1", "PNO" -> "P5", "QTY" -> 100|>,     <|"SNO" -> "S1", "PNO" -> "P6", "QTY" -> 100|>,     <|"SNO" -> "S2", "PNO" -> "P1", "QTY" -> 300|>,     <|"SNO" -> "S2", "PNO" -> "P2", "QTY" -> 400|>,     <|"SNO" -> "S3", "PNO" -> "P2", "QTY" -> 200|>,     <|"SNO" -> "S4", "PNO" -> "P2", "QTY" -> 200|>,     <|"SNO" -> "S4", "PNO" -> "P4", "QTY" -> 300|>,     <|"SNO" -> "S4", "PNO" -> "P5", "QTY" -> 400|>     }];      which is then Grouped By shipper (SNO):               grouped=SP[GroupBy[Key["SNO"]]]      What is a concise way to convert this into a List of Lists of Lists that contain only the Values? (I suppose I am trying to reproduce Gather-like behavior with datasets.) (Thanks Murta:) I hope to see:                {      {{"P1",300},       {"P2",200},       {"P3",400},       {"P4",200},       {"P5",100}},      {{"P1",300},       {"P2",400}},      {{"P2",200}},      {{"P2",200},       {"P4",300},       {"P5",400}}                 }      Something like:                {      {"S1",{{"P1",300},             {"P2",200},             {"P3",400},             {"P4",200},             {"P5",100}}},      {"S2",{{"P1",300},             {"P2",400}}},      {"S3",{{"P2",200}}},      {"S4",{{"P2",200},             {"P4",300},             {"P5",400}}}                 }      might be even better!


What is the syntax for selecting multiple layers in an Overlay?

From the documentation: > Overlay[{Subscript[expr, 1],Subscript[expr, 2],...},{i,j,...},s] allows > selections to be made and controls to be clicked in Subscript[expr, s]. and an example of selecting **one** layer:               Overlay[{Slider2D[], Graphics[{Opacity[.2], Disk[]}]}, All, 1]      Does anyone know what the syntax is for cases in which you want controls to be clicked in more than one layer, or all layers? I have tried:               Overlay[{Slider2D[], Graphics[{Opacity[.2], Disk[]}]}, All, All]      and               Overlay[{Slider2D[], Graphics[{Opacity[.2], Disk[]}]}, All, {1,2}]      without success.


Convert Integer to Numeric with Replacement rules

I have a long list of triples, each looking something like `{AGO, 1988, 2345.23}`. Some of these, however, have an integer in the third spot, like this: `{IND, 1993, 4345}` because of the nature of the original data. I do not want integers, because I have to Log this data eventually. So I thought I would map the following function through my list:               fn[s_List] :=  s //. {a_, b_, c_} /; IntegerQ[c] -> {a, b, N[c]}      It does not work. I want it to put "4345." in place of "4345". However, I can use the following to get a very good approximation:               fnn[s_List] :=  s //. {a_, b_, c_} /; IntegerQ[c] -> {a, b, c-.00001}      But, even though the loss of precision is not important for this project, I'd like to know why my first function does not work. I have been working with these kinds of replacement rules a lot recently, and this one seems pretty simple. Any help is very much appreciated.


Implementing CGS unit system in Mathematica 9

So I've just installed the trial version of Mathematica 9. The first noticeable feature for me is the new built-in physical units. I used `AutomaticUnits` package before, it was almost perfect except that its units aren't usable inside many other functions. But new units can be used everywhere but I can't yet figure out how to implement new units and unit systems or override an old ones. It would be great to have a way to convert units to CGS system. For reference, that's what I usually do using `AutomaticUnits`:               Needs["AutomaticUnits`"];     UnitSet["cgs"] = {Centimeter,Gram,Second,Statcoulomb,Statcoulomb/Second};     DeclareUnit["statC", Erg^(1/2) Centimeter^(1/2)];     toCGS[x_] :=       Convert[Convert[x, "cgs"] /. {"Statcoulomb" -> statC}, "cgs"]


Integrate message: can't prove Integration limits are real

I'm working on solving differential equations through Fourier series, I made a function to help me calculate the coefficients that looks like this:               bn[α_, T_, f_] := (2/T)*Integrate[f*Sin[((2*Pi*n)/T)*t], {t, α, T + α}]      And it was workng pretty well, until I tried to evaluate this:               bn[0, L, Piecewise[{{0, 0 < t < L/3}, {w, L/3 < t < 2*(L/3)}, {0, 2*(L/3) < t < L}}]]      And it gives me the error: > Integrate::pwrl: Unable to prove that integration limits {L} are real. > Adding assumptions may help. >> Any idea on what is causing/how to avoid the error? I tried using assumptions, but I guess I'm doing it wrong because it doens't help.               bn[α_, T_, f_] :=        Integrate[(2/T)*f*Sin[((2*Pi*n)/T)*t], {t, α, α + T}, Assumptions -> Element[T, Reals]]      ### Edit You mean enter the code like it is now? Sorry for the inconvenience, but the advanced help for the site sort of suggested that I used LaTeX.


ListLinePlot of data imported from an Excel file

This is a continuation of another very similar question about how to plot structured data using `ListLinePlot`. Here is a sample data imported from an Excel file:               myNIR = {{       {, 2, 4, 6, 8, 9}, {hex, 342432, 435345, 564564, 56756, 9945},       {oct, 23, 356, 565, 304, 564}, {butane, 55, 67, 76, 44, 7}     }}      The first element of the list of lists is the independent variable (frequency). To accommodate the table form, the first element of the first list is empty. The second, thirds and fourth lists are the experiment data. The first element of these lists are the names the experiment. I need to plot the three-experiment data (hex, oct, butane) against frequency (first list). I like plot to include the legend.


importing large data files with a constraint

As I have learned in this community, one way to import a hefty data files (e.g. millions of rows of {x1, y1} data) if you don't care about the individual elements (maybe just want to obtain some statistics) is to use the following:               s = OpenRead["path/test.dat"];     p = Sort[RandomSample[Range[5 10^5], 100000]];     dataTable = ((If[#1 != 1, Skip[s, Record, #1 - 1], Null];        ReadList[s, Number, 2]) &) /@ Differences[Prepend[p, 0]];      which assumes that the length of "test.dat" is 500000 and we randomly sample only 100000 items. I am now in want of a slightly different function. I'd like to take just the ordered pairs of "test.dat" such that x1 < x0 but this time take all of them and not random ones. I can do this by importing the whole table and then using something like `Cases` to get the desired range but importing the entire table is exactly what I want to avoid since the tables are very very large.


Substituting confidential tagged cells by a “content removed” cell

When producing a notebook with both code and text, I often end up with pieces of code, or even entire chapters, that I don't want to be shown on the final output. I generally hide or close them by hand, but this is time consuming, susceptible of error, and leaves big white spaces everywhere. I'm searching for a way of, by tagging a cell or entire chapter (a "group head") as confidential, on the moment of the printing its content is substituted by a "content removed" warning cell (if possible, a different warning for a list of different tags that are included in the search). Don't know if it can be managed on a style sheet specification (something that I know very little of) or just code (on a MMA theme that I also know very little), or both. I don't mind that a “cleaned” replica of my notebook is temporally generated, just for the printing formatting.


Plot an implicit function containing the correlation of two vectors

I am trying to do something like this:               ContourPlot3D[      Expand[Correlation[{0, 1, 2}, {b1, b2, b3}] == .5], {b1, -5,        5}, {b2, -5, 5}, {b3, -10, 10}]      But apparently this make the computer freeze.


How to prevent Grid from breaking the line upon export

I want to create a legend for my plots (a mixture of RegionPlots and ContourPlots). The legend should show the meanins of colors as boxes with text in them and the meaning of contours as framed number with text besides it. The following code creates an ideal legend in a notebook, **but** as soon as I export it to .eps (for inclusion in LaTeX), it screws up and starts breaking lines in the last part (the Grid inside the Grid). How can I prevent Mathematica from changing the appearance of the image upon export?               BoxSize = {6, 2};     boxImSize = 170;     legend = Grid[{{Graphics[{Thick, Lighter[Green, 0.3],        Rectangle[{0, 0}, BoxSize], Black,        Text[Style["Allowed by all", 14, Bold], Center] },        ImageSize -> boxImSize],        Graphics[{Thick, Lighter[Blue, 0.5], Rectangle[{0, 0}, BoxSize],          Black, Text[         Style["Excluded by \!\(\*SubscriptBox[\(m\), \(H\)]\)", 14,          Bold], Center] }, ImageSize -> boxImSize],        Graphics[{Thick, Darker[Orange, 0.3], Rectangle[{0, 0}, BoxSize],          Black, Text[         Style["Excluded by\n \[Mu] \[RightArrow] e \[Gamma]", 14,          Bold], Center] }, ImageSize -> boxImSize],      Graphics[{Thick, Red, Rectangle[{0, 0}, BoxSize], Black,          Text[Style[         "Excluded by\n \!\(\*SubscriptBox[\(m\), \(H\)]\) and \[Mu] \     \[Rule] e \[Gamma]", 14, Bold], Center] }, ImageSize -> boxImSize],      Graphics[{Thick, GrayLevel[0.8], Rectangle[{0, 0}, BoxSize],        Black, Text[        Style["Excluded by\n SUSY constraints  ", 14, Bold],         Center] }, ImageSize -> boxImSize],     Grid[{{Invisible[""],         Text[Style[Framed[5.7], 12, Bold, Blue], Background -> White],         Text[Style[          "\!\(\*SuperscriptBox[\(10\), \(13\)]\)\[Times] B(\[Mu] \        \[Rule] e \[Gamma])", 12, Bold, Blue]],         Invisible[""]}, {Invisible[""],         Text[Style[Framed[124], 12, Bold, Black],          Background -> White],         Text[Style["\!\(\*SubscriptBox[\(m\), \(H\)]\) in GeV", 12,           Bold, Black]], Invisible[""]}}, Spacings -> 0.5,       Alignment -> {Left, Center}]     }}, Background -> None, Spacings -> 0, Alignment -> {Left, Top},      Frame -> True]


How to find the domain and range of an implicit function?

For example, we have this curve: $$ x^2 + y^2 = 1 $$ Is there a function in _Mathematica_ for finding out that the ranges for $x$ and $y$ are both `[-1, 1]`? What about implicit functions of more than `2` variables? e.g. $$ x^2 + y^2 + z = 1 $$


Mathematica memory management for large arrays

I have come across a weird phenomenon in Mathematica when dealing with large arrays. When generating a list with all the possible subsets of three elements of another list (thus having elements which are lists of 3 elements), I have observed that if you extract these elements in three separate arrays, Mathematica uses much less memory to store the data, even if the total number of elements we have is exactly the same. My question is surely naive: why does this happen? This is a minimal code that sets an example of what I'm saying, recording the memory used by Mathematica in every step:               n = 100;     memvec = {MemoryInUse[]};          timesubset = Subsets[Range[1, n], {3}];     AppendTo[memvec, MemoryInUse[]];          (*Extract all the first elements*)     t0 = timesubset[[All, 1]];     AppendTo[memvec, MemoryInUse[]];          (*Extract all the second elements*)     t1 = timesubset[[All, 2]];     AppendTo[memvec, MemoryInUse[]];          (*Extract all the third elements*)     t2 = timesubset[[All, 3]];     AppendTo[memvec, MemoryInUse[]];          Clear[timesubset];     AppendTo[memvec, MemoryInUse[]];          Clear[t1];     Clear[t2];     Clear[t0];     AppendTo[memvec, MemoryInUse[]];          ListLinePlot[memvec]      I feel there is an important concept on how is the memory managed that I am missing here.


Solution given by Wolfram Alpha but not _Mathematica_

Why will _Mathematica_ not give a soluion to `Solve[Log[x] == Log[j, Log[j, x]], j]`, but Wolfram Alpha will?


Problems specifying number of bins in Histogram

So I wanted to create a Histogram with a custom number of bins. Luckily there is a simple function for this in the form of `Histogram[data, n]` where n specifies the number of bins. There is even an example of using it in the documentation:               data = RandomVariate[NormalDistribution[0, 1], 200];     Histogram[data, 5]      Problem is that this doesn't produce a Histogram with five bins but with seven bins: ![Mathematica graphics](http://i.stack.imgur.com/sa0Ky.png) `Histogram[data, 6]`still gives seven bins: ![Mathematica graphics](http://i.stack.imgur.com/Iv6Ka.png) `Histogram[data, 7]` also gives seven bins: ![Mathematica graphics](http://i.stack.imgur.com/ptj1t.png) But `Histogram[data, 10]` gives thirteen bins: ![Mathematica graphics](http://i.stack.imgur.com/TMs7c.png) Now I am utterly confused. Is this a bug or have I misunderstood something completely? How would I go about producing a Histogram with five bins?


Using mathematical notation

Is it possible to write this function in mathematica exactly as shown, and then run the expression on a dataset? ![enter image description here](http://i.stack.imgur.com/STrvR.png) Please note I know that there are several other ways to do this. I am only interested in knowing how to compute it(if its possible) using notation that you would find in a text book.


Schroedinger eigenvalue problem in two dimensions (Harmonic Oscillator)

I read here, the discussion about how to solve one dimensional eigenvalue problem. I am wondering, how can one generalize these methods to two dimensions. For example: $-(d^2/dx^2+d^2/dy^2)u(x,y)+(x^2+y^2+xy)u(x,y)=Eu(x,y)$ or any other potentials. What about three dimensions? Is there any general procedure?


How to use local variables with indices in a Mathematica Block environment?

I have the following code:               Subscript[f, i_][x_] := Block[{a},       Subscript[a, i] = 3 x;       Subscript[a, 1]     ]      If I evaluate for example `Subscript[f,1][2]`, it evaluates to `6`. After that asking what `Subscript[a,1]` is also gives me six. However, I want `a` to be a local variable. My question: how can I define a local variable while using indices...? **Note** : the original post mentioned that evaluating `Subscript[f,1][2] = 6` would lead to the described behaviour, which just isn't true. A reasonable guess is that this was ment to mean that `Subscript[f,1][2]` was to be evaluated and it would evaluate to `6` (which it does). After that `Subscript[a,1]` will evaluate to `6` as reported.


Mathematica 10 funny bug / Easter egg?

I have no idea what is happening here. I'm using Mathematica 10. I mistyped "FriendNetwork" as "FriendsNetwork" and got a weird result: ![enter image description here](http://i.stack.imgur.com/GDRMp.png) The option "FriendsNetwork" is not even listed in the help entry for the SocialMedia function. How is that even possible? I rerun the query multiple times and it gave the same result. I checked my facebook feed and I don't see that image anywhere and I don't know of a friend who would have such a photo. Can someone try this themselves and check the result?


Can I Print to a different notebook? (within the context of the same kernel)

Please imagine a simple loop:               For[i=1,i<=100,i++,       Print[i];     ];      We can ask `Print[]` to output $(1,2,3,4,...)$ to a different notebook (in the context of the same kernel)?


Exporting 2D graphics to DXF

I have a design that I've produced in Mathematica, consisting of two sets of `Rectangle` objects. The second set is a mirror image of the first and was produced with `array2 = Scale[#, -1, {0, 0}] & /@ array1`. I'm experiencing two issues when I `Export` the `Graphics` object to DXF:   1. The second set of `Rectangle`s doesn't get exported.   2. Each `Rectangle` gets exported as a pair of triangles. Mathematica's `Graphics` output: ![Mathematica output](http://i.stack.imgur.com/jvIG9.png) What AutoCAD displays: ![AutoCAD display](http://i.stack.imgur.com/l2PL7.png) `Import`ing the DXF file back into Mathematica also shows that the bottom half is missing. I'm at a loss here - what am I doing wrong? Are either of these weird behaviours deliberate? * * * Edit: Here is a snippet of my code. It generates the design for a surface acoustic wave resonator. This consists of two transducers next to two gratings, each made up of metal strips, separated by a certain number of wavelengths.               l = 2; (* wavelength in \[Mu]m *)          d = 25.5; (* cavity length in wavelengths *)     (* NB this is the distance between the fronts of the transducers *)     vRatio = 1; (* how much faster the speed of sound is in the centre \     section *)          nTransducer = 25; (* number of finger pairs in the transducers *)     nGrating = 370; (* number of fingers in the grating *)     (* NB 2 fingers == 1 wavelength *)          fingerLength = 25; (* finger length in wavelengths *)     (* NB finger length is measured from inside edge of the bus-bar *)          SetDirectory[NotebookDirectory[]];     filePath = "2um.dxf";          fingersT = Table[        Rectangle[         {-(fingerLength/2 - 1/2) l, y},         {(fingerLength/2 - 1/2) l, y + l/4}],        {y, (d*vRatio/2) l, (d*vRatio/2 + nTransducer -             1/2) l, l/2}];          (* -- the rest of the transducer is produced in a similar way -- *)          transducer =        Join[fingersT, lSquaresTOut, rSquaresTOut, lSquaresTIn,          rSquaresTIn] ~Append~ lBarT ~Append~ rBarT;          (* -- a grating is produced above the transducer in the same fashion -- *)          (* This line originally read: array1 = transducer ~Join~ grating; *)     array1 = fingersT;     array2 = Scale[#, -1, {0, 0}] & /@ array1;          diagram = Graphics[array1 ~Join~ array2]     Export[filePath, diagram, "DXF"];


Get unique values for integration limits

For an multidimensional integration I want to build up the integration limits with the following code. (the length of vars is also variable)               x = 0.223144;     vars = {x1, x2, x3};     Table[{vars[[k]], -x/(1 + i), x/(1 + i)}, {k, 1, 3}, {i, 0, 2}]      which gives me:               {{{x1, -0.223144, 0.223144}, {x1, -0.111572, 0.111572}, {x1, -0.0743812, 0.0743812}}, {{x2, -0.223144,0.223144}, {x2, -0.111572, 0.111572}, {x2, -0.0743812,0.0743812}}, {{x3, -0.223144, 0.223144}, {x3, -0.111572,0.111572}, {x3, -0.0743812, 0.0743812}}}      As I see it, it makes an outer product. But I just want the the following integration variables with the corresponding limits.               {{x1, -0.223144, 0.223144}, {x2, -0.111572, 0.111572},{x3, -0.0743812, 0.0743812}}      How would I achieve that? Thank you


func::usage needs to be run twice?

There is an annoying problem that I can't figure out why it's happening. I have defined a `usage` for a my function `tensorA`: ![definition](http://i.stack.imgur.com/60ybe.png) Then when I run `?tensorA` I get gibberish: ![enter image description here](http://i.stack.imgur.com/w11vI.png) But if I run the same code a second time, it works as intended. ![enter image description here](http://i.stack.imgur.com/4Bwk5.png) Is this problem known? Why do I need to run the `?tensorA` twice for it to display properly? What can I do to fix this?


How to place cdf file in Microsoft Word, Powerpoint or in interactive PDF file?

I would like to create a presentation for my lecture in which I would use Mathematica CDF files. Let's say I want to have such interactive content:               Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}]      How can I place it in Word, Powerpoint or in Adobe PDF (I can use Adobe Acrobat) so it is usable. Usable - means not showed as an icon. Thanks in advance and Regards Misery


Descriptive statistics of two events

I am trying to use the descriptive statistics feature of Mathematica to answer the following question: suppose I have two events, A and B, whose occurrence is described by a normal distribution around time $t_A$ and $t_B$ (with moments $\sigma_A$ and $\sigma_B$). What is the probability that, at a given time $t$, both events have occurred? I have tried to define distributions and then use them in a construct of the form `Probability[A && B, …]`, but it is clear from the documentation that `Probability` is not supposed to be used that way. * * * PS: I'm not so much interested in the mathematical solution (I have to read up on that subject, I'm really bad in statistics), rather in the way I can get Mathematica to solve this issue without me doing the maths :)


Extracting values with multiple keys

I want to extract sorted data from a huge database based upon two (or more) keys in a very timely manner. Here is a reproducible toy example for two keys only:               n = 10^5;     keys = RandomInteger[{1, 100}, n];     vals = RandomReal[{0, 1}, n];          data = Transpose[{keys, vals}];      The fastest "traditional" way I' ve found:               result1 = Sort @ Cases[data, {25 | 73, r_} :> r];      Much much faster is a **V10** solution:               assoc = Merge[Association /@ Rule @@@ data, Identity];      (I use `Merge`to allow for duplicate keys, and the time cost of getting `assoc` is not important to me).               result2 = Sort[assoc[25] ~ Join ~ assoc[73]];          result1 == result2      > True Speed comparison:               Do[Sort @ Cases[data, {25 | 73, r_} :> r], {100}]; // AbsoluteTiming // First      > 2.017115               Do[Sort[assoc[25] ~ Join ~ assoc[73]], {100}]; // AbsoluteTiming // First      > 0.030002 Certainly one reason to upgrade, but two or more questions remain: (a) Could this code be improved ? (b) And, passing to `n = 10^6`, `result1` still works, but `result2` runs forever and has to be aborted.


Why are some Buttons not working in CDFPlayer?

I have two `Button`s within a single panel. My problem is that after deploying that panel, the second `Button` is not working in the `CDFPlayer`. But it works in `Notebook`. Why is it not working in the CDFPlayer?               Panel[Row[{Button["Speak", Speak["HI"]],      Button["Speak2", (CreateDialog[     Button["Ok", Speak["infratab"], Method -> "Queued"]];),      Method -> "Queued"]}]]


How to import numbers or protected signs from .txt?

I'm new here, so please apologize any formal errors. I stumbled upon a somewhat simple problem. I want to import plain numbers or protected signs like `Pi`, `Cos`, `Sin` from .txt files. Somehow Mathematica does not understand that the read-in Pi is the protected `Pi` (= 3.14...). Even more simple examples seem not to work, e.g. reading in the number 5 from a .txt-file does not allow for using that 5 for further calculations. My approach was:   1. Saving the sign/number in a txt file. E.g. Pi.txt contains just "Pi" (without quotation marks).   2. My Mathematica code is               SetDirectory["C:\\Code"];     x := Import["Pi.txt"]     f[t_] = Sin[t];     Evaluate[f[x]]      Thank you for your help.


How to render a 3D tubular graphics from a 2D image path

Question: Is it possible to create a tubular 3D image like Extruding along a path using "Tube" function in mathematica for following images? Image (1) ![enter image description here](http://i.stack.imgur.com/nEiPq.png) Image (2) ![enter image description here](http://i.stack.imgur.com/70QiT.png) Thanks * * * I have been playing with previous answers: 1) Extruding along a path 2) Trying to extrude a 3D image from a binary 2D image 3) How to convert a 2D image into a 3D graphics? I want to generate image like first one. Here I tried RegionPlot3D: ![enter image description here](http://i.stack.imgur.com/o26DL.png) I want to map the image to 3D tube which has image cross section.


Proving inequalities with Mathematica

Question summary: I would like to learn some tips and tricks on how to **prove** inequalities with _Mathematica_. I'm studying various inequalities in triangle that have the form $R+ar + bs\geq 0$, where $R$ is a circumcircle radius, $r$ is an incircle radius and $s$ is a semiperimeter of a triangle.               ClearAll[R, r, s, isTriangle];     R[x_, y_, z_] := (      x y z)/Sqrt[(x + y - z) (x - y + z) (-x + y + z) (x + y + z)];     r[x_, y_, z_] :=        1/2 Sqrt[((x + y - z) (x - y + z) (-x + y + z))/(x + y + z)];     s[x_, y_, z_] := (x + y + z)/2;     isTriangle := 1 >= x > 0 && 1 >= y > 0 && x + y > 1;      I normalize the longest side $z=1$ to simplify the calculation. `isTriangle` is a condition that there is a triangle with sides $1,x,y$. I want to prove the following inequalities: $s-3\sqrt{3}r\geq0$ and $-\frac s2+(-2+3\sqrt{3}/2)r+R\geq 0$ for all triangles. I can easily _check_ that both inequalities are true with the following code:               FindMinimum[{s[1, x, y] - 3 Sqrt[3] r[1, x, y], isTriangle}, {x, y}]      (returns `{1.26714*10^-6, {x -> 0.998875, y -> 0.998875}}`), i.e. the minimum is $0$);               Resolve[ForAll[{x, y}, isTriangle,        s[1, x, y] - 3 Sqrt[3] r[1, x, y] >= 0]]     (* True *)      (checks that inequality holds for all triangles);               FindMinimum[{-s[1, x, y]/2 + (-2 + 3 Sqrt[3]/2) r[1, x, y] +         R[1, x, y], isTriangle}, {x, y}]      (returns `{9.01882*10^-7, {x -> 0.996601, y -> 0.996601}}`, i.e. the minimum is $0$);               Resolve[ForAll[{x, y},        isTriangle, -s[1, x, y]/2 + (-2 + 3 Sqrt[3]/2) r[1, x, y] +          R[1, x, y] >= 0]]     (* True *)      (checks that inequality holds for all triangles, but takes some time). However, I want to find a way to **prove** them, e.g. so that a human who doesn't trust _Mathematica_ can check that they are always true. I would appreciate some _general_ tips and tricks; e.g. it may be possible to find proves for these particular examples, but I would like to know some (heuristic) methods that could work for some other inequalities, too. Thanks you very much for your time!