title: How to Write into multiple files?

text: Note: this is fixed in version 9. * * * I want to put expressions into multiple files simultaneously, with the following code:               tex1 = OpenWrite["test1.txt"];     tex2 = OpenWrite["test2.txt"];          Write[{tex1, tex2}, "anything"]          Close[tex1];     Close[tex2];      Why is `test2.txt` empty? Why does it work correctly with `WriteString` instead of `Write`? Now of course I can always `Map` the `Write` statements over streams, or just go with `WriteString`, but since it would be convenient to use a list as `Write`'s first argument I did post this issue. Is it a bug?


title: Is there a way to solve the linear equation, Ax=b, in which A is a "non-constant" sparse matrix that depends on x?

text: I want to solve the Linear Equation, $Ax=b$ in Mathematica using Kylov subspace solver method preferably BICGSTAB(http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method). Suppose $A^{BE}_{\Delta,\Omega}$ is the following Laplacian+ Angular Momentum operator.![enter image description here](http://i.stack.imgur.com/RMoW8.png) Instead of using the finite difference matrices for evaluating $A^{BE}_{\Delta,\Omega}$, I am using the derivatives in Fourier space for higher accuracy. ![Derivatives](http://i.stack.imgur.com/wG316.png) where ![Description of operators](http://i.stack.imgur.com/cPwC3.png) How can one solve this Linear equation $A^{BE}_{\Delta,\Omega}\psi=\phi$ equation where $A=A^{BE}_{\Delta,\Omega}$, $x=\psi$, and $b=\phi$ in $Ax=b$? How can one extract $A^{BE}_{\Delta,\Omega}$ to plug it in `LinearSolve[A,b]`when it clearly depends upon $\psi$? I have used: `LinearSolve[A,b]` but as A ($A^{BE}_{\Delta,\Omega}$) depends on x ($\psi$), I do not get the correct result. One can solve this in MATLAB using the following function: `x = bicgstab(A,b)` Here it attempts to solve the system of linear equations A*x=b for x. A can be a function handle, afun, such that afun(x) returns A*x. Is there an analog of this function handle operation in Mathematica, in `LinearSolve`, where it can deal with the matrix A that depends on its x, in Ax=b? Any help is appreciated.


title: Finding the roots of a function with a parameter

text: I am using a differential equation method for finding the roots of a function. My function is much more complicated but I can illustrate my problem with a trivial example. The problem occurs when roots coincide and change direction. I use a differential equation method. The example equation is               eq = s^2 + 2 a s + 1;      where _a_ is a parameter (0 < _a_ ) and I wish to find the roots as the parameter is varied. To form the differential equation I take two derivatives and put them together as follows               deq = {D[eq, s], D[eq, a]} /. s -> s[a];     de = deq[[1]] s'[a] + deq[[2]] == 0     (* 2 s[a]+(2 a+2 s[a]) (s^\[Prime])[a]\[Equal]0 *)      I set up the differential equation so that I can solve with different initial conditions and over different ranges of the parameter _a_               ClearAll[sol];     sol[ic_, ae_] := s /. First[NDSolve[{de, s[0] == ic}, s, {a, 0, ae}]]      I have initial conditions from               ic = s /. Solve[eq == 0 /. a -> 0]     (* {-\[ImaginaryI],\[ImaginaryI]} *)      First case is fine               a1 = 0.999;     rts = sol[#, a1] & /@ ic;     ParametricPlot[Evaluate[{Re[#[a]], Im[#[a]]} & /@ rts], {a, 0, 0.999}]      ![Mathematica graphics](http://i.stack.imgur.com/wjOBS.png) Second case attempts to go further               a1 = 2;     rts = sol[#, a1] & /@ ic;      NDSolve gets stuck as it attempts to go "round the corner" at -1. Is there a way to get NDSolve to go round the corner? Can I get both solutions going round the corner and choosing opposite directions? (One solution should go towards the origin the other towards infinity.) Thanks for help and suggestions.


title: How to find the smallest root

text: I have a continuous, differentiable, monotonic, bounded function called `F[t]`. If `t -> Infinity` then `F[t] -> c`. I know `c`, and I want to find the smallest `t` value called `t*`, that suffices `F[t]=c` (I am sure there is one). Could somebody give me some hints about which functions to use for this task? Since I am afraid that `FindRoot` does not work in this case, because even if I know that there is a given `T` that `T` is smaller than `t*`, starting `FindRoot` from `T` as center won't give me the nearest solution, only a solution somewhere near `T` (Or am I wrong?). And neither does Solve work, because `F[t]` is not injective.


title: make mathematica recognize CCompiler and compile CUDA code on remote Windows machine

text: I have set up a _Mathematica_ remote kernel on a Windows 7 64 bit machine, which has Microsoft Visual Studio 2010 installed. When I start _Mathematica_ on the windows machine _Mathematica_ recognizes the C-Compiler without any problems and I can compile code using `Compile` as expected. But when I connect to the same machine via remote kernel, _Mathematica_ does not find any C-Compiler, i.e.               Needs["CCompilerDriver`"]; CCompilers[]      yields only an empty list `{}`. When using _Mathematica_ on the same machine locally the MS C-Compiler is listed when using `CCompilers[]`. How can I make _Mathematica_ recognize my local C-Compilers when connecting via remote kernel connection? Furthermore how can I compile CUDA-Code via the remote kernel connection, see below for the errors I get, when the MS C-Compiler is working? _Additional Information:_ I do connect to the windows machine from a Mac using Wolfram-SSH. I am running Cygwin OpenSSH on the remote windows machine. The setup seems to work fine otherwise. I tested remote connections to computers running Mac OS and Ubuntu Linux and I did not have any trouble with C-Compilers there. **Update (CCompiler working, still no luck with compiling CUDA code):** I have been able to get the MS C-Compiler working by explicitly setting               $CCompiler = {"Name" -> "Visual Studio",        "Compiler" ->         CCompilerDriver`VisualStudioCompiler`VisualStudioCompiler,        "CompilerInstallation" ->         "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0",        "CompilerName" -> Automatic}      But my next step is to get the NVCC compiler to work in order to be able to compile CUDA code using `CUDAFuncitonLoad`. Unfortunately my intended target `Windows-x86-64`, which corresponds to my `$SystemID` is not recognized as a valid target option any more (it is though when running any nvcc compilation locally on the remote machine). This can be seen by executing the following example code:               cudaString = "__global__ void addTwo(mint * A, mint length) {         int index = threadIdx.x + blockIdx.x*blockDim.x;         if (index < length)             A[index] += 2;     }"          res = CreateExecutable[cudaString, "addTwo", "Compiler" -> NVCCCompiler,        "CreatePTX" -> True, "CompileOptions" -> "-v",        "ShellCommandFunction" -> Print, "TargetDirectory" -> "C:\\temp",        "WorkingDirectory" -> "C:\\temp\\Working",        "Defines" -> {"mint" -> "int"}]     (*CreateExecutable::target: Target system specification "TargetSystemID" -> Windows-x86-64 is not available for NVIDIA CUDA Compiler installation "C:\Users\Wizard\AppData\ Roaming\Mathematica\Paclets\Repository\CUDAResources-Win64-9.0.2.0\CUDAToolkit\bin\*)      Manually adjusting the compiler paths does not help in this case, the following command gives me the same error as mentioned above:               res = CreateExecutable[cudaString, "addTwo", "Compiler" -> NVCCCompiler,        "CreatePTX" -> True, "CompileOptions" -> "-v",        "ShellCommandFunction" -> Print, "TargetDirectory" -> "C:\\temp",        "WorkingDirectory" -> "C:\\temp\\Working",        "Defines" -> {"mint" -> "int"},        "CompilerInstallation" ->         "C:\\Users\\Wizard\\AppData\\Roaming\\Mathematica\\Paclets\\\     Repository\\CUDAResources-Win64-9.0.2.0\\CUDAToolkit\\bin\\",        "XCompilerInstallation" ->         "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0",        "TargetSystemID" -> $SystemID]      **Update 2 (Changing`"TargetSystemID"`):** As you can see in the code snippet above `"ShellCommandFunction" -> Print` has been set, but I did not get any output except the error I mentioned above, i.e. > CreateExecutable::target: Target system specification "TargetSystemID" -> > Windows-x86-64 is not available for NVIDIA CUDA Compiler installation > "C:\Users\Wizard\AppData\ > Roaming\Mathematica\Paclets\Repository\CUDAResources- > Win64-9.0.2.0\CUDAToolkit\bin\ When setting the `"TargetSystemID"->"Windows"` (which is the wrong target) in the `CreateExecutable`-call above, mathematica asks for a correct `"XCompilerInstallation"`-path, which is a good sign. When I manually supply the path (as you can see in the call to `CreateExecutable` below) I get more information from the `"ShellCommandFunction"`, which I currently cannot make sense of (except that nvcc seems to be called in the right way):               cudaString = "__global__ void addTwo(mint * A, mint length) {             int index = threadIdx.x + blockIdx.x*blockDim.x;             if (index < length)                 A[index] += 2;         }";          res = CreateExecutable[cudaString, "addTwo", "Compiler" -> NVCCCompiler,        "CreatePTX" -> True, "CompileOptions" -> "-v",        "ShellCommandFunction" -> Print, "TargetDirectory" -> "C:\\temp",        "WorkingDirectory" -> "C:\\temp\\Working",        "Defines" -> {"mint" -> "int"},        "CompilerInstallation" ->         "C:\\Users\\Wizard\\AppData\\Roaming\\Mathematica\\Paclets\\\     Repository\\CUDAResources-Win64-9.0.2.0\\CUDAToolkit\\bin\\",        "XCompilerInstallation" ->         "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0",        "TargetSystemID" -> "Windows"]      Which gives me the output from the `"ShellCommandFunction"`: > call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" > x86 > > > "C:\Users\Wizard\AppData\Roaming\Mathematica\Paclets\Repository\CUDAResources- > Win64-9.0.2.0\CUDAToolkit\bin\nvcc.exe" -ptx -m32 --compiler-bindir > "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin" -arch=sm_10 -O3 > -v -Dmint=int -o "C:\temp\Working\addTwo.ptx" "C:\temp\Working\addTwo.cu" But also the following error messages (which I find confusing, because the path mathematica complains it cannot open is never created): > OpenWrite::noopen: "Cannot open > !(\"C:\\\Windows\\\m-1937a361-0128-49fa-8ead-8640028d2166\")." > General::stream: $Failed is not a string, InputStream[ ], or OutputStream[ > ]. ... and more errors that follow from the initial one


title: Setting individual CellContext for each notebook loses autocomplete suggestions

text: I'm running _Mathematica_ 9.0.1 under OS X. In order to have separate contexts for each of my notebooks, I used the instructions in the last part of the accepted answer from the following link: Is there a way to separate variables between multiple notebooks? To quote the relevant part of the answer: > "To set this automatically for all new notebooks, open the Options Inspector > (Ctrl/Command+Shift+O), and change the scope to "Global Preferences." Then, > the option CellContext is found under Cell Options -> Evaluation Options. > Change it to "Notebook." However I've found that after I do this, I lose auto-completion suggestions for symbols that I define in my notebook(s). Is there any way to fix this?


title: Solving functional equations in Mathematica

text: I am trying to solve functional equations in _Mathematica_ , but got nowhere. Just a simple example: $$f(x+y)^2=f(x)^2+f(y)^2$$ for all $x,y \in R$, assuming f is a real-valued function. How should I approach this problem in _Mathematica_ ?


title: Strange NSum behavior

text: If I do:                NSum[(i + 1)/(i + 2) LegendreP[i, 0] LegendreP[i, 0], {i, 0, Infinity}]      I get:               1.25216      If I do:               Sum[(i + 1)/(i + 2) LegendreP[i, 0] LegendreP[i, 0], {i, 0, 1000}] // N      The result is:               2.40862      This last result is larger than the infinity sum, but the sum terms are all nonnegative. That is not possible. Am I wrong or is Mathematica?


title: Incorrect information displayed when slider is moved (intermittent)

text: All, the following code graphs 10 different solutions for a first order ODE and allows the user to modify certain equation parameters to see how the graph is affected:               Manipulate[     (*Find 10 different solutions for the ODE*)     eqn = {a y''[t] == b y[t] + d, y'[0] == c};     sol = DSolve[eqn, {y[t]}, {t}];     func[t_] = y[t] /. sol[[1]];     t[x_] = Table[func[t] /. C[1] -> j, {j, 1, 10}];          (*Display graph*)     Plot[Evaluate[t[x]], {t, -tmax, tmax}],           (*Variables to parameterize*)     {a, 1, 5, 1}, {b, -1, 1, 1}, {c, -10, 10, 1},      {d, 0, 100, 10}, {tmax, 1, 10, 1},          (*Aesthetic labeling stuff*)     Delimiter,     Dynamic[Style[Row[{"Input: ", a , " y''(t) = ",      b, " y(t) + ", d, ", y'(0) = ", c}], 12]],     Delimiter,     Dynamic[Style[Row[{"Output: ", func[t]}], 12]],          (*Misc. Manipulate stuff*)     ContinuousAction -> True, SaveDefinitions -> True,      TrackedSymbols :> {a, b, c, tmax, d}]      The problem that arises is the equation that is displayed after the "Output:" label. If you are patient enough, and move around the sliders (I have been varying parameter d), you will occasionally see the equation display as something like: ![enter image description here](http://i.stack.imgur.com/2S0nx.png) When it should be: ![enter image description here](http://i.stack.imgur.com/CiBs6.png) There are also some funky little things I have noticed like the slider "dragger" in picture 1 is still highlighted even after I release it. Are there any glaring things that I am doing incorrectly that could be causing these symptoms? Is there anyone else that can reproduce the problem? One other thing - I cannot make this problem happen if I use the stepper controls instead of using my mouse to change the value of the slider.


title: Expectation problem using empirical distribution

text: I am having trouble with this Mathematica command:                Probability[ x + y + z > 14, {x, y, z} \[Distributed]       ProductDistribution[{DiscreteUniformDistribution[{1, 6}], 3}]]`      outputs 5 / 54. What I would like to do is use the EmpiricalDistribution sort of like this:                Probability[x + y + z > 14, {x, y, z} \[Distributed]      ProductDistribution[{EmpiricalDistribution[{1, 2, 3, 4, 5, 6}], 3}]]      of course, that does not work and just spits out the command. How can I get the Empirical Distribution to work like that?


title: Numerical sum does not give consistent results

text: Consider the function               λ[n_] = Sqrt[2 n];     ϕ[n_, x_] = 1/Sqrt[2^n n! Sqrt[π]] HermiteH[n, x];     f[x_] = Sum[2 Re[(-1)^(n + m) (1/(λ[m] + λ[n + 1]) + 1/(λ[n] + λ[m + 1]))                 If[n != m, 1, 1/2]] ϕ[n, x] ϕ[m, x] E^-x^2, {n, 0, 100}, {m, n, 100}];      Why is               f[-4.0] == 4.9697      while               f[-4] // N == 1.07681      ? The second result is correct as you can check by using `SetDelayed` in the definition of `f`. This discrepancy has to do with approximations. It would be good to fix it, since computations are faster if the function is defined with `Set`. I would also appreciate suggestions to evaluate this sum more efficiently. Thank you!


title: Is it possible to verify the accuracy of a file downloaded using URLFetch

text: **Objective:** I am trying to save a HTML file using the **URLFetch** function (native to Mathematica 9 onward). Sometimes the file is huge. **Question:** Is there a way to check/verify (using the headers or other parameters native to URLFetch) that the **COMPLETE PAGE HAS BEEN DOWNLOADED** , i.e. the page was not partially downloaded? Is there a protocol say like MD5 for file downloads, which allows one to confirm that the HTML file's contents were completely downloaded? (or can I be _assured_ that URLFetch returns/transfers control **ONLY** after the COMPLETE page has been fetched?) **Related questions** :   * IF the download was partial (not complete), will the "STATUS" (from the URLFetch) still be 200 ?   * Can this be solved using **Import** function


title: How to increase the number of minor ticks in a plot?

text: I want to increase the number of minor ticks in a plot, but I don't want to label them. I searched through this site and also _Mathematica_ documentation, but I didn't find any solution yet. Could anyone please tell me how to do this. For an example:               Plot[2*Sin[x], {x, 0, 10}, Frame -> True,       FrameTicks -> {True, True, False, False}, Axes -> True,       AxesOrigin -> {0, 0}]      I want to get 10 minor tick marks in between 0 and 1 and so on (in between major tick marks on both axis). ![Here is the output plot](http://i.stack.imgur.com/C4jSZ.png)


title: Conditional break point in Wolfram Workbench?

text: Is it possible to set up a conditional break point in Wolfram Workbench? For example I want the code to stop if an index `i` is equal to a given value.


title: Solving an ODE with parameters and conditions

text: I am trying to use Mathematica to solve a relatively simple ODE involving parameter(s). I would like to use a set of conditions to solve for the particular solution of the ODE. I understand how to make Mathematica find values for the constants that arise during the process of solving the ODE, but what about solving for constants/coefficients already present in the original ODE? Here is a simple example involving Newton's Law of Cooling... ![enter image description here](http://i.stack.imgur.com/rivKO.jpg) Here is the code I tried:                  DSolve[          {           T'[t] == -k*(T[t] - Ta),           T[0] == 70,           T[1/2] == 110,           T[1] == 145           },          {T[t], t, k},          {t}          ]      I feel like I need a two step process... first solve the ODE with the parameters, and then solve for the parameters afterwards. I'm just not sure where to start. Thank you in advance!


title: Making data persistent, as in xmgrace

text: I've been using xmgrace for quite a long time as my favorite solution for scientific data manipulation and plotting. These data often come from home- made fortran programs, in the form of, e.g., a formatted file with `x y z f` columns. I discovered that Mathematica (v9 here) is quite remarkable for this purpose. In xmgrace, the data you are plotting is stored (made persistent) in the xmgrace file itself (file.agr), which is very convenient because sharing the xmgrace file both shares the plot and the data being plotted. Is it possible to make the data stored inside the Mathematica (.nb) file? Note: the answer should be compatible with any quantity of data. For illustration purpose, my xmgrace file can exceed 500 MB.


title: Label area on plot

text: I created the following plot using _Mathematica_ : ![Mathematica plot](http://i.stack.imgur.com/JzMQy.png)               (* defining functions *)     msp[h_, a_, b_, c_] :=         Piecewise[{{c + b*(1.5*h/a - 0.5*(h/a)^3), h <= a}, {0, h == 0}}, b + c];     mex[h_, a_, b_, c_] := Piecewise[{{c + b*(1 - Exp[(-3*h)/a]), h != 0}}, 0];     mga[h_, a_, b_, c_] := Piecewise[{{c + b*(1 - Exp[(-(3*h)^2)/a^2]), 0 < h}}, 0];          (* plot *)     Show[Plot[{msp[x, 2, 3, 1], mex[x, 2, 3, 1], mga[x, 2, 3, 1]}, {x, 0, 2.5},        PlotRange -> {{0, 2.5}, {0, 5}}], ImageSize -> {500, 400}]      I would like to mark the y axis from 0 to 1 and the x axis from 0 to 2 using curly braces like it is done here (E(x)): ![Example](http://i.stack.imgur.com/O5Nq2.png) Is it possible to do this with _Mathematica_?


title: How to substitute the Skip function in special cases?

text: filedata={"    1       2578Hot Pink            47:21:17  9512971  ",               "    2        294Pale Green          24:57:18  4437289  ",               "    3       2497Light Yellow        39:40:57  4987642  ",               "    4       2010Turquoise           16:04:17  3290855  "}      There is an external file.   You open a Stream.   You Skip to a far postion.   It takes a long time for a large file.   How can one conceive a more direct method for a special   straightforward highly regular file structure like this?   We got an index and know the file size anyway.   A low level file function approach? * * * ## **Update** Records in file: 100.000.000   Set StreamPosition to: 60.000.000   Time needed: 40 seconds That is: Skip and SetStreamPosition takes the same chunk of time.


title: Value of $BaseDirectory within Ant script?

text: I'm using an ant script to install my application from the Workbench (as suggested in this answer). In past I've used two ways of specifying the destination for the build:   1. Hard-coded directory, like `/Users/me/Library/Mathematica/Applications`. This would be fine for a single computer, but I store the code in a versioning system, and access it from computers having different filesystems (e.g., MacOSX laptop, linux desktop). It is inconvenient to change the ant build file for each build.   2. Setting an environment variable on each computer (`$MMA_APP_DIR`, say) and using `<property environment="env"/>` within ant to get that variable using `${env.MMA_APP_DIR}`. Much better than option #1, since I don't have to change the code itself, but still an inconvenience. _Mathematica_ 's, `$BaseDirectory` and `$UserBaseDirectory` are the destinations I'm after. **How can I access the values of these variables from the ant script?** They are built into the Workbench framework, showing up as destination folders when using the Application View to export to an archive or to a folder. I've yet to discover how to access them.


title: Accessing data on local machine from remote kernel

text: I have a remote kernel on a server that I would like to use to process some data. The connection works, i.e, I'm able to use the local front end and the remote kernel. However, I cannot figure out how should I access from the remote kernel the data that are on my local machine. I thought I could simply use `Import` with the path to my computer and to the file that I want to import, but I didn't succeed. Something like:               Import["computerName@ip_address:/Users/myUserName/Desktop/data.txt","Table"]      > Import::nffil: File not found during Import. >>


title: Overlay : zoom, graphic tools, get coordinates save as etc

text: I used Jens' legendmaker to `Overlay` graphics to get a nice legend on my `ListPlot`. My question is if is there any way to make the output from `Overlay` behave like output from `ListPlot` in terms of the ability to zoom in to investigate, get co-ordinates, drawing tools, ability to right click on the graphic itself and save high resolution graphic as a host of things etc? I was able to right click the cell and save selection as a very low resolution jpeg. Thanks, **EDIT:**               boundaryplot = ListPlot[{H0SPlot, H0DPlot},PlotRange -> Full]     opts = Sequence[Background -> LightOrange, RoundingRadius -> 10];     labels = {"H0S", "H0D"}     Overlay[{boundaryplot, legendMaker[labels, opts]}, All, 1,Alignment -> {0.5, 0.5}]      While the `Overlay` options enable me to zoom in etc, when I right click on the image to `save graphic as` , I tried jpeg and pdf, it only saves the `ListPlot` and not the `Legend`. When I right click on the cell itself and use `save selection as` then I am able to save as jpeg something lower-res that also includes the legend.


title: Using Physical Constants in V9

text: How is one supposed to work with physical constants in _Mathematica_ V9? When I first open _Mathematica_ , physical constants such as `SpeedOfLight` are not recognized. If I load the PhysicalConstants package using:               << PhysicalConstants`      I get the following error message: > General::obspkg: "!(\"PhysicalConstants`\") is now obsolete. The legacy > version being loaded may conflict with current Mathematica functionality. " However, at this point `SpeedOfLight` is properly defined!


title: Computing the equivalence classes of the symmetric transitive closure of a relation

text: I have a list of pairs, for example:               pairs={{13, 10}, {12, 14}, {10, 36}, {35, 11}, {3, 5}, {1, 6},     {20, 24}, {21, 22}, {33, 7}, {31, 8}, {31, 27}, {32, 25},      {21, 35}, {34, 19}, {18, 15}, {14, 16}, {9, 5}, {4, 7},      {1, 13}, {15, 2}, {6, 36}, {4, 34}, {8, 2}, {9, 3}, {25, 20},     {19, 26}, {22, 11}, {23, 12}, {32, 28}, {30, 33}, {23, 16},     {24, 17}, {29, 27}, {26, 30}, {17, 28}, {18, 29}};      `pairs` can be seen as the definition of a relation $R$. $x$ and $y$ satisfy the relation if and only if `{x,y}` $\in$ `pairs`. I need to compute the equivalence classes of the symmetric transitive closure of $R$. In other words, I need to compute a list `eqvclss`. The elements of `eqvclss` are lists themselves. For example, 13, 10, 36, 6, 1, ... should all be in the same list in `eqvclss`. (If you understand that, then I explained the question properly; if you don't, say so in the comments so I can try to improve).


title: Assuming monotonicity and concavity

text: I have an expression that I would like to evaluate:               2 phi''[1 + a (-1 + u[10])] phi'[q]^3 > phi''[q] phi'[q] phi'[1 + a (-1 + u[10])]^2      Is there any way of telling Mathematica that the function `phi` is strictly increasing and convex?


title: Predictive code completion and custom functions in contexts

text: Suppose I work for organisation PQR, and have been developing a suite of packages, `PQRUtilities`, `PQRVisualization` etc, all of which are neatly arranged in a context `PQR`. They can all then be loaded with a single package call `Get["PQR`"]`. The only content of the PQR package is               BeginPackage["PQR`" ,{"PQR`PQRVisualization`","PQR`PQRUtilities`"}]     (* Exported symbols added here with SymbolName::usage - but nothing here *)         Begin["`Private`"]     (* Implementation of the package - nothing here either*)       End[]         EndPackage[]      I have noticed that if I call the subsidiary packages directly with `Get["PQR`PQRVisualization``"]` or the `Needs` equivalent, I get predictive code completion pop-ups including my custom functions. However, if I just call `Get["PQR`"]`, my functions are loaded but I do not get the nice predictive code completion. Ultimately all these packages will be put in the `Autoload` part of the path, so maybe this doesn't matter. I would like to be able to provide the simpler way to load all the custom packages I've developed, and still enjoy the benefits of the code-completion suggestions. Some of my function names are quite long, e.g. `PQRScatterGraph`. Is there a way I can get functions from packages loaded in this way to be visible to the code completion functionality?


title: why set values in this way doesn't work?

text: question is as follows define a list               ttt={1,2};      and if I set values in this way               {ttt[[1]],ttt[[2]]}={3,4}      then the value of list ttt now becomes {3,4} Now I try this               f:={ttt[[1]],ttt[[2]]}      then `?f` will show that `f:={tmp[[1]],tmp[[2]]}` then if I just write               f={3,4}      this will not affect the values of list ttt . **the question is that I want the values of list ttt changes as well when I set values to f. How to do this?** * * * **More Question!!** why the following code didn't change the value of ttt??               Table[With[{i = i}, Defer@ttt[[i]]], {i, 1, 2}] = {111, 222}      while               Table[With[{i = i}, Defer@ttt[[i]]], {i, 1, 2}]      really gives               {ttt[[1]],ttt[[2]]}


title: how do I can create a list of the first interval such as [-10+Sin [k], 10+Sin [K]]

text: A (k) =the closed interval [-10+Sin [k], 10+Sin [k]] How do I can create a list of the first 20 of such interval The find the intersection of the first 14 of them


title: How to set the working precision globally? $MinPrecision does not work

text: I want to increase the precision globally to `50` at least, but `$MinPrecision` does not work.               $MinPrecision = 50;     x = Sin[2.]     (* -> 0.909297 *)          Precision[x]     (* -> MachinePrecision *)      How to set the working precision globally, i.e., make all the calculations in the notebook use the new precision?


title: Constrain plot points to below a certain line

text: I have a set of curves that take on large values when approaching 1. I'm trying to create a straight line with certain slope and then truncate the plot for any curve that goes above that line for any value of x. This is my current code:               lm := Sqrt[M^2 - 1]     C1 := 2/lm     C2 := ((1.4 + 1)*M^4 - 4 M^2 + 4)/(2*lm^4)                pr1[o_, M_] := (C1*(o*Pi/180) + C2*(o*Pi/180)^2)*1.4*M^2/2 + 1;          Plot[Table[pr1[o, M], {o, {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}] // Release, {M, 1, 3},         AxesOrigin -> {1, 0}]      ![enter image description here](http://i.stack.imgur.com/OmLbV.png)


title: Reduce can't reduce an equation without appropriate assumptions

text: When there are three unknowns (`x`, `y`, `z`), _Mathematica_ can solve it:               Reduce[ Abs[x] + Abs[y] + Abs[z] == 1 && z != 0, {x, y, z},              Reals, Backsubstitution -> True]      for four variables (`x`, `y`, `z`, `t`), _Mathematica_ can't return a result in reasonable time:               Reduce[ Abs[x] + Abs[y] + Abs[z] + Abs[t] == 1 && t != 0, {x, y, z, t},              Reals, Backsubstitution -> True]      _Maple_ can solve this quickly: ![enter image description here](http://i.stack.imgur.com/GCcZk.png) Is it possible to solve this with _Mathematica_?


title: Plotting Fresnel function

text: I am trying to plot the partial sums and the cesaro means of the function $\sqrt{|x|}$ and for $a_{n}$, I obtained the following code which contains FresnelS.               (-((Sqrt[2] FresnelS[Sqrt[2] Sqrt[n]])/n^(3/2)) - (Sqrt[2] FresnelS[Sqrt[2] Sqrt[Abs[n]]])/Abs[n]^(3/2) + (2 Sin[n \[Pi]])/n + (2 Sin[\[Pi] Abs[n]])/Abs[n])/(2 Sqrt[\[Pi]])      Now my question is is it possible to graph such function using Mathematica? I have tried many examples using trial and error and some of the my examples also contain BesselJ which can't be graph. Hence I would like to know if it is true that if there is BesselJ and FresnelS in the code, then the graph cannot be drawn using Mathematica. Please correct me if I am wrong. I am graphing out its graph using this code:               f[x_] := Sqrt[Abs[Mod[x, 2 Pi, -Pi]]];     s[k_, x_] := ???     partialsums[x_] = Table[s[n, x], {n, {4}}];      c[n_, x_] := (1/n) Sum[s[m, x], {m, 0, n - 1}]     Plot[Evaluate[{f[x], partialsums[x], c[{4}, x]}], {x, -Pi, Pi},     PlotLegends -> {"f(x)=x", "Fourier, 4 terms", "Cesaro, 4 terms"},      PlotStyle -> {{Blue}, {Dashed, Thickness[0.006]}, {Red,Thickness[0.006]}}]


title: Operate on several lists to create one list

text: How do you put corresponding values from different lists together according to some operation? E.g. I have three lists giving the velocity in the x, y and z direction respectively. I'd like create one list giving the 2-norm, $\sqrt{x^2+y^2+z^2}$. I would be able to do it procedurally by using for example MapIndexed on one of the lists toghether with Part, I suppose. But I'd like to know if there is a more elegant solution.


title: ReadList problem related to Record type

text: A simple file reading issue is baffling me here. I am reading a around **200 MB** textual file in `.dat` format. Now the file contains **many lines** but to phrase my problem I am taking here first two lines from the example file.               str = "Tue 1 Jan 2013 23 : 00 : 01; 17; {}; 32.5; 0.\nTue 2 Jan 2013 2 : 20 : 01; 47; {3,4}; 3.5; 110.";      Now I want to use `;` and newline `\n` as my `RecordSeparators` and it works as expected.               ReadList[StringToStream[str],{Record, Record, Record, Record, Record},     RecordSeparators -> {"\n", ";"}]      > {{Tue 1 Jan 2013 23 : 00 : 01, 17, {}, 32.5, 0.},{Tue 2 Jan 2013 2 : 20 : > 01, 47, {3,4}, 3.5, 110.}} But if I want to specify the `Type` of each separate `Record` using for example `{String, Number, Expression, Number, number}` above code fails to work. The error is the following. > Read::readn: Invalid real number found when reading from StringToStream[Tue > 1 Jan 2013 23 : 00 : 01; 17; {}; 32.5; 0. Tue 2 Jan 2013 2 : 20 : 01; 47; > {3,4}; 3.5; 110.]. >> Is this problem solvable or I need to change the formatting of my input .dat file in a way so that it works with `ReadList`? PS: If I need to change the file format what will be best separator to use in this context?


title: Mathematica: finding min/max in list

text: I have a list of coordinates like this one:               {{x1,y1},{x2,y2},{x3,y3},...,{xn,yn}}      I need to get the minimum and the maximum of all x-values and the minimum and maximum of all y-values. Is this possible? If I use the in-built `Min` function for example gives me just the minimum of all x and y values...


title: Can CDF file embedded in a web page receive external parameters?

text: I know that I can embed a CDF file inside a web page by using:   1. The embed tag.   2. An object tag with an embed tag inside (better than 1).   3. Using the JavaScript provided by Wolfram (better than 2). My question is how can I pass some data to the CDF file. In the case of Flash, there is a flashvars attribute precisely for this, but I can't find the equivalent for this in Wolfram's CDF deployment documentation. I need this because I plan to embed a CDF in a set of pages that are similar but each for a different set of data. And I want to generate a single CDF for all of them. If this is not possible in this direction, I would be interested in knowing about solutions in the opposite direction: reading the DOM from the CDF file as this would solve my problem too.


title: Finding specific compositions of an Integer

text: I need to find all compositions of an integer L wherein all parts do not exсeed l and parts less then l cound not be neighbor. Here is my code               test[arr0_, ll0_] :=       Module[{arr = arr0, ll = ll0},        result = True;        For[i = 1, i < Length[arr], i++,          If[arr[[i]] < ll && arr[[i + 1]] < ll, result = False]];        result        ];     frag[L0_, l0_] :=       Module[{L = L0, l = l0},        part = IntegerPartitions[L, 2*Ceiling[L/l] + 1, Range[l]];        part = Flatten[Map[Permutations[#] &, part], 1];        Select[part, test[#, l] &]        ];     frag[9, 3]          Output: {{3, 3, 3}, {3, 2, 3, 1}, {3, 1, 3, 2}, {2, 3, 3, 1}, {2, 3, 1, 3}, {1, 3, 3, 2}, {1, 3, 2, 3}, {1, 3, 1, 3, 1}}      I guess Mathematica allows to solve this problem much more easier


title: Can I use SelectComponents with measurements that take into account the value of underlying pixels?

text: Normally, we can ask for the mean, median, etc. underlying pixel values for morphological components with the command:               ComponentMeasurements[{MorphologicalComponents[img], img}, "MeanIntensity"]      I'm looking to use SelectComponents to select components based on their mean or median underlying pixel values. However, commands like the following:               SelectComponents[{MorphologicalComponents[img], img}, "MeanIntensity", # < 0.4 &];      Seem to simply fail. Is there a way to proceed? Clarification - Actually, let me be a bit more specific about my question. I mean to first select MorphologicalComponents of a modified version of the image, specifically after running a filter on it. I then want to prune morphological components based on pixel values in the original unfiltered image. So I'd like to do something like this:               SelectComponents[{MorphologicalComponents[LaplacianFilter[img,3]], img}, "MeanIntensity", # < 0.4 &];


title: Visualizing vector spherical harmonics

text: I have painstakingly derived the vector-spherical harmonics $\mathbf{V}_{J,\,M}^\ell(\theta, \phi)$, which are the generalization of ordinary spherical harmonics $Y_\ell^m(\theta, \phi)$ to vector fields. But now, I would like to visualize them. The vector-spherical harmonics takes three integers ($\ell$, $J$, $M$), and yields a 3D vector field on the surface of a sphere ($\theta$, $\phi$). The integers are subject to the constraints: $J\geq0$, $\ell\geq0$, $|J-\ell|\leq 1$, $|M|\leq J$. The function `VectorSphericalHarmonicV` below generates a 3-component _complex_ vector.               Clear[ϵ]; (*Polarization vector*)     ϵ[λ_] = Switch[λ,        -1, {1, -I, 0}/Sqrt[2],         0, {0, 0, 1},         1, {1, I, 0}/Sqrt[2]   ];          Clear[VectorSphericalHarmonicV];     VectorSphericalHarmonicV[ℓ_, J_, M_, θ_, ϕ_] /;        J >= 0 && ℓ >= 0 && Abs[J - ℓ] <= 1 && Abs[M] <= J :=        Sum[         If[Abs[M - λ] <= ℓ, ClebschGordan[{ℓ, M - λ}, {1, λ}, {J, M}], 0]*         SphericalHarmonicY[ℓ, M - λ, θ, ϕ]*ϵ[λ], {λ, -1, 1}   ]          (*Examples*)     VectorSphericalHarmonicV[1, 1, -1, θ, ϕ]     VectorSphericalHarmonicV[1, 1, 0, θ, ϕ]     VectorSphericalHarmonicV[1, 1, 1, θ, ϕ]      Honestly, not sure what the best visual representation is. But, I am thinking a good one is to display a bunch of vectors on the surface of a sphere in the spirit of this one: ![enter image description here](http://i.stack.imgur.com/e0U38.png) A sticking point for me is how do I tell _Mathematica_ to display vectors ONLY an the surface? Also, because these vectors are complex, maybe the vectors can be colored to indicate the phases? Perhaps you have a better way to represent these functions?


title: Need Help Writing (a Pascal) Matrix in Mathematica

text: I want to write a function $f[n]$ in Mathematica which gives me an $n\times n$ lower triangular Pascal matrix with a row of zeros in between each nonzero row. That is, I want the matrices \begin{pmatrix} 1&0&0\\\ 0&0&0\\\ 1&1&0\\\ \end{pmatrix} \begin{pmatrix} 1&0&0&0&0\\\ 0&0&0&0&0\\\ 1&1&0&0&0\\\ 0&0&0&0&0\\\ 1&2&1&0&0\\\ \end{pmatrix} \begin{pmatrix} 1&0&0&0&0&0&0\\\ 0&0&0&0&0&0&0\\\ 1&1&0&0&0&0&0\\\ 0&0&0&0&0&0&0\\\ 1&2&1&0&0&0&0\\\ 0&0&0&0&0&0&0\\\ 1&3&3&1&0&0&0\\\ \end{pmatrix} Thanks for your help.


title: Simplify the multiplication such as $a*(b+c)$ to $a*b+a*c$

text: I am trying to solve this problem here but have to understand basics. Suppose I have a multiplication such as $a*(b+c+d+...+x)$. How can I multiply it to the result $a*b+a*c+...+a*x$? **Trials** > **[Not working]** Reduce[(a + b)*c] > > **[Not working]** Simplify[(a + b)*c] or FullSimplify[(a + b)*c]


title: Read return value as string by Mathlink.h

text: I'm using "mathlink.h" to call _Mathematica_ from a C program. I send a computation to _Mathematica_ and its return result is a very big number (100 digits). Hence, I want to read that number as a string. How can I do it using _MathLink_? Thanks,


title: Can I compile a function containing ArcTanh?

text: Can I compile a function that contains ArcTanh[]? The following doesn't work               Needs["CCodeGenerator`"]     c = Compile[ {{x}}, ArcTanh[x]^2];     c[2.5]      _Mathematica_ gives me > >     "CompiledFunction::cfn: Numerical error encountered at instruction 1; >      proceeding with uncompiled evaluation>>" >   However, in the answer to this question, a reply indicates that `ArcTanh` can be compiled.


title: Removing an extra curly braces when using Grid with an If statment

text: I use `Grid` to align controls in Manipulate. Here is a simple example               Grid[{          {name1,Control2,value1},          {name2,Control1,value2}         }]      The 3 fields above come out aligned automatically, even when one field, such as name, is longer than another, and `Spacing` can be used to control field width for all controls at once. A problem shows up when I need to use an `If` statement to build controls based on selection used in previous control:               Grid[{          {name1,Control2,value1},               (*now make a control based on above value*)               {Dynamic[If[name1==1,                      {name2,Control1,value2},                      {name3,Control3,value3}                     ]                  ]          }         }]      This works well, and allows me to change the controls that appear on the UI based on a selection that was made in another control but the problem with the above is that it gives an extra set of `{}` coming out from inside the `If` needed grouping which ends up messing up the alignment. I think I need to use `Sequence` or some other function to remove the inner `{}` but can't figure the syntax. I made below a simple working code to illustrate               Manipulate[      eq,           Grid[{             {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {Dynamic[If[eq == 1,                {"v1",            Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],            Dynamic[v1]            },                {"v2",            Manipulator[Dynamic[v2, {v2 = #} &], {0, 2, .1}],            Dynamic[v2]            }           ]], SpanFromLeft         }}       ],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      which gives ![enter image description here](http://i.stack.imgur.com/IUdoe.png) You can see that the whole expression was treated as if I wrote               Grid[{          {name1,Control2,value1},          {{name2,Control1,value2}}         }]      I tried using `First`, `Sequence` but can't get it to come out correct. Again, I need to keep the 3 fields in each `Row` separate and in a List. I can't just use `Row` since it means each row will collapse to become one field, not three fields, and I lost the alignment I needed, i.e. I can't just write               Manipulate[      eq,           Grid[{             {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {         Dynamic[If[eq == 1,                Row[{"v1",             Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],             Dynamic[v1]             }],                Row[{"v2",             Manipulator[Dynamic[v2, {v2 = #} &], {0, 2, .1}],             Dynamic[v2]             }]           ]], SpanFromLeft         }        }            ],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      ![enter image description here](http://i.stack.imgur.com/SzDCS.png) Any idea how to make the above work and remove those extra `{}`? **edit** Let me just clarify why using `Row` as a solution does not work. Compare the following 2 examples               Manipulate[eq,           Grid[{        {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {Dynamic[If[eq == 1,               Row[{"v1", Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],Dynamic[v1]}],               Row[{"v2", Manipulator[Dynamic[v2, {v2 = #} &], {0, 2, .1}], Dynamic[v2]}]         ]]        }             }],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      ![enter image description here](http://i.stack.imgur.com/abtcG.png) We can see that the whole `Row` was treated as one field. I want to the above to come out _as if_ I have written this               Manipulate[eq,           Grid[{        {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {"v1", Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],Dynamic[v1]}             }],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      ![enter image description here](http://i.stack.imgur.com/5uBzq.png) You see the difference? This is the important part. thanks.


title: Compute Correlation between two binary variables

text: > $X_1$ and $X_2$ are two binary stochastic variables with simultaneous > probabilitydistribution: > > $$ \begin{matrix} &X_2=0&X_2=1\\\ X_1=0&0.30&0.17\\\ X_1=1&0.08&0.45 > \end{matrix} $$ I want to calculate the correlation between $X_1$ and $X_2$.               Correlation[{{0.30, 0.17}, {0.08, 0.45}}]      The output I get is `{{1,-1},{-1,1}}` The solution I seek is: `0.05011` It should be pretty simple, but I have no idea where I am wrong.


title: How to calculate expected return, row by row in matrix?

text: Please help me, I'm writing my project and dont know how to solve this big matrix: ![enter image description here](http://i.stack.imgur.com/SOxL2.png) I have to compute return row by row: 1st row: (18.32-17.14)/17.14 ; (19.17-18.32)/18.32 .... 2nd row:(11.79-13.86)/13.86 ; (11.37-11.79)/11.79 ....


title: Problem when defining function through NIntegrate and NDSolve and Interpolation - Bug?

text: More than a single question, I have some doubts about the output of certain functions when defined through the result of other calculations. I am an active user of Mathematica, but maybe I haven't read deeply enough about Attributes or related things. Here is the following minimal example:               {tini, tfin} = {-Log[100], 0};     firstFuncK=NDSolve[{D[f[t,k],t]+f[t,k]^2+(1-t)*f[t,k]==3/2*     (1+k^2),f[tini,k]==1},f,{t,tini,tfin},{k,0.001,10}]          secondFuncK[t_?NumberQ, k_] :=      Exp[NIntegrate[f[et, k] /. firstFuncK, {et, tini, t}]]          thirdFuncK[t_,k_]:=Log[N[secondFuncK[t,k]/secondFuncK[-Log[100],k]]][[1]]      Here comes the first question, why exactly do I need the `[[1]]` or `First` and the `N`. Without them I get:               thirdFuncK[-1,0.01]     {Log[4.11782/secondFuncK[-Log[100],0.01]]}      It is weird that Mathematica doesn't output a number, since secondFuncK is already numerical. And I don't understand why I get a List in this case:               thirdFuncLin[et_]=thirdFuncK[et,0.01];      Output:               thirdFuncLin[-1]     {1.41532}          Plot[thirdFuncLin[tt],{tt,-4,0}]      ![thirdFuncK](http://i.stack.imgur.com/poJ4F.png) But the real problem is when I use this function to interpolate:               thirdInterp=Interpolation[Table[{et,thirdFuncLin[et][[1]]},{et,-Log[100],0,0.01}]]      I get a completely different result:               Plot[thirdInterp[tt], {tt, -4, 0}]      ![thirdInterp](http://i.stack.imgur.com/39TyC.png) I know there are related questions of simple mistakes people do, but I haven't found anything that helps me really to understand the core of this problem. Thanks for any suggestions also on style or optimization.


title: Listing matrices up to symmetry

text: I am interested in the equivalence relation on N x N binary matrices, in which two matrices are equivalent if one can be obtained by rotating/reflecting the other. I would like to obtain a list `binclasses = { {B1, m1},...{Bk, mk} }`, where Bi is a representative element of class i, and mi is the size of that class. (Of course the requirement of binary matrices is somewhat artificial here, so the question could be rephrased for matrices taking values in a finite set). For N =2, I am looking to obtain the list `binclasses = {{{{0, 0}, {0, 0}}, 1}, {{{0, 0}, {0, 1}}, 4}, {{{0, 0}, {1, 1}}, 4}, {{{0, 1}, {1, 0}}, 2}, {{{0, 1}, {1, 1}}, 4}, {{{1, 1}, {1, 1}}, 1}}` My thought process so far has been as follows:   1. Define a list `binlist` of all N x N binary matrices.   2. Choose an element `currmat` from `binlist`, and generate a list `currsym` of all rotations and reflections of `currmat`.    3. Define a new list `binminsym` which is `binlist` with all elements of `currsym` removed.   4. Add the pair `{currmat, Length[currsym]}` to a new list `binclasses`.   5. Set `binlist = binminsym`, return to step 1.  I am guessing that this is not a particularly efficient approach, and am curious to know how one could better go about the problem. **EDIT** A second update, I have improved on the original code, however, it still runs slowly (original edit left below this for information). In this variation I first group binary matrices by the number of 1s, and the number of adjacent 1s; this means that fewer list elements need be checked against each other. At the moment for the 4 x 4 case, this version takes a little over 4 minutes to identify the 8548 equivalence classes, compared to the 17 minutes of the previous method.               (* sTotal function gives total of all matrix entries *)     sTotal[matrix_] :=        Sum[matrix[[i, j]], {i, 1, Length[matrix]}, {j, 1, Length[matrix]}];          (* eTotal function gives total number of adjacent non-zero entries *)          halo[matrix_] :=      Module[{cmat},       cmat = ConstantArray[0, {Length[matrix] + 1, Length[matrix] + 1}];       cmat[[1 ;; Length[matrix], 1 ;; Length[matrix] ]] = matrix;       cmat]          eTotal[matrix_] :=        Sum[halo[matrix][[i, j]] (halo[matrix][[i, j + 1]] +            halo[matrix][[i + 1, j]]), {i, 1, Length[matrix]}, {j, 1,          Length[matrix]}];               Timing[      Clear[mdim, blist, bgrlist, binclasses, binreps, currbg, currmat,         currsym]            mdim = 4; (*matrix dimensions*)      blist = Tuples[{0, 1}, {mdim,          mdim}];  (* All square binary matrices of size mdim *)            (* blist grouped into sets of matrices with equal number of 1s, and \     equal adjacent 1s *)      bgrlist = GatherBy[blist, {sTotal, eTotal}];            (* Initialise list of equivalence classes *)      binclasses = {};      binreps = {};      ]               Timing[      Do[       Do[         currbg = bgrlist[[i, j]];         While[Length[currbg] >= 1,          currmat = currbg[[1]];          currsym = symlist[currmat];          binclasses = Append[binclasses, {currmat, Length[currsym]}];          binreps = Append[binreps, currmat];          If[i != 1 + (mdim^2 /2 ),           binreps =              Append[binreps, ConstantArray[1, {mdim, mdim}] - currmat];           ];          currbg = DeleteCases[currbg, x_ /; MemberQ[currsym, x] == True];          ]         , {j, 1, Length[bgrlist[[i]]]}];       , {i, 1, Ceiling[Length[bgrlist]/2]}];      Length[binreps]      ]      **EDIT** Here is my code for the above algorithm. Note, that I have defined the symmetries of the square as functions, even though some of them (eg. reflection in diagonal) are simply transposing the matrix. I did this for clarity (for readers on here), rather than efficiency!               (*Symmetry functions.*)     vsym[matrix_] := Reverse[matrix, {2}];     hsym[matrix_] := Reverse[matrix];     d1sym[matrix_] := Transpose[matrix];     r1sym[matrix_] := vsym[d1sym[matrix]];     d2sym[matrix_] := r1sym[vsym[matrix]];          (*List of all distinct symmetries of given matrix *)     symlist[matrix_] :=        DeleteDuplicates[{matrix, vsym[matrix], hsym[matrix], d1sym[matrix],          d2sym[matrix], r1sym[matrix], r1sym[r1sym[matrix]],          r1sym[r1sym[r1sym[matrix]]]}];          (* All square binary matrices of size mdim *)      binlist[mdim_] := binlist = Tuples[{0, 1}, {mdim, mdim}];          (* Initialise list of equivalence classes *)     binclasses = {};          binlist[2];          While[ Length[binlist] >= 1,      (currmat = binlist[[1]];        currsym = symlist[currmat];        binclasses = Append[binclasses, {currmat, Length[currsym]}];        binlist = DeleteCases[binlist, x_ /; MemberQ[currsym, x] == True]);      ]


title: How to plot logarithmic scales

text: How can a simple logarithmic number line be drawn between any 2 integer values? ![logarithmic number line of integer values](http://i.stack.imgur.com/gvIsj.png) The closest function I found in the documentation is `LogLinearPlot[]` and I've been racking my brains trying to figure out how to do this with no luck...


title: How to add the position of an added vertical line to the plot itself?

text: In this question it is answered how to add a vertical line to a graph. However, it has not been shown that how can someone add the position of that vertical line to the axis. How can I add the coordinate of a vertical line to the graph itself? I want to be able to change the font size of the coordinate too. By using the code below I can change the font size of the coordinate of axes. I want similar thing for the solution to this question too.               FrameStyle -> Directive[Black, Bold, 80]      Here is an example:               line3 = Line[{{2.33, -2}, {2.33, 2}}];     Plot[Sin[x], {x, 0, 2*Pi}, PlotStyle -> {Thick, Red}, Frame -> True, FrameStyle ->Directive[Thick, Bold, 20], Epilog -> {Directive[Thick, Blue], line3}]      Result: ![enter image description here](http://i.stack.imgur.com/0Giig.jpg)


title: Determining all possible traversals of a tree

text: I have a list:               B={423, {{53, {39, 65, 423}}, {66, {67, 81, 423}}, {424, {25, 40, 423}}}};      This list can be visualized as a tree using `TreeForm[B]`: ![TreeForm\[B\]](http://i.stack.imgur.com/ORXFl.jpg) and I would like to find all possible traversals of this tree:               {{423,53,39},{423,53,65},{423,53,423},{423,66,67},{423,66,81},      {423,66,423},{423,424,25},{423,424,40},{423,424,423}}      It seems that `Subset` might be usable, but when I tried `Subset[B,{3}]`, it gave me the null set. Another possible problem with `Subset` is that it perhaps does not respect the leveling of the tree. I looked at the `Combinatorica` package, but I don't see a way to traverse the tree -- in the direction from top to bottom -- in all possible ways.


title: Is there a way to increase the smoothness of a cylinder?

text: I am using `Cylinder` to produce wide flat disks (in _Mathematica_ 8). This works just fine except that the circular base of such a cylinder turns out to be really just a 40-gon which is simply too coarse an approximation to a circle for what I have in mind. Is there a way to convince _Mathematica_ to use say a 200-gon as a circular base for a cylinder? Here is an example of the kind of picture that I am trying to create. Zoom in to see how coarse the cylinders' curved surfaces pan out.               Graphics3D[{Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, -0.9510565162951536`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, 0.9510565162951536`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.85065080835204`, 0.`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.85065080835204`, 0.`, 0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, -0.5`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, 0.5`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, -0.5`, 0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, 0.5`, 0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`, -0.8090169943749475`, \     -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`,            0.8090169943749475`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`, -0.8090169943749475`,            0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`, 0.8090169943749475`,            0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, 0.`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, 1.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.42532540417602`, 0.3090169943749474`,            0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.7236067977499789`, 0.5257311121191336`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.16245984811645317`, 0.5`, 0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`, 0.8090169943749473`,            0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.27639320225002106`, 0.8506508083520399`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.42532540417602`, -0.3090169943749474`,            0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.7236067977499789`, -0.5257311121191336`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.85065080835204`, 0.`, 0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.16245984811645317`, -0.5`, 0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.27639320225002106`, -0.8506508083520399`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`, -0.8090169943749473`,            0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.5257311121191336`, 0.`, 0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.8944271909999159`, 0.`, 0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, -0.5`, 0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, 0.5`, 0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.7236067977499789`, -0.5257311121191336`, \     -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.42532540417602`, -0.3090169943749474`, \     -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, -1.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`, -0.8090169943749473`, \     -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.16245984811645317`, -0.5`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.27639320225002106`, -0.8506508083520399`, \     -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.7236067977499789`,            0.5257311121191336`, -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.42532540417602`,            0.3090169943749474`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.85065080835204`, 0.`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.27639320225002106`,            0.8506508083520399`, -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.16245984811645317`, 0.5`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`,            0.8090169943749473`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.8944271909999159`, 0.`, -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.5257311121191336`, 0.`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, 0.5`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, -0.5`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 1.`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.5877852522924731`, 0.8090169943749473`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.9510565162951535`, 0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.9510565162951535`, -0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.5877852522924731`, -0.8090169943749473`, 0.`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, -1.`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.5877852522924731`, -0.8090169943749473`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.9510565162951535`, -0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.9510565162951535`, 0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.5877852522924731`, 0.8090169943749473`, 0.`}}, .1]}]


title: nested numerical integration: not valid limits?

text: I encountered an error when I was hoping for some Mathematica (8.0.4) magic sparing me to code up numerical integration, function approximation and root- finding myself. The broader context and the reference functions here come from a previous question:               k=10/3;     H = ParetoDistribution[1.18709*10^6, 0.938482];     Hstar = H;     u[c_,l_]=Log[c]-Log[1+l^(1+k)/(1+k)];     T[z_]=(1-0.84/1.3) * z;     lType[n_]=ArgMax[{u[n l-T[n l],l],l>=0},l];     zType[n_] = n lType[n];      where `u` is the utility function as in Saez 2001 allowing for income effects, `T` the actual tax schedule (approximate). Note that `lType` and `zType` only makes sense numerically. The original problem with               Type=InverseFunction[zType]      was solved with not `SetDelayed` but `Set` everywhere. But the following nested (numerical) integration does not work (for any H distribution you give it). Have I defined it wrong?               g[z_]:=NSolve[T'[z]/(1-T'[z])-(k SurvivalFunction[H,z]/(z PDF[Hstar,z]))              Integrate[(1-g)Exp[Integrate[1-\[Xi]u[zzz]/\[Xi]c[zzz],{zzz,z,zz}]]             PDF[H,zz]/SurvivalFunction[H,z],{zz,z,\[Infinity]}],g,Reals];     N[g[2000000], 10]      Error: > NIntegrate::nlim: zzz = zz is not a valid limit of integration. **EDIT** : More interestingly, when I simply specify numeric arguments for the inner integral, the computation starts, though does not finish in an hour:                 tmp[z_?NumericQ, zz_?NumericQ] := NIntegrate[1 - \[Xi]u[zzz]/\[Xi]c[zzz], {zzz, z, zz}]       g[z_] := NSolve[T'[z]/(1 - T'[z]) - (k SurvivalFunction[H,z]/(z PDF[Hstar, z]))          NIntegrate[(1 - g) Exp[tmp[z, zz]] PDF[H, zz]/SurvivalFunction[H, z], {zz,z,          \[Infinity]}], g, Reals]      But the same gives me an error if I compile first. Why? Because the limit at infinity? How should I proceed?                   tmp = Compile[{{z, _Real}, {zz, _Real}},NIntegrate[1 - \[Xi]u[zzz]/\[Xi]c[zzz],          {zzz, z, zz}],Parallelization -> True, CompilationTarget -> "C"]      Then I run g[2000000] and get the error: > CompiledFunction::cfsa: "Argument zz at position 2 should be a !(\"machine- > size real number\")."


title: Plotting Piecewise function, ExclusionsStyle not shown completely

text: Suppose I define               f[x] := Piecewise[{{1.7*10^-6, 150 <= x <= 200}}, 0]      and then plot               Plot[Evaluate[f[x]], {x, 0, 1000}, PlotStyle -> {Red, Thick},          ExclusionsStyle -> {Dashed, Red}]      I get an interrupted dashed vertical line on left ![Plot of Piecewise function with Exclusion dashed line missing](http://i.stack.imgur.com/B7SlY.png) Anyone know why this happens and how to draw the entire dashed line?


title: More efficient Omnibus number determination?

text: Amusing myself with concepts from "Omnibus Sequences, Coupon Collection, and Missing Word Counts", in particular the sequences. To paraphrase the concept, a string is _k-Omni_ over some alphabet _a_ if any string of length _k_ (or less) from the alphabet can be found as a sequence of the string. e.g.,               string={5, 4, 0, 5, 3, 3, 1, 4, 0, 2, 4, 0, 2, 3, 5, 0, 0, 0, 5, 4, 2, 3, 3, 5, 5, 4, 1, 5, 5, 4, 4, 5, 3, 2, 1, 3, 1, 2, 2, 4}      is 2-Omni over the alphabet of the string, and 4-Omni over a restricted alphabet of `{1,2,3}`. I'm using               kOmni = Block[{f = Total@BitSet[0, DeleteDuplicates@#1], z, cnt = 0},        Fold[If[(z = BitAnd[f, BitSet[#, #2]]) == f, cnt++; 0, z] &, 0, #2];cnt] &      which takes the alphabet and string as arguments, to determine the _k_ for various conditions, e.g. `kOmni[{1, 2, 3}, string]` returns the desired 4 result. Might there be a more efficient way to do this? You can assume strings (and alphabets) are limited to non-negative integers, and alphabets are almost always under 200 distinct values, but the strings can be quite large (>10^5 elements). Update: An optimization I came up with nodding off...               kOmniO = Block[{f, z, cnt = 0, s = #2, a = DeleteDuplicates@#1},        s = Join[a, s];        s = s[[Sort@(Join @@               GatherBy[Range@Length@s, s[[#]] &][[;; Length@a, 2 ;;]])]];        f = Total@BitSet[0, a];        Fold[If[(z = BitSet[#, #2]) == f, cnt++; 0, z] &, 0, s];        cnt] &      About 50% faster for full alphabet, and with alphabet that is a subset of string alphabet, can be over an order of magnitude faster. I still have a gut feeling there's a faster/smarter way to do this... c'mon wizards ;-)


title: How to plot imaginary part of a function

text: I need to plot the cube root of x in mathematica, but the plot shows me only the real part. I want it to look like wolframalpha plot with both real and imaginary parts of the function. Is it possible to do it? EDIT: This is what I want the plot to look like


title: Find the solution of A^2+AB+B^2 = f(a,b,c)

text: I wanted to ask the following question: I need to find the solutions (a particular one is enough!) A and B of the equation > $A^2 + AB + B^2 = (a^2+ab+b^2)(c^2+cd+c^2)$ How can I do it? Thank you very much!


title: Leveling peaks in list

text: Consider the following:               data={2,2,2,5,3,3,3,6,1,1,1,0};     In[1]:=result=MyFunction@data     Out[1]:={2,2,3.5,3.5,3,3,4.5,4.5,1,1,1,0}      `data[[{4,8}]]` represent the peaks which I want to level via `MyFunction` as follows:               {a___,PrePeakValue1_,peak1_,b___,PrePeakValue2_,peak2_,c___}:>{a,Mean1,Mean1,b,Mean2,Mean2,c}      whereas `Mean1=Mean@{PrePeakValue1,peak1}` (i.e. `Mean@{2,5}`) and `Mean2=Mean@{PrePeakValue2,peak2}` (i.e. `Mean@{3,6}`). I posted this question  already some time ago, but Heike's approach has one disadvantage: neither it identifies and therefor nor levels the second peak. I think using `LengthWhile` migth be one reason why it won't work. EDIT: `data` is just an example. I have other lists which may contain no, one or more than two peaks.


title: How to detect crosses and circles in 60x60 raster images?

text: I have hand-written 60 pixel times 60 pixel squares. I need to detect whether they are empty, x or circle. TextRecognize function fails. Is there some other function to process this kind of raster images with text? ![enter image description here](http://i.stack.imgur.com/NWXCe.png) **Harder example** > **Circles:** (0,0..9), (0..5,0), (0..5,9), (5,0..9) > > **Crosses:** (2,3..6), (4,4..5) > > **Empty:** (1,1..8), (2,1..2), (3,1..8), (4,1..3), (4,6..8) * * * I try to summarize and help people to solve the harder puzzle. Work in progress. Have fun! > I. **Preprocessing** (example) > >> 1.1. thread about getting grid from raster image >> >> 1.2. convexity fix >> >> 1.3. rotation > > II. **Testing** > >> 2.1. Further info about mathematical morphology and Mathematica's intro.


title: How do I evaluate a double or triple integral over a region?

text: Say I need to evaluate the integral $\iiint_W f(x,y,z) dx dy dz$ and $W$ is a region given to me like $W = \\{ (x,y,z) : 1 \leq x^2 + y^2 \leq 4, 1 \leq z \leq 5\\}$. I don't how to do this with a triple integral in _Mathematica_ code.


title: How to create a numerically "equal" function?

text: A simple example about what I need to do. For example, I have three functions:               t1[x,t]     t2[x,t]     t3[x,t]      and,               t3[x_,t_]:=t1[x,t]+t2[x,t]       What is the best way to create a function t4[x,t] that is numerically "equal" to t3[x,t] but is not function of t1[x,t] and t2[x,t] in order to avoid a circular reference in a While loop program? Regards!


title: Checking if a point is in a convex 3D polyhedron

text: Extending from these questions How to check if a 3D point is in a planar polygon? and How to check if a 2D point is in a polygon?. I'm trying to do this to render specific shapes made up of spheres. For a sphere it is easy:               (* generate a grid of points*)     d = 20;     points = Table[{x, y, z}, {x, -d, d}, {y, -d, d}, {z, -d, d}]~Flatten~2;          (*check if they are inside a spherical shell*)     points2 = Select[points, 8.5 < Norm[#] < 10 &];          (*render the spheres that are inside the spherical shell*)     Graphics3D[{Sphere[#, 0.75]} & /@ points2, Boxed -> False]      ![Mathematica graphics](http://i.stack.imgur.com/vsbtV.png) However, I want to try and do the same rendering for other shapes, for example a pentagonal dipyramid               Graphics3D[{Lighter@Lighter@Blue, Opacity[.8], EdgeForm[Thickness[ 0.005]], PolyhedronData["PentagonalDipyramid", "Faces"]}, Boxed -> False]      ![Mathematica graphics](http://i.stack.imgur.com/K69AH.png) However, I'm not sure how to check if the points on the grid are with in the polyhedron. I can access the faces... `PolyhedronData["PentagonalDipyramid", "Faces"]`


title: System of ODEs specified by large coefficient matrices

text: What is the best way to call `NDSolve` for solving a system of differential equations of the form               Am.y'[x] + Bm.y[x]/x + Cm.y[x] == Dv       with `y[0] == Ev` in the interval x from 0 to 1. where y is an n-vector, Am, Bm, and Cm are n x n coefficient matrices, and Dv and Ev are n vectors. Say with               n=100;     Am = RandomReal[1,{n,n}];     Bm = RandomReal[1,{n,n}];     Cm = RandomReal[1,{n,n}];     Dv = RandomReal[1,{n}];     Ev = RandomReal[1,{n}];


title: Retrieving Data from Excel Using NETLink / Pulling data using RTD Link

text: Reference: I've looked at the posting Open excel file with _Mathematica_. My intention is to be able to use Excel's RTD capability in order to pull market data into _Mathematica_. To my knowledge, this can be done, at the least, by having Excel use the RTD link, then using NETLINK to grab the value from Excel. At some point, it would be nice to have _Mathematica_ pulling real time data from an Excel RTD link, but for now the RTD link value is only updated once per day.               Needs["NETLink`"]     PullValue[file_String] :=       Module[{excel, workbook, worksheet, RTDvalue},        NetBlock[InstallNET[];         excel = CreateCOMObject["Excel.Application"];         If[! NETObjectQ[excel], Return[$Failed], excel[Visible] = True;          workbook = excel@Workbooks@Add[];          worksheet = workbook@Worksheets@Item[1];          worksheet@Range["A1"]@Value =            "=ProphetX|QUOTE!'@CT@A?SettlementPrice'";          RTDvalue = worksheet@Range["A1"]@Value;          workbook@SaveAs[file];          workbook@Close[False];          excel@Quit[];]];        LoadNETType["System.GC"];       GC`Collect[]         RTDvalue];          outputfile = "C:\\Temp\\demo.xlsx";     Quiet[DeleteFile[outputfile]];     PullValue[outputfile];      The `=ProphetX|QUOTE!'@CT@A?SettlementPrice'` is the RTD portion, which at this point is putting a value into the saved Excel file, which should be correct. Sometimes when dealing with RTD links, I've noticed that I need to use `FormulaArray`, but `@value` seems to be working fine here. `Print[RTDvalue]` is outputting -2146826246, instead of the correct value of ~ 81.26 So, I am wondering how I can get those values RTD values, which have gone into an Excel cell, into _Mathematica_ , like they did in the posted link. Also, any direction or thought on how I could eventually have the data coming into *Mathematica*in real time.


title: Use a custom3D graphic for points in ListPointPlot3D

text: I would like to make a plot where the points of ListPointPlot3D are themselves a Graphics3D object created using SphericalPlot3D, and each one depends on the position of the point. So basically, you have a list of points, {x, y, z}, and at each point there is a graphic which is determined by a function f(xi, yi, zi). I have been searching for about a day now to try and find a solution to this with no luck. Any help is greatly appreciated. Also, I don't have to use ListPointPlot3D, and if there is a better method I would certainly welcome it.


title: To what extent can NonlinearModelFit be sped up?

text: Can `NonlinearModelFit` be parallelized or compiled to allow one to achieve a scalable speedup for a fitting procedure? Attempting to use this function to fit a bivariate Gaussian (with a decent guess for initial conditions) can take upwards of a second.


title: Plots using TextAlignment with SwatchLegend to left align multi-line items

text: I have Legends that stretch over multi-lines and the only way I can get them left aligned is by adding white space to the end of the legend item. Does anyone know if there is a way to use TextAlignment with SwatchLegend?               gJ = Plot[Sin[x], {x, 1, 12},        PlotLegends -> {Placed[          SwatchLegend[{RGBColor[1, 0.5, 0], RGBColor[0., 0.329412, 0.],             RGBColor[0.619608, 0.25098, 1.],             RGBColor[0, 1, 1]}, {"it ends up centred", "but ",             "fox jumped over two lines that I want to \nalign to the left",             "A quick brown"},            LegendMarkers -> {Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}]},            LegendLayout -> "ReversedColumn", LegendMarkerSize -> 16,            LabelStyle -> {FontFamily -> "Arial", 18},            Spacings -> {0.5, 0.25}], {0.4167, 0.7701}]}]      ![enter image description here](http://i.stack.imgur.com/MFBdF.png)


title: AstronomicalData and Planetary Heliocentric (x,y,z) Velocity Components

text: I'm trying to find data on the heliocentric velocities of planets in our solar system and was directed to _Mathematica_ 's `AstronomicalData` in a previous topic. Unfortunately I cannot find any x,y and z velocity components and was hoping someone might be able to point me in the right direction.


title: Forecasting future Stock Prices II

text: I intend to do the following: I want to forecast future stock price under the following assumptions: The stock price is governed by the stochastic differential equation: dS = μSdt + σSdWt whereas dW_t~N(0,√dt) In the first step I want to define the Brownian Motion for one path and for multiple paths, which is done by: **1Path:**               BrownianMotion[period_, steps_Integer: 1000, init_: 0] := Accumulate[        Prepend[RandomVariate[NormalDistribution[0, Sqrt[period/steps]],        steps], init]]          ListLinePlot[BrownianMotion[1,1000], AxesLabel->{"Time",B_t},        PlotLabel -> Style["Stochastic Brownian Motion",Bold]]       **Multiple Paths:**               BrownianMotionPaths[period_, steps_Integer: 1000, paths_Integer, init_List]      /; (Length[init] == paths) := Transpose[       Accumulate[        Prepend[RandomVariate[NormalDistribution[0, Sqrt[period/ steps ]],      {steps, paths}], init]]]          ListLinePlot[BrownianMotionPaths[1, 1000, 50,         ConstantArray[0.5, 50]],         AxesLabel->{"Time",B_t},         PlotLabel -> Style["Stochastic Brownian Motion",Bold]]      So I get the following, which works perfectly for one path:               μ2 = 0.01; σ2 = 0.3; S2 = 100;          ListLinePlot[S2*(1+μ2ConstantArray[1,251] + BrownianMotion[1, 250]*σ2),       AxesLabel→{"Time","St"},        PlotLabel -> Style["Price by proxy data"],        PlotRange -> All]      NOW I want to manipulate S2,μ2, and σ2. In order to do so, I entered the following code:               Manipulate[       ListLinePlot[S1*(1 + μ1 ConstantArray[1, 251] + BrownianMotion[1, 250] * σ2),        AxesLabel -> {"Time", "St"},        PlotLabel -> Style["Price by proxy data"],        PlotRange -> All],        {S1, 100, 500, Appearance -> "Labeled"},        {μ1, 0, 1, Appearance -> "Labeled"},        {σ1, 0, 1, Appearance -> "Labeled"}]      It works, but the results must be wrong, because when I choose Sigma to be small and increase Mu drastically, I should get something which looks like an exponentially increasing function, because the function is driven heavily by the drift. However, according to my code this is not the case. So something must be wrong. Does anybody have a solution when I want to manipulate the start value (S1), Sigma, and Mu, for one and for multiple paths?


title: How to calculate the volume of a convex hull?

text: Given a spatial curve represented by a parametric equation, is it possible in _Mathematica_ 9 to calculate symbolically (or at least numerically) the volume of its convex hull?


title: How to fix a PDF line rendering problem in V9

text: If I run this in V8               Export["test.pdf", Grid[       Table[x, {10}, {7}],       Alignment -> {{Left, {Right}}, Center},       Background -> {None, White},       BaseStyle -> Directive[FontFamily -> "Times", 12],       Dividers -> {{1 -> White, -1 -> White}, {3 -> True,           6 -> True, -1 -> True}},       Frame -> False,       FrameStyle -> Directive[AbsoluteThickness[0.5], Black],       ItemSize -> {{35, {9}}, 1.5},       ItemStyle -> {Automatic, {Bold}},       Spacings -> {{1, 1, {0.5}, 2}, {0.5}}]]      I get divider lines of the correct thickness. If I run it in V9 the divider line thickness is screwed up. With not only the lines being different to the specification but the line thicknesses vary from each other despite all being specified to have the same thickness. Coincidentally I have noticed this the same day as this question was posted. It appears something became broken in V9. I am wondering if anyone has any suggestions for fixes? I am using Mac 10.9.2 and V9.0.1 and V8.0.4


title: How do I find the all valid pairings between two sets?

text: I have a pretty hard problem to solve here, and I have no idea how to start. I have X kind of fruits and 5 colors (let's say Red, Green, Yellow, Blue and Purple). Each fruit can be available in several colors (but in at least 1). How can I find each combination, when I need exactly 1 fruit of each color but no fruit twice (so there will always be bought exaclty 5 fruits in exactly 5 different colors)? For example:   1. Pears are available in [Red, Green, Yellow]   2. Apples are available in [Red, Green]   3. Plums are available in [Purple]   4. Grapes are available in [Red, Green, Purple]   5. Bananas are available in [Blue, Yellow] Since bananas are the only fruit available in blue, it's already sure, that bananas will be bought in blue, and not in yellow. These would be the solution for this list:   1. Yellow Pear, Red Apple, Purple Plum, Green Grapes, Blue Banana   2. Yellow Pear, Green Apple, Purple Plum, Red Grapes, Blue Banana No other combination is possible here. Is there any algorithm to do this with a dynamic list, which may also have more than 5 fruits? I know, it's a pretty hard problem, but maybe someone has a simple solution for it.


title: intersection between function and plane

text: I try to solve a ODE system of equations and i want to plot the intersection of the 3D solutions with a costant plane. To do this i use the follow code:               Clear["Global`*"]     tfin = 500;     T = p1^2/2 + p2^2/2;     V = x^2/2 + y^2/2 + x^2 y - y^3/3;     H = T + V;     eq1 = x'[t] == D[H, p1] /. p1 -> p1[t];     eq2 = y'[t] == D[H, p2] /. p2 -> p2[t];     eq3 = p1'[t] == -D[H, x] /. {x -> x[t], y -> y[t]};     eq4 = p2'[t] == -D[H, y] /. {x -> x[t], y -> y[t]};     energy = (H /. {x -> -.1, y -> -.2, p2 -> -.05}) == 0.06;     sol = Solve[energy, p1];     p10 = p1 /. sol[[2]];     sol2 = NDSolve[{eq1, eq2, eq3, eq4,         x[0] == -.1,         y[0] == -.2,         p1[0] == p10,         p2[0] == -.05},        {x[t], y[t], p1[t], p2[t]}, {t, 0, tfin}, MaxSteps -> 5000];     a = ParametricPlot[Evaluate[{x[t], y[t]} /. sol2], {t, 0, 20}];     b = ParametricPlot[Evaluate[{x[t], p1[t]} /. sol2], {t, 0, 20}];     c = ParametricPlot[Evaluate[{y[t], p2[t]} /. sol2], {t, 0, 20}];               gr1 = ParametricPlot3D[Evaluate[{x[t], y[t], p2[t]} /. sol2],        {t, 0, tfin},         PlotPoints -> 4000, BoxRatios -> {1, 1, 1}, ViewPoint -> {1, 0, -2},        DisplayFunction -> Identity];      This is the 'plane' of intersection. Maybe I must use something like `PLot3D[0.,{y,ymin,ymax},{z,zmin,zmax}]` because i want a plane that intersect the orbit in the plane x=0.               gr2 = Graphics3D[{Green, Opacity[0.9],          Polygon[{{0, -.31, -.31}, {0, -.35, .35}, {0, .35, .35}, {0, .35, \     -.31}}]}, DisplayFunction -> Identity];      This is the 'intersection' i only plot the solutions with a very thin x-axis but this is not a plot of the points of intersection between the solutions and the plane (pl1):               ParametricPlot3D[Evaluate[{x[t], y[t], p2[t]} /. sol2], {t, 0, tfin},      PlotPoints -> 4000, PlotStyle -> Directive[Red, Thick],       PlotRange -> {{0, 0.002}, {-.4, .4}, {-.4, .4}},      ViewPoint -> {1, 0, 0}, AxesLabel -> {"", "y", "p2"},       ImageSize -> {500, 500}]          Show[gr1, gr2, DisplayFunction -> $DisplayFunction,       ImageSize -> {500, 500}]      Can someone help me please?


title: PDF of binomial distribution and mixed binomial distribution

text: I want to plot the PDF of binomial distributed function and a mixed binomial distributed function, therefore I entered for the binomial distribution function the following:               Remove["Global`*"];     m = 45; (*number of banks*)     n = 5;(*number of defaults*)     AssetV = 100;(*asset value at T*)     DebtV = 80;(*debt value at T*)     μ = 0.2;(*annual drift*)     σ = 0.3;(*annual volatility*)     T = 5;(*years*)     ρ = 0.8; (*asset correlation*)          (*calculation of the individual default probabiltiy p^*, which is \     determined based on the Merton model*)                P* = (CDF[            NormalDistribution[], -(Log[                 AssetV/DebtV] + (μ - 0.5*σ^2)*T)/(σ*Sqrt[               T])])     (*generating data table, which captures the probabilities that the \     number of defaults will be greater than n1, whereas n1 encompasses \     the range from 0 to m by the step of 1 (integer)*)          dataBD = Table[       Probability[x >= n1,         x \[Distributed] BinomialDistribution[m,  P*]], {n1, 0, m,         1}]      now I want to plot everything:               pdfBD = DiscretePlot[       PDF[BinomialDistribution[m, P*], n1], {n1, 0, m},        PlotRange -> All, AxesLabel -> {"# of Defaults", "PD"},        Joined -> True, ImageSize -> 500]      so I get this plot ![enter image description here](http://i.stack.imgur.com/dxe9p.jpg) now I want to consider the mixed binomial distribution, determiend by the following code:               dataMBD =       Table[1 -         CDF[NormalDistribution[], ((1/             Sqrt[ρ])*(((Sqrt[                1 - ρ])*(InverseCDF[                 NormalDistribution[], (n1/m)]) + (InverseCDF[                NormalDistribution[], (CDF[                  NormalDistribution[], -(Log[                       AssetV/DebtV] + (μ - 0.5*σ^2)*                       T)/(σ*Sqrt[T])])]))))], {n1, 0, m, 1}]      However, if I want to see its PDF and if I therefore enter this command it does not work:               DiscretePlot[PDF[dataMBD, n1], {n1, 0, m, 1}]      Is the error within the command above, or is there a fundamental problem based on wrong understanding? hope somebody can help me. thanks.


title: ListPlot InterpolationOrder->0 datapoint centered

text: it is possible to get a histogram style in `ListPlot` using `InterpolationOrder->0`               testdata = {{1, 3}, {3, 4}, {4, 3}, {5, 8}, {7, 6}, {9, 4}};     ListPlot[testdata, Joined -> True, InterpolationOrder -> 0,      Epilog -> {PointSize[Large], Point[testdata]}]      ![enter image description here](http://i.stack.imgur.com/kfem4.jpg) Note that the data points are sitting at the corner of the histograms at the left end of the horizontal lines. My question is: How could I plot the same data set with the data points being centered on the horizontal line segments? For equidistant data points this is of course a simple shift. But how to do this for irregularly gridded data? Edit 1: To clarify: Of course this is possibly not very meaningfull in irregularly spaced cases, and centered is the wrong term, however, in the example case the data point connection I was looking for could look like the following: ![enter image description here](http://i.stack.imgur.com/8UtCJ.jpg)


title: How to evaluate sums that have 0^0 = 1

text: In my code:               summand[k_, x_] := (0.25*x*mu)^k/(k!*Pochhammer[(m + 1)/2, k])*                        Hypergeometric1F1[(m + 1)/2, (m + 1)/2 + k, eta];          cumdistfunc[x_] := 1 - 0.5^(m (m + 1)) Exp[-eta] Exp[Tr[kappa x]] Sum[summand[k, x], {k, 0, 20}]      I have that the summand function ought to be able to be evaluated at `0` so that the value of my cumulative distribution function at `0` is actually `0`. Do you know how I could do that? Thank you so much!


title: NMaxmize with a list of variables

text: I want to use NMaximize to find the maximum value of a function with multiple variables. The problem is I would like to set this up so the number of variables is only decided when the function sees the data. So I have:               NMaximize[{F[data,a1,a2],a1>0,a2>0},{a1,a2}]      when there are data from two genes. But would like the function to be               NMaximize[{F[data,a1,a2,a3],a1>0,a2>0,a3>0},{a1,a2,a3}]      if there are 3 genes...etc Any way to set this?


title: Is there a fast way to trilaterate a point?

text: I have a point in 2D or 3D space at an unknown coordinate, $p_0$, and I'd like to determine its position using distances from known coordinates $(p_1, p_2, p_3)$. Beyond using `Reduce`, what is a fast method of doing this in _Mathematica_ , particularly for the two-dimensional case? Is there some built-in function for this? Also, how can I get an output in coordinate form without any string processing? For example, to parse the output from `Reduce`, I need to convert the output to a string, infer where the actual coordinate values are, and extract them, which is an awful way to go about doing things. Here's an implementation with `Solve`:               PostOne = {10, 10};     PostTwo = {10, 0};     PostThree = {0, 0};          PointToLocalize = {x0, y0};          D1 = 0;     D2 = 10;     D3 = 200^(1/2);          Solve[EuclideanDistance[PointToLocalize, PostOne] == D1 &&            EuclideanDistance[PointToLocalize, PostTwo] == D2 &&            EuclideanDistance[PointToLocalize, PostThree] == D3, {x0, y0}]      Now that the string processing issues have been resolved, is `Solve` or `Reduce` really the most efficient way to do this for $10^6$ or $10^7$ or so points?


title: Kramers-Kronig Mathematica code

text: I'm trying to write Mathematica code to use Kramers-Kronig on a csv file with 2 columns. Column 1 is h(eV). It goes from 0 to 6, in increments of 0.1. Column 2 is alpha (cm^-1). For some reason, my code just outputs a blank graph. Can someone please tell me what's wrong with it? This is the equation I'm trying to implement (thanks J.M. for doing the latex) $$n_r(\hbar\omega)-1=\frac{c\cdot h}{2\pi^2}P\int_0^\infty \frac{\alpha(\hbar\omega^\prime)}{(\hbar\omega^\prime)^2-(\hbar\omega)^2}d(\hbar\omega^\prime)$$ The reason I posted on this forum is that my code is based on the code from another topic on this site (Update: wrong link, see comments below)               c = 300000000;     data = Import["kk.csv", "CSV"];     column1 = data[[All, 1]];     column2 = data[[All, 2]];     Delete[column1, 1];     Delete[column2, 1];          output :=        1 + (c PlanckConstant)/(2 pi^2)          NIntegrate[column2/(column1^2 - omega^2), {omega, (column1)^2, 0, infinity},            Method -> "PrincipalValue", Exclusions -> Automatic]          Plot[output, {column1, 0, 6}, AxesOrigin -> {0, 0}]


title: How do I display a histogram with normalized counts?

text: I have some data corresponding to real number distances: `{200.04053, 200.232123, 156.3242,...}`, and I would like to bin these values and display them as a histogram where the heights of each bar in the histogram are normalized so that the sum of all the bin heights is equal to one. The objective here is for me to be able to use `FindDistributionParameters` to determine, well, appropriate distribution parameters, and then to overlay the PDF of this suggested distribution on my actual data. Is there an easy way to do this?


title: Why is CityData[All, "Coordinates"] failing?

text: When I evaluate               CityData[All, "Coordinates"]      _Mathematica_ returns > >     {Missing["NotAvailable"], Missing["NotAvailable"]} >   but when I evaluate `CityData[All]` or `CityData[{All, "USA"}]`, it behaves as expected, and returns a gigantic list of cities. I'm curious to modify the neat example for `FindShortestTour`, to use coordinates from `CityData` \-- _yes it may take a very long time, but I'm curious to see for myself_ :) My guess is that it is because not every city in the database has coordinates mapped thereto - but why is _Mathematica_ failing this way? **How can I programmatically eliminate the cities with 'bad' coordinates? Or programmatically build a list of all cities that do have coordinates?**


title: Symbolic evaluation fails because it exceeds $RecursionLimit

text: I am trying to perform a simple arithmetic in complex algebra.                      a := Subscript[a, 1] + I*Subscript[a, 2];            b := Subscript[b, 1] + I*Subscript[b, 2];            r[z_] := a/(b - z) + a\[Conjugate]/(b\[Conjugate] - z);      when I try to evaluate r[0], mathematica gives me the following message                      $RecursionLimit::reclim: Recursion depth of 256 exceeded.      I was expecting something like the following                      2*Re[a/b] = 2 (a_1 * b_1 + a_2 * b_2)/(b_1 ^2 + b_2 ^2)      Could someone please point out where I did mess up?


title: Is there a better way to add a "key" for the list of GatherBy?

text: In ruby ,               1.upto(10).to_a.group_by{|x| x%3}      gives               {1=>[1, 4, 7, 10], 2=>[2, 5, 8], 0=>[3, 6, 9]}      I would like use patten replace as a hash table in _Mathematica_. For example:               {1 -> {1, 4, 7, 10}, 2 -> {2, 5, 8}, 0 -> {3, 6, 9}}      I know I can use `GatherBy`, but it only contains the value. I tried to solve and I feel it isn't efficient for a large list.               fun = Mod[#, 3] &;     Thread[fun /@ #[[All, 1]] -> #] &@GatherBy[Range[10], fun]


title: Find the derivatives of arbitrary order of a function found using NDSolve

text: For the following initial value problem               BC[b_]:=x[0]==b;     eq[b_]:=NDSolve[{equation==0, BC[b]}, x, {t,0,1000}];     body[t_,b_]:= x[t]/.eq[b];      one could define the derivative of `body` with regard to `t` as               Dbody[t_,b_]:=x'[t]/.eq[b];      However I'm trying to find a way to define this for derivatives of arbitrary order with regard to `t`, and make the definition of `Dbody` redundant. Simple invocations of `'`, `D` and `Derivative` failed; for example:               Derivative[1][body][1,1]      returns               body'[1,1]


title: How to convert a transfer function model to a zero-pole-gain model?

text: Mathematica has a function to convert TransferFunctionModels to StateSpaceModels:               mytf=TransferFunctionModel[(2 s + 3)/(s^3 + 4 s^2 + 5), s]     StateSpaceModel[mytf]      Is there a corresponding function that will convert to a zero-pole-gain model?


title: Local variables

text: I'm trying to use `Modules` together with functions.               tmp2 = x^2 + 1; f[y_] := Module[{x = 1}, Evaluate[y tmp2]]      This works when I just have               tmp2 = x^2 + 1; Module[{x = 1}, Evaluate[tmp2]]      But `f[1]` outputs $1 + x^2$. **Edit:** After seeing the answers I wonder how I can get something like this to work:               ClearAll[withRules]     SetAttributes[withRules, HoldAll]     withRules[rules_, expr_] :=       Internal`InheritedBlock[{Rule, RuleDelayed},        SetAttributes[{Rule, RuleDelayed}, HoldFirst];       Unevaluated[expr] /. rules]     ClearAll[f, tmp2]     tmp2[y_] = y (x^2 + 1)     withRules[{expr -> tmp2}, f[y_] := Module[{x = 1}, expr[y]]]      **Edit 2:** Maybe it is better if I explain what I'd like to do. I have a lot of calculations in terms of $k_x$, $k_y$ and $k_z$. So, those are outputted in terms of these three variables. However, sometimes I need to integrate such expressions but to do this I need to use spherical coordinates. So I set $k_x = k \sin(a) \cos(b)$ and so on and then integrate. I don't want the transformations always set because I want the other calculations to have $k_x$, $k_y$ and $k_z$ as variables, not $a$ en $b$.


title: Question about number theory

text: Let `S[p]` denote the sum of digits of `p`. A prime `p` is said to be stubborn if none of `S[n] + 1`, `S[n]`, `S[n] - 1`, `S[n] - 2` , or `S[n] - 3` is a prime. Write a mathematica code that finds the smallest stubborn prime and tell which prime is it?


title: How to solve the recursion equation that include the uncertain value i in it?

text: I write the following code of a recursion equation, but it can not work correctly.               RSolve[{        a[0]==(1-p)a[n],        For[i=1,i<=n-1,i++,a[i]==p a[n-i+1]+(1-p)a[n-i]],        a[n]==a[0]+p a[1],        Sum[a[k],{k,0,n}]==1},     a[n],n]


title: How can I defer the loading of a PopupView control until it is used?

text: Background: I have several `PopupView`s of which the loadtime adds to the startup time of a program. To improve the perceived performance I want to defer the loading of the `PopupView` to the moment that they are actually used. I thought about this:                 Clear[filelist];       Clear[obj];       filelist = {};       Dynamic@PopupView[filelist, Dynamic[obj, (obj = #;) &],          Button["Edit", filelist = {1, 2, 3}, ImageSize -> 80]]      The idea works but not as expected, the popupview is not displayed correctly until filelist is loaded. I want to correct this or find an alternative way to set this up. **Question: How can I defer the loading of a`PopupView` control until it is used ?**


title: From a list of dates get a list of the last date available in a each month

text: I wondered if anyone has another or even a more direct way of finding the last dates of each month available from a list of successive dates? I currently do the following (note: nothing special about WeatherData[] here, I just used it to generate a list of dates):               WeatherData["KMDZ", "MeanTemperature", {{2007, 1, 1}, {2007, 12, 31}, "Day"}][[All, 1]];     Last[#] & /@ SplitBy[%, DateList[#][[2]] &]          {{2007, 1, 31}, {2007, 2, 28}, {2007, 3, 31}, {2007, 4, 30}, {2007, 5, 31}, {2007, 6, 30}, {2007, 7, 31}, {2007, 8, 31}, {2007, 9,30}, {2007, 10, 31}, {2007, 11, 30}, {2007, 12, 31}}      This works fine. I just wondered if I could think about this problem in a different way. * * * It seems the question needs a clarification. The starting list of dates may not include every date in a given month as such, it also may not include the actual last date of any given month. I need to find the last date in any month available in the list.


title: Calculating a limit with a result that is discontinuous in the parameters

text: The following limit is left unevaluated ( _Edit:_ added the assumption that $\epsilon$ is real thanks to the comment below):               Limit[ 1/(1 + Exp[ϵ/T]), T->0, Direction->-1, Assumptions->ϵ ∈ Reals]      However, the limit is easy to calculate (it is the Fermi-Dirac distribution), and it gives $\theta(-\epsilon)$. It seems that MMA has a hard time when the result is discontinuous in the parameters.   Nevertheless, MMA can actually calculate the limit, if we help it by explicitly splitting up the parameter space:               In[2]:= Limit[1/(1 + Exp[ϵ/T]), T->0, Direction->-1, Assumptions->#] & /@ {ϵ > 0, ϵ < 0}     Out[2]= {0, 1}      **Is there a way to make MMA automatically calculate such limits, without explicitly splitting up the parameter space?**


title: Measure the length and width of the image

text: I obtained the images from a Magneto Optic Kerr Effect system from which I have to do some calculations. I cannot calculate the desired information from the images. The details are as follows: ![The image I obtain from the system looks like this:](http://i.stack.imgur.com/eYXlo.jpg) From the image I have to calculate the length and width of the black part of the image (which can be assumed to be a rectangle). So, I first use the command for finding the radius and threshold of the image and then convert it into a binary image. The command I use is               Manipulate[EdgeDetect[image, r, t], {{r, 2, "radius"}, 1, 10},          {{t, 0.1, "threshold"}, 0, 0.5}]      And then I get this result after detecting the edges of the black rectangle.![The result after manipulate and edgedetection](http://i.stack.imgur.com/0gU4F.jpg) Now I have to calculate the width and the length at several different positions in the black box and then take the average to get the mean result. As I know that I will definitely get the result in pixels which I can then convert to real world measurements using the scale bar, but I am unable to calculate the length and the width. Since I am new to _Mathematica_ as well as image processing, help will be highly appreciated.


title: RSolve with assumptions

text: I want to solve the following non-linear first order difference equation: $$ k_{t+1} = (1-a) k_t^{a} $$ with $0 < a < 1$, and $k_0 = \text{const.}$ . Of course, the solution is easily found, but I want _Mathematica_ to solve it. Using               RSolve[{ k[t + 1] == (1-a) k[t]^a, k[0] == k0}, k[t], t ]      gives               {{k[t] -> E^(((-1 + a^t) (I π + Log[-1 + a]))/(-1 + a)) k0^a^t}}      The solution is much simpler when considering the restriction on $a$. How can I tell _Mathematica_ that $a$ is between $0$ and $1$ when applying the `RSolve` command? P.S. I've played around with the `Reduce` command, using assumptions, but that did not help.


title: Can I use Table without the appropriate bounds?

text: I´d like to use the `Table` command without defining `n`, so that I can have a list of `n` arguments. It is possible for the `Sum` command, but I guess not for the Table command, or is it? Something like               n = 5; eSO = Table[e[i], {i, 1, n}]; ebar[1] = EBAU - Sum[ebar[i], {i, 2, n}];      a[1] = A - Sum[a[i], {i, 2, n}]; b[1] = B - Sum[b[i], {i, 2, n}];          Cost = Table[1/2/a[i]*(ebar[i] - e[i])^2 + b[i]*(Sum[e[i], {i, n}])^2 /2, {i, 1, n}];          FOC = Table[D[Sum[Cost[[i]], {i, n}] == 0, e[i]], {i, 1, n}];          solsSO = eSO /. Solve[FOC, eSO];          solsSO = Flatten[solsSO];          ESO = Simplify[Sum[solsSO[[i]], {i, n}]]      but a bit more complicated in the end.