How to solve issue with exporting / importing data to and from Excel

Background ( simplified ): When I export data to Excel like                Export["voorbeeld.xls", {{{0.5, 0.166667}, {0.666667,      0.166667}, {0.166667, 0.333333}, {0.333333, 0.333333}, {0.5,      0.333333}, {0.666667, 0.333333}, {0.833333, 0.333333}, {0.166667,      0.5}, {0.333333, 0.5}, {0.5, 0.5}, {0.666667, 0.5}, {0.833333,      0.5}, {0.5, 0.666667}, {0.666667, 0.666667}}, {{1., 2., 6.,      5.}, {3., 4., 9., 8.}, {4., 5., 10., 9.}, {5., 6., 11., 10.}, {6.,      7., 12., 11.}, {10., 11., 14.,      13.}}, {{RGBColor[0.9308155947203784, 0.9308155947203784,       0.9308155947203784]}, {RGBColor[1, 0, 0]},    RGBColor[0., 1.,      0.14062714579995422], {RGBColor[1., 0.11317616540779736,       0.000015259021896696422]}, {RGBColor[1., 0.9651483939879454,       0.38461890592813003]}, {RGBColor[0.9685511558709087,       0.9685511558709087, 0.9685511558709087]}}}]      I would expect the data to be inserted into cells but Excels uses just 3 cells. When I imported the same data the three main lists were stored in seperate sheets in Excel. Example 2:               list3={{RGBColor[0.9308155947203784`,0.9308155947203784`,0.9308155947203784`]},      {RGBColor[1,0,0]},RGBColor[0.`,1.`,0.14062714579995422`],       {RGBColor[1.`,0.11317616540779736`,0.000015259021896696422`]},      {RGBColor[1.`,0.9651483939879454`,0.38461890592813003`]},      {RGBColor[0.9685511558709087`,0.9685511558709087`,0.9685511558709087`]}}      Export["voorbeeld.xls",list3] creates a column with RGB values. Export["voorbeeld.xls",{list3}] creates one cell. Does this help? **Question: is there a solution / workaround for this issue?** Example 2:                list3={{RGBColor[0.9308155947203784`,0.9308155947203784`,0.9308155947203784`]},      {RGBColor[1,0,0]},RGBColor[0.`,1.`,0.14062714579995422`],{RGBColor[1.`,0.11317616540779736`,0.000015259021896696422`]},{RGBColor[1.`,0.9651483939879454`,0.38461890592813003`]},{RGBColor[0.9685511558709087`,0.9685511558709087`,0.9685511558709087`]}}            Export["voorbeeld.xls",list3] creates a column with RGB values.       Export["voorbeeld.xls",{list3}] creates one cell.       Does this help?


Problem on Consecutive Sequence Sums that are Squares

Here is a seemingly simple Problem: I have two natural numbers n and m, n < m such that S1:= n +...+ m is a square and also S2:= n +...+ m + (m+1) is a square. Problem a) : Find n and m. You find a solution by looking at my demonstration "Sequence Sums that are Squares". Problem b) : Now here is the hard part: find a second solution (maybe with a Mathematica program?) or prove that no other solution exists.


Define function using variable list

I have a list of variables `variables={a,b}` and a list with values `values={1,2}`. I'd like to define a function using the variables in `variables` like so:               f=Function[variables,2a+b];      Then, I'd like to call it in a way like               result=f@@values        or               result=f@@variables/.(Rule@@@Transpose@{variables,values})      or something similar. Is there a way to create a function where the names of the variables are in a given list?


How can I get TracePrint to treat certain functions as atomic?

Consider the following example:               In[1]:= f[x_]:=x+1;g[x_]:=f[2x]          In[2]:= TracePrint[g[1]]      g[1]       g       1      f[2 1]       f       2 1        Times        2        1       2      f[2]      2 + 1       Plus       2       1      3          Out[2]= 3      So far, so good. However I'd now like to instruct TracePrint to treat evaluation of `f` as atomic, that is not to print the intermediate steps of evaluating `f[2]`, so that the next line after `f[2]` would be `3` (but without excluding any other lines). My first idea was to just make `f` read protected:               In[3]:= SetAttributes[f,ReadProtected]          In[4]:= TracePrint[g[1]]      g[1]       g       1      f[2 1]       f       2 1        Times        2        1       2      f[2]      2 + 1       Plus       2       1      3          Out[4]= 3      As you can see, the inner working of `f` is still traced. However the attribute is otherwise honoured:               In[5]:= ?f     Global`f          Attributes[f] = {ReadProtected}      Another thing which does not work is               TracePrint[g[1],Except[_f]]      which again gives the complete trace. So how do I instruct `TracePrint` to treat the function `f` as atomic?


Functional derivatives in Feynman Path Integral

Is there any package that can simplify functional derivatives in path integrals? For instance the expression (integrate over, $x,y,z,u,v,r,s$): $$\int\delta_{J_{A}^x}\delta_{J_{B}^x}\delta_{J_{B}^x}\int{J_{B}^y}\Delta^{yz}_B{J_{B}^z}\int{J_{B}^u}\Delta^{uv}_B{J_{B}^v}\int{J_{A}^r}\Delta^{rs}_A{J_{A}^s},$$ where $$\delta_{J_{A}^x}:= \frac{\delta}{\delta {J_{A}^x}}$$ and $$\Delta^{rs}_A:=\Delta_A(r-s).$$


Taking averages at certain intervals

I am trying to take averages of a large two dimensional array at certain intervals. For example, for the first row, I want to take K averages of 500 values. Here is what I am trying               Do[Data[[i, k]] =      Mean[Data[[i]][[j + 1 ;; j + 500, 2 ]] ], {i,      8}, {j, 0,      100*5*200, 500}, {k, 1,     200} ]*)


Animate the scattering of a Wave Packet

I know mathematica is probably not the best choice for intense numerical integration, but its the only software I know. I would like to create an animation (not real-time, but pre-render the frames) of a Gaussian wave-packet scattering against a spherical square-well, whose stationary states are known. Basically, I need to carry out the following integral: $$\Psi(\vec{x},t)=\int\frac{d^3\mathbf{k}}{\sqrt{(2\pi)^3}}\tilde{f}(\mathbf{k}) \psi_\mathbf{k}(\vec{x})\,e^{-i E(\mathbf{k})t}$$ where $\tilde{f}(\mathbf{k})=\exp(-\frac{(\mathbf{k}-\mathbf{k}_0)^2}{2(\Delta k)^2}-i \mathbf{k}.\vec{x}_0)$ is the Gaussian wavepacket in Fourier space, and $E(\mathbf{k})$ is a very simple function quadratic in $\mathbf{k}$. The integral needs to be done at several different times, and then compiled together to form an animation (this last step I know how to do). Is there a good reference that I can look up that will accomplish my task?


Make the linked images show well?

Cell[TextData[{ "(16) ", ButtonBox["[images]",  BaseStyle->"Hyperlink",  ButtonData->{"http://i.stack.imgur.com/gHWby.png", None}]}], "Text"]      After click the link, then open one notebook, however it's in bad encoding? ![enter image description here](http://i.stack.imgur.com/tPE4r.png) My `$CharacterEncoding` is `CP936`, I'm not sure whether this is related, I'm on Windows, maybe someone's environment will show the linked image good?


Move variable to one side of the equation

Say if I have a formula like so:               a1*a2*a3^(a4 + 1)*(1 - E^(a5*a6/a3^a4/a2)) == 0      How do I move a3 to the right? I've tried to follow other examples here on stack exchange but couldn't find anything that worked on this kind of formula. Using Solve[] causes this error: > Solve::nsmet: This system cannot be solved with the methods available to > Solve.


How to get data from For loops to plot it?

How can I get data from `For` loops to use in `ListStreamDensityPlot`? I tried `AppendTo`, but it didn't work. I probably did it wrong.               Clear[a, x, y, z, m, n, o, Bx, By, Bz]     a = 0.1 (*amplitude*)     z = 0  (*ploting on different heights*)     For[i = 1; x = m, i < 6, i++, x = 2 Pi/4*(i - 1);         For[j = 1; y = n, j < 7, j++, y = -3 + (j - 1);           {Bx = NIntegrate[a*z*Cos[t]/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -              3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2]Sin[t]) a),              {t, -Infinity, Infinity}, AccuracyGoal -> 20,MaxRecursion -> 15];            By = NIntegrate[-z/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -              3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2]Sin[t]) a),              {t, -Infinity, Infinity}, AccuracyGoal -> 20, MaxRecursion -> 15];            Bz = NIntegrate[(y + a*(t*Cos[t] - x*Cos[t] - Sin[t]))/             ((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -              3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2]Sin[t]) a),              {t, -Infinity, Infinity}, AccuracyGoal -> 20, MaxRecursion -> 15]};        ]      ]     ListStreamDensityPlot[{x, y}, {Bx, By, Bz}]      I only get > `[out]=ListStreamDensityPlot[{2 \[Pi], 2}, {0., 0., 1.00294}]` Thanks in advance. EDIT: With the help of Verbeia I can now make the plot. I would like to get something like this http://i.stack.imgur.com/3ixqI.png My wire is a different one than the above though. Mine is a sinusoid. Is ListVectorDensityPlot the right plot to get plots like the ones above?               a = 0.1     x = Pi/2          data = Table[With[{y = -1 + 0.1 (i - 1),         z = -1 + 0.1 (j - 1)}, {{NIntegrate[ a*z*Cos[t]/((t^2 - 2 t x + x^2 +          y^2 + z^2)^(3/2) - 3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[t]) a),          {t, -Infinity, Infinity}, AccuracyGoal -> 20,  MaxRecursion -> 20],          NIntegrate[-z/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -           3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[t]) a),           {t, -Infinity,Infinity}, AccuracyGoal -> 20, MaxRecursion -> 20]},          NIntegrate[(y +  a*(t*Cos[t] - x*Cos[t] - Sin[t]))/((t^2 - 2 t x + x^2 + y^2 +             z^2)^(3/2) - 3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[t]) a),       {t, -Infinity, Infinity}, AccuracyGoal -> 20, MaxRecursion -> 20]}],       {i, 1, 21}, {j, 1, 21}]          ListVectorDensityPlot[data, DataRange -> {{-1, 1}, {-1, 1}}]      I get this graph. http://i.stack.imgur.com/YvqyD.jpg The field should be rotational. Is the problem that integrals don't converge? How can I improve the convergence of integrals then? I doubt upping max recursions to 80 would be smart because it would increase the process time a lot. It takes a couple of minutes anyway.


How to read data file quickly?

I have a tab separated value file with 10 million rows each of which has three tab separated values. The first value is a string, the second an integer, and the third another string. How to read efficiently (in terms of timing and memory footprint) the $n^{th}$ to $(n+100)^{th}$ rows of the file into Mathematica as               {         {_String, _Integer, _String},         ...     }      ?


Lossless TIFF or PNG export

I'd like to export an output from MatrixPlot[], however, the output file size seems to depend on my specification of the ImageSize -> {..., ...}. How might I export a TIFF with all of the data in the $N \times M$ matrix being plotted? Presumably one could set the ImageSize to reflect the matrix dimensions, however, how would one appropriately pad for the axes and axes labels? The command I'm using for MatrixPlot[] export is:               Export["MatrixExportFileExample.tiff",MatrixPlot[...]];


FindMinimum gives wrong solutions inside a loop

I have a density function $\rho(r,z)$ and I want to calculate the minimum distance $d_{min} = \sqrt{r^2 + z^2}$ from the center (0,0) in which $\rho$ becomes negative. The easiest way is to find where $\rho = 0$, since for all greater distances is always $\rho < 0$. In my system, there is a variable parameter $\delta$ which takes values in the interval [0, 1]. So, I want to monitor the evolution of $d_{min}$ as a function of $\delta$. The corresponding Mathematica code is the following:               Clear["Global`*"];     Off[FindMinimum::eit];          Vg = v0^2/2*Log[r^2 + (1 + δ)*(a + Sqrt[h^2 + b*z^2])^2 + cb^2];      Vn = (-G*Mn)/Sqrt[r^2 + z^2 + cn^2];      Vh = (-G*Mh)/Sqrt[r^2 + z^2 + ch^2];     Vt = Vg + Vn + Vh;     Vr = D[Vt, r];     Vz = D[Vt, z];     Vrr = D[Vr, r];     Vzz = D[Vz, z];     ρ = 2.325/(4*π*100)*(Vrr + Vr/r + Vzz);          G = 1;     v0 = 25; a = 3; h = 0.12; b = 1.5; cb = 2.5;     Mn = 400; cn = 0.25;     Mh = 10000; ch = 25;          data = {};     Do[       sol = FindMinimum[{r^2 + z^2, ρ == 0}, {r, z}];       dmin = sol[[1]];       AppendTo[data, {δ, Sqrt[dmin]}],       {δ, 0, 1, 0.05}       ]          S1 = ListPlot[data, Joined -> True, Frame -> True,      FrameLabel -> {"δ", Subscript["d", "min"]},      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Times"],      PlotStyle -> Black, ImageSize -> 600, PlotRange -> {0, 200}]      Here is the plot (S1) I get using the values obtained from the `FindMinimum` inside the `Do` loop ![plot](http://i.stack.imgur.com/WuRCh.png) We see, that there are two horizontal areas regarding the evolution of $d_{min}$, the first one when $0 \leq \delta \leq 0.3$ and the second when $0.7 \leq \delta \leq 1$. I am quite sure that for some unknown to me reason these areas are in fact wrong. In particular, when $\delta = 0$ density is always positive so, $d_{min}$ should be infinite not almost zero as indicated in the plot. In fact, the plot should be like this ![plot2](http://i.stack.imgur.com/4ibyU.png) I suspect, that there might be some issue with the precision of the calculations. Any ideas?


Undo differences in a time series

I have estimated and ARMA process in Mathematica using data which I have had to take the 2nd difference of to remove the trend. I have managed to fit a model to the detrended data but cannot work out how to undo the differences when forecasting. I can undo the difference if the set is a list of numbers but because the forecast uses temporal data I am stuck. I am fairly new to Mathematica and do not have very much coding experience so an example would appreciated. Here is a link to my dropbox with code I have done so far. https://www.dropbox.com/s/jabol8ne54h7znl/Mortality.nb Thanks for any help in advance.


FlipView Alignment problem

Here's the problem with MWE:               Framed[       FlipView[Framed /@ {100, 1}, Alignment -> Center]       ,        ImageSize -> {100, 150}, Alignment -> Center]      > ![enter image description here](http://i.stack.imgur.com/TuTVz.png) I find the following behaviour unexpected, undesired, possible bug:   * while `mouse key is pressed` now visible **next** object **left** edge is aligned to **current** object **left** edge ( _invisible alread_ ). But it should not be dependent and be aligned as the options are stated.   * after releasing the mouse key it is aligned correctly according to options. This makes horrible jumping each time. Reproduced on: WinXP V9.01 OS X V9.00 Win7 V9.01


Using Mathematica in Conjunction with LyX. Path Issues?

I am attempting make life easier, and, instead of using Mathematica at the same time that I'm using LyX (a front end for LaTeX), I was hoping that I could just use LyX and use the CAS option to do some of the simple algebraic computations that Mathematica can handle so powerfully. Of course, this has been a headache for me, as I am not very comfortable with anything Unix related. I already know where to locate Mathematica, its absolute path name, and can put it inside the "PATH prefix" that LyX demands of me. But, even doing that, I cannot get an output on the simplest of computations. ![Path for Mathematica's kernel that I entered in LyX](http://i.stack.imgur.com/i8ttr.png) Is anyone familiar with this, because I'm up against a wall. I have no idea what to do. I've been trying for hours. By the way, as is evident from the picture, I am on a Mac, I don't know if that makes a significant difference. Thanks! Edit: Here is some more information about something that I'm asking LyX to do, in a picture: ![The Option to Use Mathematica](http://i.stack.imgur.com/CdRzM.png) ![LyX Tries to Communicate with LyX and Fails to Produce an Answer to a Simple Addition](http://i.stack.imgur.com/CpKa3.png)


How do I evaluate Mathematica expressions and insert them in a LaTeX file?

I want to make use of _Mathematica_ as the backend to solve some computations used in my LaTeX input file. As I have no knowledge to make it in _Mathematica_ , I used Maxima as explained in the following steps that I got somewhere on the internet. ## Step 1 Download and install Maxima. ## Step 2 Create a batch file named `cas.bat` (for example) as follows.               rem cas.bat     echo off     set PATH=%PATH%;"C:\Program Files (x86)\Maxima-5.31.2\bin"     maxima --very-quiet -r %1 > solution.tex      Save the batch in the same directory in which your input file below exists. It is just for the sake of simplicity. ## Step 3 Create the input file named `main.tex` (for example) as follows.               % main.tex     \documentclass[preview,border=12pt,12pt]{standalone}     \usepackage{amsmath}          \def\f(#1){(#1)^2-5*(#1)+6}               \begin{document}           \section{Problem}     Evaluate $\f(x)$ for $x=\frac 1 2$.          \section{Solution}     \immediate\write18{cas "x: 1/2;tex(\f(x));"}          \input{solution}          \end{document}      ## Step 4 Compile the input file with `pdflatex -shell-escape main` and you will get a nice output as follows. ![enter image description here](http://i.stack.imgur.com/nJdTH.png) ## Questions Apparently the output of Maxima is as follows. I don't know how to make it cleaner.               solution.tex                                                 1                                            -                                            2     $${{15}\over{4}}$$                                          false      Now, my questions are   * how to implement the scenario above in _Mathematica_?   * if _Mathematica_ also produces the unnecessary texts, how to remove such texts?   * if _Mathematica_ also produces the same output format, how to obtain just `\frac{15}{4}` without `$$...$$`?


How to express trigonometric equation in terms of of given trigonometric function?

How can I express a trigonometric equation / identity in terms of a given trigonometric function? using following trigonometric identities               Sin[x]^2+Cos[x]^2==1     Sin[x]/Cos[x]==Tan[x]     Csc[x]==1/Sin[x]     Sec[x]==1/Cos[x]     Cot[x]==1/Tan[x]      Examples $$\text{convert}(\sin x,\cos)\Rightarrow \pm\sqrt{1-\cos^2(x)}$$ $$\text{convert}(\cos x,\sin)\Rightarrow \pm\sqrt{1-\sin^2(x)}$$ $$\text{convert}\left(\frac{\cos x}{\sin x},\tan\right)\Rightarrow\frac{1}{\tan x}$$               convert[eqn_,trigFunc_]:=??


Expectation of a family of random variables

I did some search here, but seems that no one asked about this. I want to define a family of independent and identically distributed random variables, $x_1,...,x_n$, and then calculates the expected value of some expressions like $\sum_{i,j=1}^nx_ix_j$. The result would be some function depending on $n$. Is there a way to do this?


Can Mathematica Handle Open Intervals? Interval complements?

**Open Intervals** Following up on this question, I was wondering whether Mma can handle open intervals. For example, the union of the intervals, $$1<x<5$$ and $$5<x<8$$ should not include the number 5. This is easy enough to do in one's head, but how can it be done, if at all, computationally? **Interval Complement** Also, is there a way to find the complement of two intervals? `IntervalComplement[int1,int2,int3]` should contain all the points in `int1` that are **not** in the other intervals. * * * Edit: Let's take Mark McClure's data as an example.               int1 = x < -2 || -1 <= x < 1 || x == 3 || 4 < x <= Pi^2;     int2 = -3 <= x < 0 || x > 1;      The intervals are shown below: ![intervals](http://i.stack.imgur.com/0xiLQ.png) The Interval Complement (drawn above in blue on the x-axis) would seem to be:               x < -3 || 0 <= x < 1


How do I dynamically change Manipulate controls?

What I'd like to be able to do is dynamically change the axis of a 3D plot inside a manipulate. For example if I have a function that has three input variables I'd like a 3D plot using 2 of the input variables and be able to manipulate the third. The part that I've had trouble with is making the axis of the plots dynamic. This is how far I've got:               axes = {{x, 0, 10}, {y, 0, 10}, {z, 0, 10}};     Manipulate[     Plot3D[fun1[x, y, z], {x, 0, 10}, {y, 0, 10}], {z, 0,      10}, {{axis1, x, "Axis 1"}, axes[[All, 1]],      PopupMenu}, {{axis2, y, "Axis 2"}, axes[[All, 1]], PopupMenu}]      which gives me ![result](http://i.stack.imgur.com/CqU0t.png) Any help would be greatly appreciated. To be more clear; The axes I would like to change are the x and y axis on the 3d plot. What I'd like to be able to do is select axis 1 = x and axis 2 = z and have the manipulate change to y.


Cross-validation of a FittedModel

Although I would know how to perform cross-validation tests after fitting a model using a function like NonLinearModelFit, I wonder if there is a way to do this providing the right parameters to the FittedModel. If not available, then I think that this would be a good way to improve FittedModel functions in future versions of Mathematica.


Implementation of a new Game of Life Rule

I need to implement a new "game of life" in Mathematica: I have three states — black, red and white. Black means go forward, red go back and white take no action. I would like to implement the outcomes in this Excel file: http://cl.ly/0s2B2M3h3M2N The code I have used is the following:               input13 = {{1, 1, 0, 0, 0}, {2, 0, 1, 2, 0}, {1, 1, 2, 1, 0}, {0, 1,          2, 1, 2}, {2, 1, 0, 1, 1}};          getNbhd[A_, i_Integer?Positive, j_Integer?Positive] :=    A[[i - 1 ;; i + 1, j - 1 ;; j + 1]];          evaluateCell[A_, i_, j_] :=   Module[{nbhd, cell = A[[i, j]], numNeighbors},            If[i == 1 || j == 1 || i == Length[A] || j == Length[A[[1]]],     Return[0]];            nbhd = getNbhd[A, i, j];   numNeighbors = Apply[Plus, Flatten[nbhd]];            If[cell == 2 && numNeighbors - 2 >= 4 ||          numNeighbors - 2 == 3 && numNeighbors - 1 <= 3 ||          numNeighbors - 2 == 2 && numNeighbors - 1 <= 2 ||          numNeighbors - 2 == 1 && numNeighbors - 1 <= 1 ||          numNeighbors - 2 == 0 && numNeighbors - 0 == 8, Return[2];     If[cell == 2 && numNeighbors - 2 == numNeighbors - 1, Return[0],          Return[1]]];            If[cell == 1 && numNeighbors - 1 >= 4 ||          numNeighbors - 1 == 3 && numNeighbors - 2 <= 3 ||          numNeighbors - 1 == 2 && numNeighbors - 2 <= 2 ||          numNeighbors - 1 == 1 && numNeighbors - 2 <= 1 ||          numNeighbors - 1 == 0 && numNeighbors - 0 == 8, Return[1];     If[cell == 1 && numNeighbors - 1 == numNeighbors - 2, Return[0],          Return[2]]];            If[cell == 0 && numNeighbors - 1 == numNeighbors - 2, Return[0];     If[cell == 0 && numNeighbors - 1 > numNeighbors - 2, Return[1],          Return[2]]];]          evaluateAll[A_] :=               Table[evaluateCell[A, i, j], {i, 1, Length[A]}, {j, 1, Length[A[[1]]]}];     makeFrames[A_, n_] :=    Map[ArrayPlot[#, Mesh -> True] &,            NestList[evaluateAll, A, n]]; animate[frames_] := ListAnimate[frames, 1,                 ControlPlacement -> Top];      But running this code I don't have anything special (the colors should be black, grey and white, but after 2 steps I have a red cell, that maybe means that no rule is set for that cell with those neighbors). Can you help me? My purpose is also to show that the rule I have made is fractal. * * * I have tried to delete the IFs from the brackets, and now I don't have any red cells, but after 2 step the figures don't change (always the same cell in the same place, they don't interact). Where is the problem??               If[ cell == 2 && numNeighbors - 2 >= 4 ||          numNeighbors - 2 == 3 && numNeighbors - 1 <= 3 ||          numNeighbors - 2 == 2 && numNeighbors - 1 <= 2 ||          numNeighbors - 2 == 1 && numNeighbors - 1 <= 1 ||          numNeighbors - 2 == 0 && numNeighbors - 0 == 8,   Return[2]];           If[ cell == 2 && numNeighbors - 2 == numNeighbors - 1, Return[0], Return[1]];          If[ cell == 1 && numNeighbors - 1 >= 4 ||          numNeighbors - 1 == 3 && numNeighbors - 2 <= 3 ||          numNeighbors - 1 == 2 && numNeighbors - 2 <= 2 ||          numNeighbors - 1 == 1 && numNeighbors - 2 <= 1 ||          numNeighbors - 1 == 0 && numNeighbors - 0 == 8,    Return[1]];          If[ cell == 1 && numNeighbors - 1 == numNeighbors - 2, Return[0],  Return[2]];          If[ cell == 0 && numNeighbors - 1 == numNeighbors - 2, Return[0]];          If[ cell == 0 && numNeighbors - 1 > numNeighbors - 2, Return[1],   Return[2]]];      @amr: I had a look to the documentation, but there are only rule already done, I want to have my rule (the one that you can see in the excel file). Few questions: 1)Should the center cell to be count in the number of neighbors? 2)Is there another way to specify a new rule? 3)Is there a way to discover if the rule that I have created is already implemented in Mathematica with an internal code? 4)May I use a BooleanFunction to do it faster? Many Thanks


Union and Intersection of intervals

I have two sets $A = \\{1 \leq x \leq 5\\}$ and $B = \\{5 \leq x \leq 8\\}$. Now I want to find the `Union` and `Intersection` of $A$ and $B$. I tried `Union[A, B]`, I got `{1 <= x <= 5, 5 <= x <= 8}` and for `Intersection[A, B]`, I got `{}`. The correct answer for $A \cup B$ is `[1, 8]` and $A \cap B$ is `{5}`. How do I tell _Mathematica_ to do that? And if $A = \\{1 < x < 5\\}$ and $B = \\{x > 5\\}$. Now I want to find the `Union` and `Intersection` of $A$ and $B$. How do I tell _Mathematica_ to do that?


Complex LogIntegral error

Going through Derbyshire's Prime Obsession & trying to take `LogIntegral` of `20^ZetaZero[1]` & comes up with a value of `1.99797 - 3.91384 I` instead of `-0.105384 + 3.14749 I` quoted in the book. Am I doing something wrong? Is it something to do with discrepancy between American definition of `LogIntegral` & European?


How to place more than one ChartLabel in a BarChart

I have the following data:               data = {{493, 416}, {1330, 1586, 1579, 1424, 1667, 1023, 665}, {1963,          428, 1797, 1832, 1697, 549, 526}, {1742, 2040, 1767, 1876, 1680,          668, 531}, {1751, 1565, 1577, 1693, 1691, 584, 523}, {1356}};          days = {{Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday,          Friday, Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday,          Friday, Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday,          Friday, Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday,          Friday, Saturday, Sunday}, {Monday}};          daysnum = {{1, 2}, {3, 4, 5, 6, 7, 8, 9}, {10, 11, 12, 13, 14, 15,          16}, {17, 18, 19, 20, 21, 22, 23}, {24, 25, 26, 27, 28, 29,          30}, {31}};      I want to plot a BarChart and to use more than one ChartLabel. I have created a handmade picture so that you can know what I mean. ![enter image description here](http://i.stack.imgur.com/gFOXC.jpg) How can I create a ChartLabel at the x-axis and at the center and the top of the BarChart?   Is it possible to color a ChartLabel according to the Bars colors?


Make a density list plot/histogram from large, pre-binned data set?

I have a large data set consisting of $\mathcal{O}(10^9)$ two-dimensional points. In order to save memory and time I have pre-binned these into a uniform grid of $500 \times 500$ bins using Fortran. When imported into Mathematica 8.0 as a table the resulting data look like: > `data = {{0.388348, 0.388349, 9},{0.388348, 0.776699, 23},...}`, where the first two items of each entry correspond to the $x$-$y$-coordinates of the upper-right-hand corner of the bin and the third is the count. ## Edit:   * For a sample of the raw data, `raw=RandomReal[1,{1000000000,2}]` is a good approximation. This is obviously unworkable.   * For the binned data: `binned=Table[{.01*Ceiling[raw[[i,1]]/.01],.01*Ceiling[raw[[i,2]]/.01],RandomInteger[1000]},{i,1,250000}]`.  I would like to plot this pre-binned data set in the form of a DensityHistogram, but my data format doesn't fit into what this function is expecting. I have reviewed a similar question for one-dimensional histograms at Histograms with pre-counted data, however I'm at a loss as to how to apply this to 2-D. I have also looked at doing > `Image[Rescale[data]]` on the raw data. However, this crashes immediately with a SIGSEGV error that has the Wolfram Support team puzzled. Consequently, I haven't gone very far down this road. ## Edit:   * I have also tried `ListDensityPlot[data,InterpolationOrder->0]`. For the full data set, Mathematica hangs for over 10 minutes, at which point it runs out of memory and the kernel shuts down. For a subset of the data, I get something more reasonable, but I would need some way to scale this up to $500^2$ data points. Making these plots seem to be something that is fairly easily done in Matplotlib, but I have already made some other plots in Mathematica and don't want to mess with different styles. I'm fairly new to Mathematica and don't have a good knowledge of all the functionality, unfortunately. So, how can I make a DensityHistogram when the bins and counts have already been calculated?


NonlinearModelFit does not find a good fit

I am trying to fit my data to the following function, $$\frac{a b t \left(\log \left(\frac{-a d t+a t-1}{a d t}\right)-2\right)}{4 (a t-1)}-c$$               data = {         {0.275, 23.85}, {0.275, 22.03}, {0.2613, 21.13}, {0.2888, 20.77}, {0.3438, 18.71},          {0.2475, 17.7}, {0.3301, 17.65}, {0.3163, 16.79}, {0.3713, 17.09}, {0.3851, 14.92},         {0.4126, 14.37}, {0.4401, 12}, {0.3851, 11.7}, {0.4813, 11.14}, {0.4538, 10.64},          {0.4676, 10.08}, {0.4951, 9.63}, {0.4951, 8.975}, {0.5639, 8.42}, {0.6601, 8.571},         {0.5914, 7.311}, {0.5088, 7.613}, {0.5088, 7.361}, {0.5776, 6.756}, {0.7564, 6.807},         {0.6464, 6.303}, {0.7426, 5.597}, {0.7014, 5.496}, {0.6189, 5.395}, {0.6464, 4.992},         {0.7289, 4.891}, {0.7426, 4.437}, {0.8802, 4.689}, {0.8664, 4.235}, {0.7976, 3.933},         {0.9077, 3.58}, {0.8664, 2.975}, {0.9627, 3.076}, {0.9352, 2.672}, {1.073, 2.773},          {1.018, 2.269}, {1.073, 1.966}, {1.155, 2.218}, {1.169, 1.714}, {1.293, 1.866},          {1.279, 1.613}, {1.306, 1.361}, {1.458, 1.563}, {1.458, 1.008}, {1.54, 1.059},          {1.623, 1.261}, {1.788, 1.059}, {1.719, 1.16}, {1.802, 0.9076}, {2.008, 0.7563},          {2.09, 0.8571}, {2.159, 1.008}, {2.242, 0.605}, {2.31, 0.6555}, {2.407, 0.8067},          {2.544, 0.8067}, {2.599, 0.6555}, {2.682, 0.4538}, {2.792, 0.7563}, {2.888, 0.4034},         {2.929, 0.7563}, {3.246, 0.5546}, {3.356, 0.4538}, {3.479, 0.4538}, {3.906, 0.4034},         {4.029, 0.4538}, {4.181, 0.3529}, {4.332, 0.2521}, {4.621, 0.2521}, {4.855, 0.2521},         {5.088, 0.3025}, {5.185, 0.3025}, {5.804, 0.3025}, {6.546, 0.3025}     };      using the following code:               nlm = NonlinearModelFit[         data,         {-c+(a b t (-2+Log[(-1+a t-a d t)/(a d t)]))/(4 (-1+a t)),a>0,b>0,c>0,d>0},         {{a,10},{b,20},{c,36},{d,0.0001}},         t     ]      It gives me following fit which is obviously not correct, $$\frac{50. t \left(\log \left(\frac{100. (9.99 t-1)}{t}\right)-2\right)}{10. t-1}-36.$$ ![Mathematica fit](http://i.stack.imgur.com/YTJ8X.jpg) I tried manually varying parameters and I can come up with the following fit, ![Fit with real data](http://i.stack.imgur.com/6kVgu.jpg) With parameters $a=10$, $b=20$, $c=36.5$, $d=0.0001$. But I want to do it using _Mathematica_ and find the right parameters for a proper fit and not just do it by trial and error.


Increase optimization processing speed

As you know, sometimes numerically solving of optimization problems takes several minutes. For this reason 2 question came up to me: 1 - When one is abort the optimization procedure, how it is possible to obtain latest updated variables? For example, consider the code below: (get data matrices from here)                     imp = Import["data_matrices.mat", "LabeledData"];           Atilt = "A0" /. imp;           Btilt = "M1" /. imp;           Ctilt = "M2" /. imp;                T = 0.01;                Xp = {{x + y*(T/2), y*T}, {1, 1}};           Arbar = Atilt + Btilt.Xp.Ctilt;                Ghat = Ctilt.Inverse[(IdentityMatrix[102] /. 1 -> z) - Arbar].Btilt;                (* Ghat = {{g11, g12},{g21, g22}} *)           g11 = Part[Ghat, 1, 1] /. z -> Exp[I w];           g12 = Part[Ghat, 1, 2] /. z -> Exp[I w];           g21 = Part[Ghat, 2, 1] /. z -> Exp[I w];           g22 = Part[Ghat, 2, 2] /. z -> Exp[I w];               (* find H_infty norm of Ghat *)          f[x_, y_, w_] := Max[{Abs[g11] + Abs[g12], Abs[g21] + Abs[g22]}];                    g[x_?NumberQ, y_?NumberQ] := NMaximize[{Evaluate[f[x, y, w]], 0 <= w <= 2.Pi}, {w, 0, 2.Pi}][[1]];               FindMinimum[{g[x, y], 0.5 <= x <= 1.7, 0.7 <= y <= 1.3}, {x, 1}, {y, 1}]      If I abort the optimization, how can I find the latest `x` and `y`? (Is this a correct question?!) 2 - How can I change the code above to increase optimization processing speed? Any ideas would be appreciated. * * * **Data matrices** : As it's obvious the `data_matrices.mat`(`A0`,`M1`,`M2`) created in MATLAB environment.                 del = 1;       h = 0.01;   % Obtain discrete-time system; transfer function and state-space realization            numG = 1; denG = conv([1 1],1);       G = tf(numG,denG);       Gd = c2d(G,h,'zoh');       [numGd,den] = tfdata(Gd,'v');        k = del/h;       denGd = conv(den,[1 zeros(1,k)]);       Gd = tf(numGd,denGd,h);            ssGd = canon(Gd,'companion');       A = ssGd.A; B = ssGd.B; C = ssGd.C;       m = size(A);            A0 = cell(2,2); Ar{1,1} = A; Ar{1,2} = zeros(m(1),1); Ar{2,1} = zeros(1,m(1)); Ar{2,2} = zeros(1,1);       Br = cell(2,2); Br{1,1} = -B; Br{1,2} = zeros(m(1),1); Br{2,1} = zeros(1,1); Br{2,2} = ones(1);       Cr = cell(2,2); Cr{1,1} = C; Cr{2,1} = zeros(1,m(1)); Cr{1,2} = zeros(1,1); Cr{2,2} = ones(1);       M1 = cell2mat(Br);       M2 = cell2mat(Cr);


Control Object Annoyance

This may seem like is a trivial annoyance, but it really is a control object "convenience of use" issue. Example: I want to use a popup menu to determine which Excel worksheet I take data from, as shown below (I'm using ExcelLink to acquire a list of worksheets from the currently active workbook): ![enter image description here](http://i.stack.imgur.com/KWJqd.png) Works great, but, if I make it an initialization cell so it will get a refreshed list and be ready to use as a control object, the next time I open the notebook and evaluate a function I get the following: ![enter image description here](http://i.stack.imgur.com/1wzj4.png) and I have to delete the old control object. Is this preventable? When I created a test case that didn't use `ExcelLink`, responding to Sjoerd's request, the problem went away: ![enter image description here](http://i.stack.imgur.com/Vz5Ht.png)


How to represent the lines that are formed by the intersection of two planes?

I am trying to set up Brillouin zone and representing the lines that are formed by the intersection of two planes is part of my step. I have tried the sample sections from the graphics guide book, but I got some wrong output. Here is the code that I copied from the guidebook:               (* to save memory *) $HistoryLength = 0;      The function `latticePointListSC` generates all lattice points that we want to take into account. It returns all lattice points inside a sphere of radius d around the origin.               latticePointListSC[d_] :=       With[{n = Ceiling[d]},          Select[           DeleteCases[             Flatten[Table[{i, j, k}, {i, -n, n}, {j, -n, n}, {k, -n, n}], 2],             (* without origin *){0, 0, 0}],           #. # <= d^2&]]          maxDist = 4;Length[latticePoints = latticePointListSC[maxDist]]          Show[Graphics3D[Cuboid[# + 0.1 {1, 1, 1},# - 0.1 {1, 1, 1}]& /@ latticePoints],       Axes -> True];      Next, we construct the perpendicular planes in the middle of the lines origin–latticePoint. We denote a plane in the form `Plane[onePointOfThePlane, listOfTwoOrthogonalDirections]`. The function `toPlane` generates a plane (head Plane) of the bisector plane formed by the point latticePoint.               toPlane[p:latticePoint_] :=       Plane[latticePoint/2,         Which[(* lattice point is on a coordinate axis *)           p[1] == 0 && p[2] == 0, {{1, 0, 0}, {0, 1, 0}},           p[1] == 0 && p[3] == 0, {{1, 0, 0}, {0, 0, 1}},           p[2] == 0 && p[3] == 0, {{0, 1, 0}, {0, 0, 1}},           (* lattice point is on a coordinate plane *)           p[1] != 0 && p[2] != 0, {#, Cross[#, p]}&[{p[2], -p[1], 0}],           p[1] != 0 && p[3] != 0, {#, Cross[#, p]}&[{p[3], 0, -p[1]}],            p[2] != 0 && [P3] != 0, {#, Cross[#, p]}&[{0, p[3], -p[2]}],           (* lattice point is in generic position *)           True, {#, Cross[#, p]}&[{p[2], -p[1], 0}]]]      We are now adding some planes that guarantee that polygons are divided along the symmetry planes. A “symmetry unit” (for brevity, just called unit in the following) is given by the following domain x>=0, y>= 0, z>= 0, z >= x, x >=y. This is 1/48 of the whole space. The list symmetrySlicingPlanes contains the planes that bound the unit.               symmetrySlicingPlanes =       Plane[{0, 0, 0}, #]& /@         {{{1, 0, 0}, {0, 1, 0}}, {{1, 0, 0}, {0, 0, 1}},{{0, 1, 0}, {0, 0, 1}},          {{0, 0, 1}, {-1, 1, 0}}, {{0, 0, 1}, {1, 1, 0}}, {{1, 0, 0}, {0, -1, 1}},           {{1, 0, 0}, {0, 1, 1}}, {{0, 1, 0}, {-1, 0, 1}},{{0, 1, 0}, {1, 0, 1}}};      Here are the symmetrySlicingPlanes. The red, slightly sticking out polygons mark one symmetry unit. We will in the following concentrate on this unit and only later in the visualization part generate all other 47 units by reflection and rotation.               With[{ε = 0.05},       Show[         Graphics3D[{           (* make polygons *)           Polygon[{#[1] - #[2, 1] - #[2, 2],                     #[1] + #[2, 1] - #[2, 2],                    #[1] + #[2, 1] + #[2, 2],                     #[1] - #[2, 1] + #[2, 2]}]& /@ symmetrySlicingPlanes,           {SurfaceColor[Hue[0]],             (* lift a bit up *)            Map[# + {ε, ε, 2ε}&,               (* boundary of the unit cone *)              {Polygon[{{0, 0, 0}, {0, 0, 1}, {1, 0, 1}}],               Polygon[{{0, 0, 0}, {0, 0, 1}, {1, 1, 1}}],               Polygon[{{0, 0, 0}, {1, 0, 1}, {1, 1, 1}}]},              {-2}]}}],          Boxed->False]]          planes =        Join[toPlane /@ latticePoints, symmetrySlicingPlanes];     Take[planes, 4]      Next, we construct representations of the lines that are formed by the intersection of two planes. The presentation of the lines will be in the form Line[onePointOfTheLine, lineDirection]. We use here a two-argument version of Line, in distinction to the built-in Line, which takes one argument. The function lineOnPlane[plane1, plane2] calculates the intersection line which is located on plane1 , induced by its intersection with the plane plane2 .               (* three equations cannot be solved for four variables *)     Off[Solve::"svars"];     lineOnPlane[Plane[p_, {dir1_, dir2_}], Plane[q_, {d1_, d2_}]] :=        Module[{eqs, sol, line, var, aux, P1, P2},         If[           (* are the planes parallel? *)           Length[DeleteCases[RowReduce[{dir1, dir2, d1, d2}], {0, 0, 0}, {1}]] == 2,            {},           (* calculate direction of the intersecting line *)           eqs = Thread[p + s dir1 + t dir2 == q + u d1 + v d2];         sol = Solve[eqs, {s, t, u, v}];         aux = p + s dir1 + t dir2 /. sol[[1]];         (* two points on the line *)         {P1, P2} = {aux /. {u -> 0, v -> 0}, aux /. {u -> 1, v -> 1}};Line[P1, P2 - P1]]]          lineOnPlane[planes[[1]], planes[[5]]]      I should have gotten > >     Line[{-2, 1, -1}, {0, -20, 10}] >   but i got > >     Line[{-2, s, -(1/2) - s/2}, {0, 0, 0}] >   instead The lines after this all got messed up beacuse of the wrong out[16] Could anyone please help? Is there a better way I could do compute the lines that are formed by the intersection of two planes?


How does one adjust ColorFunction quality independently of surface quality?

I have a function $f:\mathbb{C}\rightarrow\mathbb{C}$ which I would like to visualize by by plotting $|f|$ with `Plot3D` using $\operatorname{Arg}f$ as the `ColorFunction`. I use               DensityPlot[Arg[f[a + I b]], {a, -5, 5}, {b, -5, 5}, PlotPoints -> 35,                 WorkingPrecision -> 50, ColorFunction -> "DarkRainbow"]      and get the following: ![nice](http://i.stack.imgur.com/JF1rH.png) which looks pretty nice. However then when I use               Plot3D[Abs[f[a + I b]], {a, -5, 5}, {b, -5, 5}, PlotPoints -> 35,            WorkingPrecision -> 50,            ColorFunction -> (ColorData[{"DarkRainbow", {-\[Pi], \[Pi]}}][Arg[f[#1 + I #2]]] &),            ColorFunctionScaling -> False,            PerformanceGoal -> "Quality", Mesh -> None]      I get ![awful](http://i.stack.imgur.com/8vPU2.png) The quality of $\operatorname{Arg}f$ was fine in the DensityPlot using the same quality parameters, but it's awful when I make it a `ColorFunction`. I suppose this is because the surface mesh is made from $|f|$ in the `Plot3D` and not from $\operatorname{Arg}f$ as it was in the `DensityPlot`, and $|f|$ isn't changing very much around the important parts of $\operatorname{Arg}f$ which is why it looks so choppy and noticable. So, how do I fix this? Is there a way to give the `ColorFunction` more `PlotPoints` than the actual surface, or perhaps a different mesh? If possible I want to avoid just increasing `PlotPoints` for the overall plot, as I am happy with the quality of $|f|$ here, and it can be very slow to render as it is.


How can I modify specific key values within a dataset?

Given a dataset, is there a way to modify a value? Example               (*data = First@Import["dataset.xlsx"];*)      data= {{"Supplier", "Material", "Geography", "Quantity"}, {"Acme", "A",        "United States", 676.}, {"Acme", "B", "Argentina", 520.}, {"Acme",        "C", "Russia", 186.}, {"Acme", "D", "France", 568.}, {"Acme", "E",        "United States", 201.}, {"Beta", "A", "Argentina", 483.}, {"Beta",        "D", "Russia", 289.}, {"Beta", "F", "France", 177.}, {"Beta", "G",        "United States", 169.}, {"Beta", "H", "Argentina", 842.}, {"Gamma",        "G", "Russia", 123.}, {"Gamma", "H", "France", 709.}, {"Gamma", "I",        "United States", 579.}, {"Gamma", "J", "Argentina",        163.}, {"Gamma", "K", "Russia", 238.}, {"Delta", "A", "France",        405.}, {"Delta", "B", "United States", 411.}, {"Delta", "D",        "Argentina", 740.}, {"Delta", "H", "Russia", 322.}, {"Delta", "K",        "France", 321.}}          {fields, data} = {First[#], Rest[#]} &@data;     myDataset =        Dataset[Map[         Association, (Rule[#[[1]], #[[2]]] & /@ Transpose[{fields, #}] & /@            data)]];      Trying to update a value               myDataset[1, "Material"] = B      You'll get an error Set::write: Tag Dataset in xxx [1,Material] is Protected.


How can I remove matching sublists from my list?

I want to use `DeleteCases` (or any appropriate function) to remove elements of a list, which in turn are lists of fixed size. The rule I wish to apply is that any element of the list which already appear elsewhere in the list, up to _any number of_ -1 is to be removed. But I don't know how to do this kind of tricky pattern matching. For example, I have the following list:               myData = {{h -> 255.155, c -> 0, s -> -10000.},      {h -> -255.155, c -> 0, s -> 10000.},       {h -> 0, c -> 0, s -> 10000.},      {h -> 0, c -> 0, s -> -10000.},       {h -> 255.155, c -> 0, s -> 10000.},      {h -> -255.155, c -> 0, s -> -10000.},      {h -> -255.155, c -> 1870.83, s -> 3535.53},      {h -> 255.155, c -> -1870.83, s -> -3535.53},      {h -> 0, c -> 1870.83, s -> 3535.53},       {h -> 0, c -> -1870.83, s -> -3535.53},      {h -> 255.155, c -> 1870.83, s -> 3535.53},      {h -> -255.155, c -> -1870.83, s -> -3535.53},      {h -> 255.155, c -> -4000., s -> 0},      {h -> -255.155, c -> 4000., s -> 0},      {h -> 0, c -> 4000., s -> 0},       {h -> 0, c -> -4000., s -> 0},      {h -> 255.155, c -> 4000., s -> 0},      {h -> -255.155, c -> -4000., s -> 0},       {h -> 255.155, c -> 1870.83, s -> -3535.53},      {h -> -255.155, c -> -1870.83, s -> 3535.53},       {h -> 0, c -> 1870.83, s -> -3535.53},      {h -> 0, c -> -1870.83, s -> 3535.53},      {h -> 255.155, c -> -1870.83, s -> 3535.53},       {h -> -255.155, c -> 1870.83, s -> -3535.53},      {h -> 255.155, c -> 0, s -> 0},       {h -> -255.155, c -> 0, s -> 0},      {h -> 0, c -> 0, s -> 0}}      As can be seen the first element `myData[[1]]` (which is a list of three items) is a duplicate (up to the minus signs) `myData[[2]]` `myData[[5]]` `myData[[6]]`. But I don't know how to get _Mathematica_ to remove these. As an added bonus, it would be nice that, among the ones that are duplicates up to -1, the one with the least number of negatives is kept, and all others are removed. (In the example above, `myData[[5]]` would be among those that would be kept.)


How to define and work with temporary graphics data?

Background: I am working on a program that produces design patterns ( using wallpaper- and frieze-group theory ). This is for example a 'generating region' for a frieze or a wallpaper.                  Graphics[Polygon[{{.1, .1}, {.3, .8}, {1, .1}, {.5, .5}}]]      In reality this piece of Mathematica Graphics code is the result of many ( matrix- ) calculations. Usually I want this in a larger size, for example 1 by 2:                  Graphics[{Polygon[{{.1, .1}, {.3, .8}, {1, .1}, {.5, .5}}],          Polygon[{{1.1, .1}, {1.3, .8}, {2, .1}, {1.5, .5}}]}]      Currently I work as follows: ===pseudocode=== follows:                 Map[ CalculateBaseMotif[#1,#2] &,             Flatten[Map[# &, Table[{ii, jj}, {ii, 1, lenX}, {jj, 1, lenY}]], 1]      So `CalculateBaseMotif` is calculated over and over. While all I want is to transtlate the result of                  G=Graphics[Polygon[{{.1, .1}, {.3, .8}, {1, .1}, {.5, .5}}]].      Summarizing: I make a ( complicated ) graphic G requiring many calculations of width W and height H. Then I want to produce a ( final ) graphic like so:                 GGGG       GGGG      thus having width 4 x W and height 2 x H in the most efficient manner. **Question: How to define and work with temporary graphics data ?**


How do I calculate Standard Deviation confidence intervals in Mathematica?

I have a series of simulation results and I would like to demonstrate how the confidence interval for the mean and standard deviation decrease as the number of results increases. I have done this for the mean using the inbuilt MeanCI function as shown below (I've replaced my simulation results with random data).               Needs["HypothesisTesting`"]     data = Table[RandomReal[{-1, 1}], {i, 1, 100}];     movingData = Table[data[[1 ;; i]], {i, 2, Length[data]}];     meanCI = MeanCI[#, ConfidenceLevel -> .80] & /@ movingData;     ListPlot[Transpose[meanCI]]      ![enter image description here](http://i.stack.imgur.com/nrpjo.png) What I would like to do is create a similar chart showing how the standard deviation confidence interval decreases. There isn't a standard function for StandardDeviationCI but is there a way to use the tools inside the HypothesisTesting package to get a similar result?


How to show factorial in expanded form with variables

When evaluating the following               (Factorial[n + 1]/Factorial[(n + 1) - (k + 1)])      with Mathematica 9, the result is sent to output as               (1 + n)!/((n + 1) - (k + 1))!      I would like to show the expanded (if that's the correct term) form of the result , if possible, to show for example               (n + 1)n(n - 1)...(n+1-k)      Is there a function like `Expand` to accomplish this?


Non-linear equation system 3 equations and 3 variables

Can anyone please help me solve this system? 9.208x-3*y=0 -3x+3.208y+5*z=0 x^2+y^2+z^2=1 Thanks!


What is the most convenient way to read definitions of in-memory symbols when we don't have the source files? (Spelunking tools)

**Note:** I put Simon's implementation on GitHub. Contributions welcome! * * * When trying to read the definition of already defined (package or built-in) symbols using `Information` or `FullDefinition`, the biggest inconvenience is that lots of distracting private context names appear in front of all symbol names. Currently I am using a little function `contextFreeDefinition[]` to avoid this problem. It will attempt to hide the most frequently appearing context name in the definition. `contextFreeDefinition[]` is based on this answer. Compare for example `ClearAttributes[RunThrough, ReadProtected]; Information[RunThrough]` and `contextFreeDefinition[RunThrough]`. The latter is a lot less cluttered because the `System`Dump`` context is hidden in the definition. (I usually paste the output of this function into Workbench and re-indent it using the `Source -> Format` context menu item for better readability) * * * Unfortunately `contextFreeDefinition[]` does not always successfully hide contexts, for example try the following:               ImportString["1", "List"]; (* force Stub symbols to be loaded *)          System`Convert`TableDump`ImportList // contextFreeDefinition      and notice that several symbols (especially patterns) still have `System`Convert`TableDump`` prepended. For example, I see the following in the `FullDefinition` it prints:               protectRegEx[System`Convert`TableDump`s_String] :=           StringReplace[System`Convert`TableDump`s, $ProtectedCharacterRules]      The symbol `System`Convert`TableDump`s` still has the context name prepended even though the function tried to hide exactly this context. **Question:** How can `contextFreeDefinition[]` be fixed so it always hides the context, or what other alternative approaches are there to read the definitions of in-memory symbols? * * * The code of `contextFreeDefinition[]`.               Clear[commonestContexts, contextFreeDefinition]          commonestContexts[sym_Symbol, n_: 1] := Quiet[       Commonest[        Cases[Level[DownValues[sym], {-1}, HoldComplete],          s_Symbol /; FreeQ[$ContextPath, Context[s]] :> Context[s]], n],       Commonest::dstlms]          contextFreeDefinition::contexts = "Not showing the following contexts: `1`";          contextFreeDefinition[sym_Symbol, contexts_List] :=       (If[contexts =!= {}, Message[contextFreeDefinition::contexts, contexts]];       Internal`InheritedBlock[{sym}, ClearAttributes[sym, ReadProtected];        Block[{$ContextPath = Join[$ContextPath, contexts]},          Print@InputForm[FullDefinition[sym]]]])          contextFreeDefinition[sym_Symbol, context_String] :=       contextFreeDefinition[sym, {context}]          contextFreeDefinition[sym_Symbol] :=       contextFreeDefinition[sym, commonestContexts[sym]]      * * * **Understanding and using the function:** `commonestContexts[sym, n]` will find the `n` most frequently used contexts that are not in `$ContextPath` in the definition of symbol `sym`. `contextFreeDefinition[sym]` will print the `FullDefinition` of `sym`, hiding the commonest context that would appear there. It will also issue a message with the name of the context being hidden. `contextFreeDefinition[sym, {"Context1`", "Context2`", ...}]` will try to hide an explicitly given list of contexts.


How can I view the code implementing a built-in Mathematica function?

> **Possible Duplicate:**   >  What is the most convenient way to read definitions of in-memory symbols > when we don’t have the source files? I would like to look at the code that implements `FillingTransform`. Does _Mathematica_ provide any way to do this?


Linking FORTRAN with Librarylink

FORTRAN code can be called using MathLink or .NET/Link (see the link for a worked examples). But as mentioned in a talk by T.Gayley and J.Klein in Wolfram Technology Conference 2011, LibraryLink, which is new in version 8, is much faster. In the presentation, they gave a comparison of these three different approaches. (see also here a comparison by @Szabolcs). I just copy the pros and cons of LibraryLink from that presentation: * * *   * Pros     * Extremely fast, comparable to internal implementation in Mathematica itself.     * Memory for large arrays can be shared with the kernel.     * Code generation tools in Mathematica can be used to simplify creating and compiling libraries.     * Probably a better alternative than installable MathLink programs for most users who want to call C functions.   * Cons     * Need to write specialized C code for every function you want to call.     * Without special (and sometimes inconvenient) effort by the author, the kernel is not interruptible while calling a library function. This means that functions cannot be aborted while in progress, and the front end will not be responsive to most buttons, the help system, etc. * * * The advantages arouse my interest. But I have little experience with C programming... :-( So I want to know how can one call fortran functions and subroutines using Librarylink? Is there any worked example? Practically, I want to use it to call a cernlib package MINUIT written in FORTRAN 77, see my question here. MINUIT is a complicated package for function minimization and error analysis, and it has been widely used for may years, especially in the fields of nuclear and particle physics. Here is a link to its reference manual.


Borked Find Window in OS X

I've been having this happen to me on a daily basis with the Find & Replace window on OS X: ![enter image description here](http://i.stack.imgur.com/CNYHN.png) No text can be typed into the red regions, so all find & replace functionality is gone when this occurs. If you hover over the red regions, you can see the following error message: > An unknown box name ($Aborted) was sent as the BoxForm for the expression. > Check the format rules for the expression. The only solution to this, as far as I can tell, is to restart the kernel, which is fairly annoying. I recall that in previous versions of Mathematica (prior to 7), the Find & Replace window wasn't tied to the kernel at all, and this sort of thing would never occur. I think this is probably just a bug, but perhaps there is something I am doing in my code, perhaps setting a reserved variable that this window depends on, that is leading to the repeated recurrence of the problem. Just wanted to see if anyone here has had experience with this issue (perhaps it's not just OS X specific), and if they had any tips on how to avoid it, or perhaps some remedies that don't involve a full kernel restart. **Edit:** Here's a bit of code I used to stress-test a potential cause of this issue:               For[i = 1, i <= 100, i++,         pal = CreatePalette[Dynamic@ProgressIndicator[progress]];         progress = 0; cnt = 0;         Do[cnt = cnt + 1; progress = cnt/100000, {j, 100000}];         NotebookClose[pal];     ]


Dynamic Syntax - Evaluate AppendTo as the second argument

I am attempting to `Append` a new value into my list `paramMonitor` whenever the value for `B` changes. I had the code working perfectly, but my computer crashed without saving the document. I am now having a lot of trouble (dynamically) appending these values to my list. My attempts:   * This updates `B` but does nothing to append the value {`B`, `e`, `some number`} to `paramMonitor`              Dynamic[B,               AppendTo[paramMonitor,                {B,e,Abs[model[B, e][#] & /@ test[[All, 1]] - test[[All, 2]]] // Total}]      and   * Removing the first argument 'B', this code fails to compile and simply aborts upon execution:              Dynamic[AppendTo[paramMonitor,               {B,e, Abs[model[B, e][#] & /@ test[[All, 1]] - etst[[All, 2]]] // Total}]      I believe this is a quick fix (since I had it working earlier), but I cannot seem to find the issue.


Importing malformed XML: Import[... "XMLObject"] vs ImportString[..., "XML"]

It appears that `Import[ url , "XMLObject" ]` is more forgiving of improperly formatted XML than `ImportString[ string, "XML"]`. For example, Mathematica is happy to do this               popNamesXML =        Import["http://uscode.house.gov/popularnames/popularnames.htm",          "XMLObject"];      but complains about this               popNames =        URLFetch["http://uscode.house.gov/popularnames/popularnames.htm"];     xml = ImportString[popNames, "XML"];      ![enter image description here](http://i.stack.imgur.com/WJ3IB.png) and barks about utf8 encoding for this               ImportString[popNames, {"HTML", "XMLObject"}]      In the `Trace` of the first snippet it appears these options are being passed to `XMLGetString`:               {"NormalizeWhitespace"->True,"IncludeNamespaces"->Automatic,      "ValidateAgainstDTD"->Automatic,"IncludeEmbeddedObjects"->None,      "AllowRemoteDTDAccess"->True,"ReadDTD"->True,"IncludeDefaultedAttributes"->False,      "AllowUnrecognizedEntities"->Auomatic,"PreserveCDATASections"->False}      But passing these to `ImportString` or directly to `XMLGetString` still results in the same errors. This answer may be of interest but does not seem to be the problem, though I could be wrong. I tinkered with the suggestion there without luck. Does anyone know if/how I can make `ImportString` behave nicely here?


Performing Computations on Sets

I would like to find a permutation of $\quad S=\\{\frac{1}{10}, \frac{1}{2}, \frac{4}{7}, \frac{3}{5}, \frac{2}{3} \\}\quad$ that maximizes the sum of theses elements raised to unique powers: $\;\\{0,1,2,3,4\\}$.   I think it is \begin{align}\biggr(\frac{1}{10}\biggr)^0 + \biggr(\frac{4}{7}\biggr)^1 + \biggr(\frac{2}{3}\biggr)^2 + \biggr(\frac{3}{5}\biggr)^3 + \biggr(\frac{1}{2}\biggr)^4&\approx 2.294373016\end{align} but I would like to verify that this is the case via computation. Also it would be useful to know how to perform general operations on sets.


Evaluate conditional expression

I solved an integral and get a conditional expression as the result. The conditions are quite heavy but if I use `Assumptions` within my `Integral` call the computation time is heavily increased. My question, how can I evaluate a conditional expression? Example:               Integrate[1/Sqrt[z - Cos[x]], {x, 0, 2*Pi}]     Out[1]:= ConditionalExpression[(2 EllipticK[-(2/(-1 + z))])/Sqrt[-1 + z] + (       2 EllipticK[2/(1 + z)])/Sqrt[1 + z], Re[z] > 1]      And now let's say I know that $z \in \mathbb{R}$. I want to see what conditions are left when I plug that assumption in (of course this is quite an easy case here, but in my case I have tons of conditions and I like to see which disappear because I can make certain assumptions). Again, I could use `Assumptions` but it will make the computation ultra slow.


How to expand the size of the matrix automatically?

I have a matrix in 2x2               a ={{x, y}, {z, u}}      I want to expand this matrix 3x3               b ={{x, y, y}, {z, u, x}, {z, x, u}}      4x4               c ={{x, y, y, y}, {z, u, x, x}, {z, x, u, x}, {z, x, x, u}}      5x5               d ={{x, y, y, y, y}, {z, u, x, x, x}, {z, x, u, x, x}, {z, x, x, u, x}, {z, x, x, x, u}}      and soon... Basically, I am adding a row and column each time. How to do this automatically, without writing each time? * * * **Edit:** Now consider x, y,z and u are also 2x2 matrices. Lets               x={{0,1},{1,0}}, y={{1,1},{1,0}}, z={{1,0},{1,1}}       and                u = {{p,q},{r,s}}.      How I can get a,b,c and d (defined above) in this case?


How do I compute the entropy of the beta distribution?

I tried               Expectation[-q*Log[q], q \[Distributed] BetaDistribution[a, b]]      and got               (a (HarmonicNumber[a] - HarmonicNumber[a + b]))/(a + b)      (I get the same result using integration.) This seems pretty different from the expression in Wikipedia, even after substituting the identity (mentioned at MathWorld that `H[n] = gamma + PolyGamma[0,n+1]`, where `gamma` is Euler's constant and `PolyGamma[0, n+1] = Digamma[n+1]`. Any ideas which identity I'm missing? Kevin P.S. I trust the Wikipedia answer, I have seen this result before, but I want to re-derive it with _Mathematica_ as a sanity check, before I go on to derive other expressions of interest.


How to modify tick's range in Image3D

Suppose we have an array of color data               colorArray = ParallelTable[With[{v = RandomReal[]},     Append[List @@ ColorData["LightTemperatureMap"][v], If[v >= .8, .5, 0]]     ], {z, 0, .1, .005}, {y, 0, 1, .1}, {x, 0, 10, 2}];      And we use `Image3D` to visualize them               is = 350;     Image3D[     colorArray, "Real", ColorSpace -> "RGB",     ViewPoint -> {1.3, -2.4, 2}, SphericalRegion -> True,     Boxed -> True, BoxRatios -> {1, 1, 1},     Axes -> True, AxesLabel -> {"X", "Y", "Z"},     ImageSize -> is, ImageResolution -> 3*is]      ![enter image description here](http://i.stack.imgur.com/SnTbx.png) The problem is that the ticks are the relative position of each `RGBColor` element in the array, not the actual range of `x`, `y`, and `z` (`{z, 0, .1, .005}, {y, 0, 1, .1}, {x, 0, 10, 2}`). My question is how can we change the ticks to show the actual range of `x`, `y`, and `z`? A direct implement seems impossible because in `colorArray` no data about the original `x`, `y`, and `z` values are stored (actually we cannot store them in `colorArray` due to the requirement of `Image3D`).


Formatting results of a polynomial long division

I am teaching polynomial long division to my high school students. Not a pleasant topic to have to cover. I went to use Wolfram|Alpha and obviously, internally, they have a really elegant way to express the results of long divisions. ![long-division](http://i.stack.imgur.com/SYkUP.png) I don't suspect there is any easy way to directly ask Alpha (from _Mathematica_ ) to do that division for me? Has anyone implemented anything like this? Would it involve using a table or matrix? Everything is nicely lined up and typeset; it would be helpful to see how such a structure was created. Tom


Create huge RandomInteger list

For testing purposes, I'd like to create very large amounts of Random Integers, let's say between $-1000$ and $1000$. I'm using the usual               RandomInteger[{-1000, 1000}, 5]      command to create $5$-tuples. On my machine (8GB of RAM), this process becomes quite slow once in the                 Table[        RandomInteger[{-1000, 1000}, 5]        ,        {100000000}]      (one hundred million) region. It takes 17 seconds of `Timing[]` for this list to be made, and I haven't even had any calculations on it. Does this mean I should restrain using lists till somewhat lower as this threshold, or is there any other way of handling huge lists? Does MMA input the whole list in RAM before doing calculations with it? Is it possible to handle huge lists without including the _whole_ list in RAM, for speeding purposes? I thought of dividing the list, perhaps exporting to different files (CSV for example), and then doing calculations with every file individually. This is probably the same as `Partition[]` does (without exporting)? Thanks for any more suggestions!


Complement for a Matrix

In a matrix, there are some non-zero elements same as: aA= ![enter image description here](http://i.stack.imgur.com/KN0bZ.png) Also, there is a list such as:               list = {a, b, c, d, e, f, g, ii, jj, kk};      I want to access to elements of the list which are not in the matrix. (I mean: 'c','d','g','jj') I use Complement to this work:               Complement[aA, list]      But Complement doesn't work.


Labeling vertices by number in Graph: Getting text to display at the right size

Minor aesthetic question here. I was playing around with `Graph`'s and decided to render a cute-looking family of directed graphs, with the vertices being the number associated with the vertex. Here is an example with number of nodes $n=200$ (right-click and open in a new tab to see at proper resolution):               n = 200;     Graph[Table[i -> Mod[30 i, n, 1], {i, n}], ImageSize -> 1280,       VertexShape -> Table[i -> i, {i, n}], VertexSize -> 1,       VertexStyle -> White, EdgeStyle -> Green, Background -> Black]      ![enter image description here](http://i.stack.imgur.com/maTTZ.png) It looks fine. Now let's try $n=5$:               n = 5;     Graph[Table[i -> Mod[30 i, n, 1], {i, n}], ImageSize -> 1280,       VertexShape -> Table[i -> i, {i, n}], VertexSize -> 1,       VertexStyle -> White, EdgeStyle -> Green, Background -> Black]      ![enter image description here](http://i.stack.imgur.com/1nYef.png) The vertex labels are gigantic and distort the figure to make it unreadable. Fine, let's just set `VertexSize -> Automatic`: ![enter image description here](http://i.stack.imgur.com/9WBQ7.png) Much better. Let's try using `VertexSize -> Automatic` for the $n=200$ case once more: ![enter image description here](http://i.stack.imgur.com/0N3l9.png) The three-digit labels are unreadable, because `Automatic` does not appear to correctly scale them, and so it only displays the first digit and cuts off the rest with a `...`. Is there an automatic way (other than `VertexSize -> Automatic`) to make text vertices show up as the right size without being truncated?


How to rotate 3D graphics in ListAnimate ... without making a mess?

`Manipulate` is, of course, wonderful … but there are LOTS of examples that are simply far too computationally intensive to use live real-time animations for. In such case, one has to use pre-generated graphics. So, let us suppose we have something like:               ListAnimate[
 Table[Plot3D[Cos[x Sin[n y]], {x, 0, 2 Pi}, {y, 0, Pi}], {n, 1, 2, .1}]]      All fine. Then it starts playing … and you grab the plot, and rotate it … and Mma rotates ONE SINGLE plot … and leaves all the others images in the animation as they were … creating a visually absurd animation. Suggestion: If a user rotates one plot in a grouped animation ... even if they pre-rendered … they should all rotate by the same amount … so the animation will still work as intended. Any suggestions as to how to overcome this short-coming in the Mma 9 front-end user interface?


Numerically Solving Compatible Systems of Overdetermined PDE

Is there an easy way to get Mathematica to numerically solve a compatible system of overdetermined PDE, and plot the solutions? For example, consider the "toy" example $\dfrac{\partial u}{\partial x} = (1+x y^2) u, \qquad \dfrac{\partial u}{\partial y} = (1+y x^2) u$ with initial data, say, $u(0,0)=1$. (The actual system I want to solve is nonlinear and has many more dependent variables.) One could apply NDSolve to the first equation, with $y=0$, to get $f(x)=u(x,0)$ defined over the $x$-axis. Then for each of several values $x_i$, solve the second equation with $x=x_i$ and initial value $u(x_i,0)=f(x_i)$. This produces a family of interpolating functions, each of which is a snapshot of $u(x,y)$ for some fixed value of $x$. But I'd like to put the plots of these together to form the graph of a function of two variables. Better yet, I'd like some way of automating this, so I don't have to choose the values $x_i$ by hand.


Restricted accumulation of values

Please consider the following list `data`. I was trying to accumulate `data` until the result turns positive the first time and finally found an approach. Maybe it's useful to others and maybe there are other (more efficient) approaches:               data={-1050, 50, 1001, 1950, 1950, 1950, 525, 0};      The same what `Accumulate` does can be done by `FoldList`:               Rest@FoldList[Plus, 0, data] == Rest@FoldList[#1 + #2 &, 0, data] == Accumulate@data     (*True*)      Now, one can add constraints to `FoldList`. For my problem I had to write:               Rest[FoldList[If[#1 + #2 < #2, #1 + #2, #2] &, 0, #]]&@data     (*{-1050, -1000, 1, 1950, 1950, 1950, 525, 0}*)      **Question** How can this be improved, either in terms of speed or elegance?


How can I make Which format its output?

Functions like `Piecewise` have cool, easy-to-read formatting. In the same vein, I think it would be wonderful if the `Which` function automatically returned output in a column or tabulated form:                Which[a < b,     1,            c < d,     2,             True,      3]      rather than the what currently happens, which can sometimes be difficult to read.               Which[a < b, 1, c < d, 2, True, 3]      This example happens to be easy to read, but for `Which` expressions with a large number of `<condition, value>` pairs, it would be nice to have a structured layout for the output. Any suggestions as to how to make this happen automatically?


How to understand the process of ListCorrelate when it in two-dimensional condition?

Toady,I learn a function **`ListCorrelate`** ,and I can understand **`process of execution his result in one-dimensional`**. However,the documentation gives a **`two-dimensional correlation example`** (shown as below)               ListCorrelate[{{1, 1}, {1, 1}}, {{a, b, c}, {d, e, f}, {g, h, i}}]      > {{a + b + d + e, b + c + e + f}, {d + e + g + h, e + f + h + i}} To understand it,I replace `{{1,1},{1,1}}` to `{{u,v},{x,y}}`.               ListCorrelate[{{u, v}, {x, y}}, {{a, b, c}, {d, e, f}, {g, h, i}}]      > {{a u + b v + d x + e y, b u + c v + e x + f y}, {d u + e v + g x + h y, e u > + f v + h x + i y}} ### My trail to figure out how his result be generate: > I think two-dimensional correlation is the **`composition`** of two one- > dimensional correlations, but,unfortunately, from the results that > _Mathematica_ executes it is not what I think.               ListCorrelate[{{u, v}}, {{a, b, c}, {d, e, f}, {g, h, i}}]      > {{a u + b v, b u + c v}, {d u + e v, e u + f v}, {g u + h v, h u + i v}}               ListCorrelate[{{x, y}}, {{a, b, c}, {d, e, f}, {g, h, i}}]      > {{a x + b y, b x + c y}, {d x + e y, e x + f y}, {g x + h y, h x + i y}} ### Question: **How to understand the process of`ListCorrelate` when it in two-dimensional condition?**


How can I solve a forward-backward-looking recurrence system?

I would like to (numerically) solve a forward-backward looking recurrence equation in _Mathematica_. The system is something like:               x[n+1] = x[n] + y[n]          y[n]   = 2* y[n+1]      subject to               x[0]=1,y[N]=1      The problem is that the boundary of `x` at the beginning (`n=0`) where the boundary of `y` is at the end (`n=N`) (hence forward-backward looking). The _Mathematica_ command `RecurrenceTable` does not handle this. I would need to obtain a result for an arbitrary level of `n`. Numerical results are fine. What would be the most efficient method to tackle this problem?


How can I create a new tables out of a table and plot it

I have the following problem. I have a table, call it m, which is labelled by 3 indices (say i,j,k), each of them running from 1 up to 100. I would like to be able to construct a new table which would consist of elements taken from m under the following condition: For any p, such that `2 < p < 301`, construct the table consisting of pairs, where the first term in all pairs for a given p is always the same equal `p*0.06`               Table[{0.06*p, m[[i, j, k]]}, {p, 2, 301}]  WITH THE CONSTRAINT  i + j + k = p      It is the constraint which puzzles me. I would also like to plot all these Lists on one graph (using `ListPlot`?). I managed to do something like this for a table with two indices using a `Do` loop, but for three indices, it seems I would have to use a double loop and I don't know how to do that. Looking forward to any suggestions!


How does Mathematica interpret a expression?

I'm a beginner to Mathematica. I'd read several document. But I still have a problem. For example, every expression in Mathematica are of the form `Head[expr1,expr2,...]` If I type `Plus[3^3,6*9]`, what is the practical order Mathematica interpret?   1. Interpret `Plus` first, and then interpret expr1, expr2,... In other words, from 'outside' to 'inside'   2. Evaluate `Power[3,3]` first, then `Times[6,9]`, after evaluating these, then interpret `Plus` Or there may be other ways Mathematica use? What else should I notice? Thanks for your replying and forgiving my bad English grammar. :-)


Evaluation - separate Output window + not evaluate particular cells

is it possible to avoid that mathematica writes the output into the nb file? I would prefer that mathematica writes the output into a separate file. If it writes into the notebook (I usually use: evaluate notebook), mathematica always runs through the file so that I always have to search for the cell I was recently working with; the view changes when I use evaluate notebook. Another question is: Is it possible to exclude cells from evaluation? E.g. if I have different cases and case 1 is finished. Then I write case 2 below case 1 and use "evaluate notebook". However, it would be nice if I could mark the cells within my programming so that case 1 remains untouched. I know how to use **(** ) and I know that I can choose cells to be evaluated - but that's not what I'm looking for -- Instead I'm looking for a command, a switch or goto-label. Or is there a command similar to ( _*_ *) which can be used for more than 1 cell? Thanks a lot!!


Draw grid with points

How would I draw a grid with dots on specified intersections? The image below shows the basic idea: ![enter image description here](http://i.stack.imgur.com/acXcH.jpg) If I wanted to label the grid lines with index numbers or letters, how would I do that?


Pass by reference for an option argument

Pass by reference can be faked by using `HoldAll` or something similar in the definition of a "Function". But can pass by reference be faked for symbols passed as named arguments (Options)? Let me demonstrate: This works (when you click on the checkboxes the list changes):               ClearAll@PassByArg;     Attributes[PassByArg] = {HoldFirst};     PassByArg[list_] := CheckboxBar[Dynamic[list], Range@Length@list];     aList = {1, 2, 3, 4, 5};     PassByArg[aList]     Dynamic[Sort@aList]      **How can I pass the reference to`list` as an option?** Here is one of my failed attempts (it returns `et::setraw: Cannot assign to raw object {1,2,3,4,5}` when a checkbox is clicked.               ClearAll@PassByOption;     Options@PassByOption = {"List" -> None};     PassByOption[opts : OptionsPattern[]] :=        With[{i = ReleaseHold@OptionValue@"List"},         CheckboxBar[Dynamic[i], Range@Length@i]];     aList = {1, 2, 3, 4, 5};     PassByOption["List" -> Hold@aList]     Dynamic[aList]      I always evaluate either too much (to `{1,2,3,4,5}`) or too little... Perhaps some motivation is in order: I'm developing a GUI using `Dynamic`. Now I would like to control a list of displayed functions in some plot. If I implement this as a reference passed with a named argument I practically don't have to change any other code:)


Matrix echelon/upper diagonal form

Is there a way to find the echelon form of a matrix in _Mathematica_? I see there is a function to find the reduced echelon form, `RowReduce[]`, but I can't see anything for the echelon or upper triangular form? Thanks David.


Converting Mesh in Density Plots to a Graph

Consider the following line of code:               DensityPlot[4 Sin[2 Pi x] Cos[1.5 Pi y] (1 - x^2) (1 - y) y,                        {x, -1, 1}, {y, 0, 1}, Mesh -> All, MeshStyle -> Thick]      with the following output: ![mesh](http://i.stack.imgur.com/rUZVo.png) How can I convert the shown mesh into a `Graph` object such that:   1. All the vertices are aligned at the intersection of the lines, withe correct `VertexCoordinates`.   2. The edges (line segments in the plot) connect the corresponding vertices. Note: If `g` is the result `Graph`, the the following code should give the same figure as the one above:               Show[DensityPlot[4 Sin[2 Pi x] Cos[1.5 Pi y] (1 - x^2) (1 - y) y, {x, -1, 1}, {y, 0, 1}], g]


Plotting a convolution fails

i'm trying to plot a graph of a convolution and a discrete convolution, using _Mathematica_ 8               x[t_] := exp[-2*t]*(HeavisideTheta[t + 2] - HeavisideTheta[t]) +         (1 - t/2)*(HeavisideTheta[t] - HeavisideTheta[t - 2])     y[t_] := -2*DiracDelta[t + 2] +  2*(HeavisideTheta[t] - HeavisideTheta[t - 2])     c[t_] := Convolve[x[d], y[d], d, t]     Plot[c[t], {t, -4, 4}, PlotRange -> {-4, 4}, PlotStyle -> {Thickness[0.006]}]      This results in an empty graph. Can _Mathematica_ 8 plot convolutions? Same thing happens with discrete convolution. Any help is appreciated, thanks in advance.


Recommended settings for git when using with Mathematica projects?

# Background I'm relatively new to git — currently overseeing an offshore .NET-based development project on GitHub within a private business account, but little experience beyond that. I'd like to set up repos for storing my _Mathematica_ projects (including one for my dissertation work). Initial tests revealed that git will make an unusable mess out of .nb files. Searching lead me to resources mentioning that notebooks contain too much metadata to diff/merge cleanly (without some specialized logic). # Question: What git customizations are appropriate when _Mathematica_ files and projects are involved (i.e., Workbench projects)? I'm a git noob, so be as explicit as possible with any instructions/advice! Are there any specific considerations to be made when using GitHub to host my _Mathematica_ projects? * * * _Resources that might help:_   1. Pro Git Book:     * Git configuration     * Git attributes (← section on binary files seems important)   2. Are there suitable versioning systems for _Mathematica_ notebooks?


Kernel quits upon evaluation of a limit

Using 9.0.1 on OS 10.9.3, I evaluated               Limit[(1 + t/Sqrt[n])^-n, n -> Infinity]      at the start of a session and it caused an error that made the kernel quit. But I don't see any warning or error message. On the other hand, evaluating a very similar expression               Limit[(1 + t/n)^-n, n -> Infinity]      generates no such warning. Can anyone reproduce this issue?


Working precision for each variable

How can I define working precision for each variable individually for example:               Maximize[x y< 100, {x, y}]      where the working precisions for `x` and `y` should be `2` and `7` respectively. Say `x` is some real life quantity that is _ONLY available to 2 decimal places_ and we need `y` to be as precise as possible (say 7 decimal places) regardless of the precision of `xy`. How can I do this in Mathematica? **here is exact problem**                  Maximize  hsum + isum + jsum + ksum + lsum + msum + nsum + osum      constraints are:                  0 < hsum,isum,jsum,ksum,lsum,msum,nsum < 10000       -5000 < osum < 0             a*x1 + b*x2 + d*x4 - h*(x1 + x2 + x4) = hsum        a*x1 + b*x2 + d*x4 - i*(x1 + x2 + x4) = isum        a*x1 + b*x2 + e*x5 - j*(x1 + x2 + x5) = jsum        a*x1 + b*x2 + e*x5 - k*(x1 + x2 + x5) = ksum        a*x1 + c*x3 + f*x6 - l*(x1 + x3 + x6) = lsum        a*x1 + c*x3 + f*x6 - m*(x1 + x3 + x6) = msum        a*x1 + c*x3 + g*x7 - n*(x1 + x3 + x7) = nsum         a*x1 + c*x3 + g*x7 - o*(x1 + x3 + x7) = osum            > X1,X2,X3....X7 are integers               a=100          b = (a + u1) && c = (a - u2) && d = (b + u3) && e = (b - u4) &&      f = (c + u5) && g = (c - u6) && h = (d + u7) && i = (d - u8) &&      j = (e + u9) && k = (e - u10) && l = (f + u11) && M = (f - u12) &&     n = (g + u13) && o = (g - u14)                0.1 <= u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12, u13, u14 <= 3      in the above problem `a` is `100` rest of the variables `b,c,d,e,f,g,h,i,j,k,l,m,n,o` can be derived by adding or subtracting `u1,u2,u3....u14` now i need to define that value of u must be upto 2 decimal places. Also here is the link for the same Non linear constrained interger Optimization (you can check out this one too!)


Manipulating slots in a pure function

How does one manipulate the slot numbers in a pure function? Some trick with `Evaluate` or `Hold`? I'm aiming for something along the lines of:               (Slot /@ Range[19, 164, 29])& @@ {...}      **EDIT** It turns out my actual problem is: why does               Evaluate[{Slot /@ Range[19, 164, 29]}] & @@ Range[164]      yield `{{19, 48, 77, 106, 135, 164}}` but               {Evaluate[Slot /@ Range[19, 164, 29]]} & @@ Range[164]      yields `{{#19, #48, #77, #106, #135, #164}}`?


Why do two roots of my equation disappear when I give numerical values to two parameters?

Consider the equation               (-Sqrt[1 + KE la + KE s + KE la s - Sqrt[4 KE la + (1 + KE s - KE la (1 + s))^2]]*     (1 - KE la + KE s - KE la s + Sqrt[4 KE la + (1 + KE s - KE la (1 + s))^2])-      (-1 + KE la - KE s + KE la s + Sqrt[4 KE la + (1 + KE s - KE la (1 + s))^2])*     Sqrt[1 + KE la + KE s + KE la s + Sqrt[4 KE la + (1 + KE s - KE la (1 + s))^2]]) == 0      `KE` and `la` are real constants. When I use Solve on the above, it gives four symbolic roots. But when I give `KE` and `la` numerical values, it only returns two numerical roots. How can this be explained?


Creating a function as a table of derivations

Suppose I have function, which is in fact a list of $n$ functions with $n$ parameters               f = {#1 + #2^2 + #3^3, #1^2 + #2^3 + #3^4, #1^3 + #2^4 + #3^5}&      I want to get a function that is in fact matrix of all possible partial derivations $ \left( \begin{array}{ccc} \frac{\partial f_1}{\partial x_1} & \frac{\partial f_1}{\partial x_2} & \frac{\partial f_1}{\partial x_3} \\\ \frac{\partial f_2}{\partial x_1} & \frac{\partial f_2}{\partial x_2} & \frac{\partial f_2}{\partial x_3} \\\ \frac{\partial f_3}{\partial x_1} & \frac{\partial f_3}{\partial x_2} & \frac{\partial f_3}{\partial x_3} \end{array} \right)$ , i.e               g = {{1,2#1,3#1^2},{2#2,3#2^2,4#2^3},{3#3^2,4#3^3,5#3^4}}&      I tried to do that myself by adapting the answer Find partial derivatives when the number of variables is unknown, but I don't understand the cumulative use of `Apply`, `Seqence` and `Map`.


PlotStyle in ListPlot: change color scheme, manually choose color of first plot

Say i have this data:               data1 = Map[Cos, Range[0, 20]];     data2 = Map[Sin, Range[0, 20]];      And i want to plot `data1` in gray and a chosen set (with `Manipulate`) of multiplicities of `data2` in several other colors. This code does what I mean:               Manipulate[      ListLinePlot[{data1, Sequence @@ Table[data2*i, {i, k}]},        PlotStyle -> {LightGray,          Sequence @@ ConstantArray[Automatic, Length[k]]}], {{k, {1,          2}}, {1, 2, 3, 4}, ControlType -> CheckboxBar}]      I managed to make it work to only plot `data1` in gray and the multiplicities of `data2` in automatic colors, but now I'm stuck at the standard color scheme, although `PlotStyle` accepts `ColorData`. For example:               PlotStyle -> ColorData[3, "ColorList"]      However I don't know how to implement this with the condition that the first plot should be gray. **Question: Is there a way to change the color scheme in`ListPlot` AND manually choose the color of the first plot?**


Module Returns Two Values for Plot; I need to Color them

This is probably a very stupid question, but I've been fighting with it for quite awhile now. So suppose you have a module:               Test[g_] := Module[{r = g, r2},     r2 = g + 2;     Return[{g, r2}];     ];      That module returns two values such that you can plot them (I've tried it with and without the {} around the function):               Plot[{Test[g]}, {g, 0, 100}, PlotStyle -> {Red, Blue}]      I need to have them colored. I realize I can do this:               Plot[{Test[g][[1]], Test[g][[2]]}, {g, 0, 100}, PlotStyle -> {Red, Blue}]      However, Test is just an example to ask this question, my real module takes a half an hour to plot (it is doing a bunch of maximizations, etc). So, doing the last option would double that time. (and I want to make a bunch of plots). So, does anyone know how to color the lines when in the first form such that I'm not running the module twice?


How to Import random elements of huge data files

I am calculating huge data files with an external program. I would like then to import the data into Mathematica for analysis. The files are 2 columns and up to many millions of rows. So for small data files I have just been using:               dataTable = Import["data.txt", "Table"];       However once the files gets so large (into the millions), Mathematica and my computer slow down considerably. Now, I don't really care about most of the data in these files and in Mathematica I end up only using several thousand entries. So my question is, can I import a random sampling from the large data file (say 10000 elements only) instead of importing the entire file? So if I had a file with 10^6 rows, I would like to import just 10^4 of those rows (preferably randomly).


Error in ARIMAProcess example

I am trying to compile the sample of ARIMAProcess of MMA here .It doesn't work.What is wrong?Could you please help?I am using exact same code.               data = TemporalData[FinancialData["EUR/USD", {{2012, 5, 1}, {2012, 9, 30}}]]["Part",All, {{2012, 5, 1}, {2012, 9, 30}}];     DateListPlot[data["Path"], Joined -> True, Filling -> Bottom, ImageSize -> 350]     eproc = EstimatedProcess[data, ARIMAProcess[40, 2, 0]]     forecast = TimeSeriesForecast[eproc, data, {20}]     DateListPlot[{data["Path"], forecast["Path"]}, Joined -> True,      Filling -> Axis, PlotLabel -> "EUR/USD", ImageSize -> 350]


Minimizing a Matrix

pnorm[A_, p_] := Module[{m, n, x, y, f, ans, ret},       {m, n} = Dimensions[A];       y = Array[x, n];       f = Norm[A.y, p]/Norm[y, p] // FullSimplify;       ans = Maximize[f, Array[x, n]] // N;       ret = Part[ans, 1];       ret     ]          findD[L_, c_, \[Lambda]_, p_] := Module[{B, M, w, pp, ans},       M = Array[B, Dimensions[L]];       w = Tr[c.(Transpose[M])];       pp = pnorm[L - M, p] // FullSimplify;       ans = Minimize[Hold[pp + \[Lambda] w],          Flatten[Array[B, Dimensions[L]]]] // N;       ans     ]          findD[{{3, 8}, {2, 5}}, {{9, 1}, {3, 6}}, .5, 3]          During evaluation of In[44]:= NMinimize::nnum: The function value 6.59387       +1/((Abs[<<1>>]^3+<<1>>^3)/(Abs[<<1>>]^3+<<1>>^3))^(1/3) is not a number at {B$33209[1,1],B$33209[1,2],B$33209[2,1],B$33209[2,2]} = {0.643476,0.766972,0.280303,0.964763}. >>          During evaluation of In[44]:= NMinimize::nnum: The function value 1/((Abs[<<1>>]^3+<<1>>^3)/(Abs[<<1>>]^3+<<1>>^3))^(1/3)+0.5 (9 B$33209[1,1]+B$33209[1,2]+3 B$33209[2,1]+6 B$33209[2,2]) is not a number at {B$33209[1.,1.],B$33209[1.,2.],B$33209[2.,1.],B$33209[2.,2.]} = {0.643476,0.766972,0.280303,0.964763}. >>          During evaluation of In[44]:= NMinimize::nnum: The function value 1/((Abs[<<1>>]^3+<<1>>^3)/(Abs[<<1>>]^3+<<1>>^3))^(1/3)+0.5 (9 B$33209[1,1]+B$33209[1,2]+3 B$33209[2,1]+6 B$33209[2,2]) is not a number at {B$33209[1.,1.],B$33209[1.,2.],B$33209[2.,1.],B$33209[2.,2.]} = {0.643476,0.766972,0.280303,0.964763}. >>          During evaluation of In[44]:= General::stop: Further output of NMinimize::nnum will be suppressed during this calculation. >>          Minimize[      Hold[pp$33209 + 0.5 w$33209], {B$33209[1., 1.], B$33209[1., 2.],       B$33209[2., 1.], B$33209[2., 2.]}]      The code above is trying to find a matrix $\mathbf M$ which minimizes $\|\mathbf L-\mathbf M\|_p + \lambda\,\mathrm{tr}(\mathbf C\mathbf M^\top)$. However, the usage of `Minimize` in the `findD` function is giving me problems. Does anyone know how to fix the "not a number" problem? Thank you!


NDSolve diffusion equation over/underdetermined

I have a feeling the solution to my problem is very simple… but my knowledge of differential equations is pretty weak. I am trying to solve a scalar diffusion equation (used in NMR spectroscopy, but from what I understand, modeled after heat and Fickian diffusion). I've tried following model equations, but whenever I ask Mathematica to evaluate, it returns the original equation. What am I missing here? Here is my code:               With[{Dif = 2300, pde = D[u[t, r], t] == Dif/r*D[u[t, r]*r, r, r] -       1/(0.0945 E^(0.000212+0.4077r))*(u[t, r]+1.2004)},       soln = NDSolve[{pde, u[0, r] == 0, Derivative[0, 1][u][t, 0] == 0,       Limit[u[t, r], r -> \[Infinity]] == 0}, u, {t, 0, 10}, {r, 0, 500}]]      Upon evaluation, it returns an error stating that the equation is "overdetermined". Removing a single one of the 3 boundary conditions results in an "underdetermined" error. Is this possible to solve using NDSolve, or do I need to break down the equation? Thanks for the help!


Given a list of date and value pairs, efficiently sum the values by date

I have a list of date & value pairs. There can be multiple entries for each day. Sample data can be generated with the following:               maxDays = 10;     date = AbsoluteTime[{2013, 5, 13}];     dateValuePairs = Flatten[Table[{date + day * 86400, value}, {day, maxDays}, {value, 10}], 1];      The sample data looks like:               {{3577478400, 1}, {3577478400, 2}, ... {3577478400, 10},      {3577564800, 1}, {3577564800, 2}, ... {3577564800, 10},       ...      {3578256000, 1}, {3578256000, 2}, ... {3578256000, 10}}      I am trying to sum the values for the same day. With the sample data above, I expected to see ten days, each with a value of 55 . I tried the following:               Clear[sumByDay];     Map[        (sumByDay[#[[1]]] =          If[ValueQ[sumByDay[#[[1]]]],           sumByDay[#[[1]]] + #[[2]],           #[[2]]           ]) &, dateValuePairs];     DownValues[sumByDay]      ... and I expected it to return:               Out[]= {HoldPattern[sumByDay[3577478400]] :> 55, HoldPattern[sumByDay[3577564800]] :> 55, ... HoldPattern[sumByDay[3578256000]] :> 55}      ... however I receive:               $RecursionLimit::reclim: Recursion depth of 256 exceeded. >>          Out[]= {HoldPattern[sumByDay[3577478400]] :> 1 + sumByDay[3577478400]}      `sumByDay[#[[1]]] + #[[2]]` must not be being evaluated as I expected, see below:               In[]:= a[3577478400] = 1     In[]:= a[3577478400] = a[3577478400] + 2     ...     In[]:= a[3577478400] = a[3577478400] + 10          Out[]= 1     Out[]= 3     ...     Out[]= 55      ## And the Question of Efficiency ... I am sure I can accomplish this less efficiently. As I am equally sure that it can be done more efficiently. i.e. :               Map[(day = #;        {day, Total[          Transpose[Select[dateValuePairs, #[[1]] == day &]][[2]]]}        ) &, Sort[DeleteDuplicates[Transpose[dateValuePairs][[1]]]]]      The number of days defined by `maxDays` in the sample data example will grow at a const rate.


NDSolve with arrays and Tables of Equations and WhenEvent

I've been toying around with NDSolve for a while, and read through the website. By doing so I discovered that I could use it for vectors and arrays with much pleasure. So I wanted to write a simple simulator with multiple balls or particles interacting with Lennard Jones potentials. When I write this way I have no problem               partsim[p0_, v0_, mass_] :=        Module[{rp},       rp[t_] := Evaluate@Array[Unique[][t] &, {nParticles, 3}];       rp[t] /. NDSolve[       Join[        Table[         {          (*Initial COnditions*)          rp[0][[i]] == p0[[i]],          rp'[0][[i]]  == v0[[i]],               (*Newton Equations*)            rp''[t][[i]] == (1/mass[[i]])*            Sum[If[j != i, ljForce[i, j, rp[t]], 0], {j, 1,               nParticles}]          (*Third newton law in the future*)               }         , {i, nParticles}](*End of Table*)          ](*End of Join*)       , rp[t]       , {t, 0, ftime}] // First        ](*End of Function*);      The real problem arises when I'm trying to also add a `WhenEvent` for each of the particles present in the system. Since it's 3d I would like them to stay inside a bounding box and invert the sign of their velocity every time they touch the walls or at least come withing tolerance.               partsim[p0_, v0_, mass_] :=        Module[{rp, vel},       rp[t_] := Evaluate@Array[Unique[][t] &, {nParticles, 3}];       vel[t_] := Evaluate@Array[Unique[][t] &, {nParticles, 3}];       rp[t] /. NDSolve[       Join[        Table[         {          (*Initial COnditions*)          rp[0][[i]] == p0[[i]],          rp'[0][[i]] == vel[0][[i]] == v0[[i]],          (*Newton Equations*)          rp'[t][[i]] == vel[t][[i]],                  rp''[t][[i]] == (1/mass[[i]])*            Sum[If[j != i, pairForce[i, j, rp[t]], 0], {j, 1,               nParticles}]                    }         , {i, nParticles}](*End of Table*)                  (*Discrete Events*)        (*Bouncing on walls*)             , Table[{         WhenEvent[          {Norm[rp[t][[u]] - wallcoord] < .01  ,            Norm[rp[t][[u]]] <  .01}          , vel[t][[u]] -> -vel[t][[u]]          ](*End of WhenEvent*)         }, {u, nParticles}]             ](*End of Join*)            , rp[t]       , {t, 0, ftime}, DiscreteVariables -> {vel}] // First        ](*End of Function*);      The error that appears seems to be related to the fact that `u` remains unevaluated, as attempting to `Table` it outside of the program will reveal. I have added `DiscreteVariables -> {vel}` because I thought that since we are subjecting velocity to a sudden change it would be necessary. Is there a way of adding a list of working `WhenEvent`, one for each particle, to the system of equations? Many thanks


How to write data from Mathematica to an existing formated Excel file?

I have a sheet in an Excel file already formated: different colors, fonts, columns width and cells styles. I want to fill-out values from Mathematica into specific cells of that sheets, or use that sheet as a formated template to create a new sheets, "copying" the stylings and data in the corresponding cells.


Strange Behavior of NDSolve

I am trying to evaluate the following ODE numerically:               NDSolve[(2 + Sqrt[2] +s^2 -(-2 + Sqrt[2]) s^4 + s^6) /(1 + s^2)^2 yy[s] -(1 - s^2)^2 yy''[s] == 0 &&              yy[-1] == 0 &&   yy'[-1] == 1, yy[s], {s, -1, 1}]      and I surprisingly get the following error:               Power::infy: "Infinite expression 1/0.^2 encountered."     Infinity::indet: "Indeterminate expression 0.\ ComplexInfinity encountered."     NDSolve::ndnum: "Encountered non-numerical value for a derivative at s == -1.`."      One can verify directly that no infinities should appear at `s=-1`:               D[(2 + Sqrt[2] + s^2 - (-2 + Sqrt[2]) s^4 + s^6)/(1 + s^2)^2, s] /.  s -> -1          gives: 3 + 1/4 (-8 + 4 (-2 + Sqrt[2]))      But apparently, the ODE solver automatically divides by the factor in front of the `yy''[s]` term before computation. in this case we indeed find a singular               D[-(2 + Sqrt[2] + s^2 - (-2 + Sqrt[2]) s^4 + s^6)/((1 + s^2)^2 (1 - s^2)^2), s] /. s -> -1      Clearly, if one does not divide by the factor of the kinetic term, the ODE is well defined on the whole interval including the boundaries. Why does the solver divide? What can I do to prevent this? Or maybe there is some workaround?


Log does not reduce expressions

When solving an analytical expression, I need to take the `Log` of something. However, _Mathematica_ seems unable to reduce a simple Log of an exponential:               Log[E^x] // does not output 'x'      Why does this not work? Laurens


How can I make my plot continuous?

Looks like plots became of low quality in Mathematica 9? ![enter image description here](http://i.stack.imgur.com/GtDQ9.jpg) How to make _Mathematica_ to plot continuously? Logically current plot style is solid.


Problem with System`Graph and Combinatorica`Graph functionality conflict

I'm trying to generate a random geometric graph. When evaluating `HighlightGraph`, even if I am passing graph object _Mathematica_ always gives error like > A graph object is expected at position 1 in RowBox[{"HighlightGraph", "[", > RowBox[{InterpretationBox[StyleBox[RowBox[{...` How can I solve this problem. I am new to _Mathematica_ programming and am using _Mathematica_ 9\. my code is..               v = {};     For[i = 1, i <= n, i++, v = Append[v, {{Random[], Random[]}}]];     g = Graph[{}, v];     keyrings = {};             For[i = 1, i <= n, i++,                 keyring = {};                 If[P == K,                      For[k = 1, Length[keyring] < K, k++,                             keyring = Append[keyring, k]                         ],                     (* P > K *)                     For[k = 1, Length[keyring] < K, k++,                             key = Random[Integer, {1, P}];                             If[MemberQ[keyring, key] == False,                                 keyring = Append[keyring, key]                             ]                         ]                 ];                 keyrings = Append[keyrings, keyring];             ];     For[i = 1, i <= n, i++,                 For[j = i + 1, j <= n, j++,                      xi = Extract[Extract[Extract[v, i], 1], 1];                     xj = Extract[Extract[Extract[v, j], 1], 1];                     yi = Extract[Extract[Extract[v, i], 1], 2];                     yj = Extract[Extract[Extract[v, j], 1], 2];                     If[dist[xi, yi, xj, yj][[1]] < rc,                              If[          Extract[keyrings, {i}] ⋂             Extract[keyrings, {j}] != {},                                 g = AddEdge[g, {{i, j}}],                                 (* Else *)                                 Print["No secure link between ", i, " ", j]                             ]                         ]                 ]             ];     HighlightGraph[g, {NeighborhoodGraph[g, 1], Labeled[1, 1]}];     Print[ShowGraph[g]]     ]     ]      Please tell me where I have made a mistake.