title: Issue with Compile

text: The following code works fine with the the function `f` defined as a module, however, when I convert it to be a compiled function, it gives me errors. Can some one help me identify the problem is with the following code:               demand[n_, k_] := Min[k Vf, n capacity];      supply[n_, k_] := Min[(n Kj - k) w, n capacity];      flo[n_, ku_, kd_] := Min[demand[n, ku], supply[n, kd]];     gamma[ku_, kd_] := Min[1, supply[L, kd]/(demand[L, ku] + 0.001)];      inflow [phi_, FQin_] := (phi - β FQin) dx; density[qin_, qout_, qr_] :=        (qin - qout + qr)/Vf;          dx = 1/6; capacity = 7500.; Kj = 150.; w = 100.; Vf = 100.; n = 60; m = 300; p = 24;      RML = 18;α = 4300.; β = 0.1; L = 3.; delta = 1.; dt = 4./3600.;           f = Compile[{{a1, _Real}, {a2, _Real} {a3, _Real}, {a4, _Real}, {a5,_Real}},        Module[{k0 = ConstantArray[0, n],                kr = Table[Table[0, {i1, 1, p}], {i2, 1, n - 2}],                ϕ = 0,                 Shutoff = False},         j = 0;         RMori =            Table[             If[i1 dx < 2, 100 a1,                If[i1 dx < 4, 100 a2,                  If[i1 dx < 6, 100 a3,                    If[i1 dx < 8, 100 a4, 100 a5]]]],              {i1, 1,n - 2}];         kr = ReplacePart[#, 1 -> (α delta/Vf)] & /@ kr;          NtwrkTT = TT = Plus @@ (Plus @@ kr);         While[TT > 0,            TT = 0;           qf = MapThread[flo[L, ##] &, {Most@k0, Rest@k0}];           ϕ = demand[1, #[[-1]] ] & /@ kr MapThread[gamma, {k0[[2 ;; -2]], k0[[3 ;;]]}];           qin = inflow[ϕ, Most@qf];           k0 += Join[{0}, density[Most@qf, Rest@qf, qin], {0}];           RM = MapThread[Min[#1, #2] &, {RMori, flo[1, #[[RML]], #[[RML + 1]]] & /@ kr}];           qr =              MapThread[Join[#1, {#2}, #3, {#4}] &,                {flo[1, ##] & @@@ Partition[#[[;; RML]], 2, 1] & /@ kr,                 RM,                 flo[1, ##] & @@@ Partition[#[[RML + 1 ;;]], 2, 1] & /@ kr, ϕ}];           kr =              MapThread[(#1 + #2) &,                {Join[{0}, #] & /@ (density[Most@#,Rest@#, 0] & /@ qr), kr}];           If[j > m && Shutoff == False, Shutoff = True;            kr = ReplacePart[#, 1 -> 0] & /@ kr];           TT += Plus @@ k0;            TT += Plus @@ (Plus @@ kr);            NtwrkTT += TT;            j++;];         NtwrkTT dt]]      When the function is evaluated at `f[39, 39, 39, 39, 39]`, it gives the following errors > >     ReplacePart::argrx: ReplacePart called with 2 arguments; 3 arguments are > expected. >> >     ReplacePart::argrx: ReplacePart called with 2 arguments; 3 arguments are > expected. >> >     ReplacePart::argrx: ReplacePart called with 2 arguments; 3 arguments are > expected. >> >     General::stop: Further output of ReplacePart::argrx will be suppressed > during this calculation. >> >     Compile::cpintlt: 3;;All at position 2 of k0[[3;;All]] should be either > a nonzero integer or a vector of nonzero integers; evaluation will use the > uncompiled function. >> >     Compile::cpintlt: 3;;All at position 2 of k0[[3;;All]] should be either > a nonzero integer or a vector of nonzero integers; evaluation will use the > uncompiled function. >> >     Compile::cset: Variable \[Phi] of type {_Integer,0} encountered in > assignment of type {_Integer,1}. >> >     Compile::cplist: density[Most[qf],Rest[qf],qin] should be a tensor of > type Integer, Real, or Complex; evaluation will use the uncompiled function. > >> >     Compile::cpapot: Compilation of > (flo[1,##1]&)@@Compile`GetElement[System`Private`CompileSymbol[4],System`Private`CompileSymbol[5]] > is not supported for the function argument flo[1,##1]&. The only function > arguments supported are Times, Plus, or List. Evaluation will use the > uncompiled function. >> >     Compile::cpapot: Compilation of > (flo[1,##1]&)@@Compile`GetElement[System`Private`CompileSymbol[4],System`Private`CompileSymbol[5]] > is not supported for the function argument flo[1,##1]&. The only function > arguments supported are Times, Plus, or List. Evaluation will use the > uncompiled function. >> >     Compile::cpapot: Compilation of > (flo[1,##1]&)@@Compile`GetElement[System`Private`CompileSymbol[4],System`Private`CompileSymbol[5]] > is not supported for the function argument flo[1,##1]&. The only function > arguments supported are Times, Plus, or List. Evaluation will use the > uncompiled function. >> >     General::stop: Further output of Compile::cpapot will be suppressed > during this calculation. >> >     Compile::cpintlt: RML+1;;All at position 2 of > Compile`GetElement[kr,System`Private`CompileSymbol[0]][[RML+1;;All]] should > be either a nonzero integer or a vector of nonzero integers; evaluation will > use the uncompiled function. >> >     General::stop: Further output of Compile::cpintlt will be suppressed > during this calculation. >> >     Compile::cset: Variable kr of type {_Integer,2} encountered in > assignment of type {_Integer,0}. >> >     Compile::cset: Variable \[Phi] of type {_Integer,0} encountered in > assignment of type {_Integer,1}. >> >     General::stop: Further output of Compile::cset will be suppressed during > this calculation. >> >     Compile::cplist: density[Most[qf],Rest[qf],qin] should be a tensor of > type Integer, Real, or Complex; evaluation will use the uncompiled function. > >> >


title: Summarizing SQL Tables

text: `data = Table[SQLSelect[conn, "All", {"col1", "col2"}, SQLColumn["col1"] == n && SQLColumn["col2"] == o], {n, 1, 8}, {o, 21, 30}];` This results in selecting the range of data in each column specified. What I'd really like to do is get a count of _each_ value in col1 _for each_ value in col2. As it is, I will get: {1,21},{1,22},{1,23},{1,24},{1,25},{1,26},{2,27},{1,23}... If I use the complete range of values I just cull col1 and col2 from my original table. What I have in mind is a table, per this example code, 8 rows x 9 columns that shows the count of all the times 1 and 21 appear together, then all the times 1 and 22 appear together up to 30, then how many times 2 and 21 appear and so on. I want to end up with a table that looks something like this (row and column headers can be ignored):                    21  22  23  24  25  26  27  28  29  30     1    1   1   2   7   12  30  47  80  91  112     2    1   1   3   12  18  48  59  118 133 151      and so on... These SQL symbols are tricky in that they react strangely to variable manipulations. Any suggestions would be appreciated.


title: Fill below two functions.

text: I'm new to Mathematica and some of the filling stuff is confusing me. I don't think this should be too hard but I can't seem to get it to work. I have plotted x and -x. I want to fill below BOTH of them and above BOTH of them in two different plots. How can this be done?


title: How can I use the Klingon alphabet symbols?

text: **Note:** This functionality is presently missing. See: How to add named characters to Mathematica 10? * * * _Mathematica_ apparently supports the Klingon alphabet:               MemberQ[$CharacterEncodings, "Klingon"]      > True UnicodeFontMapping.tr excerpt: > >     0xF8D0        N       15      0x41        # \[KlingonA] >     0xF8D1        N       15      0x42        # \[KlingonB] >     0xF8D2        N       15      0x43        # \[KlingonCH] >     0xF8D3        N       15      0x44        # \[KlingonD] >     0xF8D4        N       15      0x45        # \[KlingonE] >     0xF8D5        N       15      0x47        # \[KlingonGH] >     0xF8D6        N       15      0x48        # \[KlingonH] >     0xF8D7        N       15      0x49        # \[KlingonI] >     0xF8D8        N       15      0x4a        # \[KlingonJ] >     0xF8D9        N       15      0x4c        # \[KlingonL] >     0xF8DA        N       15      0x4d        # \[KlingonM] >     0xF8DB        N       15      0x4e        # \[KlingonN] >     0xF8DC        N       15      0x46        # \[KlingonNG] >     0xF8DD        N       15      0x4f        # \[KlingonO] >     0xF8DE        N       15      0x50        # \[KlingonP] >     0xF8DF        N       15      0x4b        # \[KlingonQ] >     0xF8E0        N       15      0x51        # \[KlingonQH] >     0xF8E1        N       15      0x52        # \[KlingonR] >     0xF8E2        N       15      0x53        # \[KlingonS] >     0xF8E3        N       15      0x54        # \[KlingonT] >     0xF8E4        N       15      0x58        # \[KlingonTLH] >     0xF8E5        N       15      0x55        # \[KlingonU] >     0xF8E6        N       15      0x56        # \[KlingonV] >     0xF8E7        N       15      0x57        # \[KlingonW] >     0xF8E8        N       15      0x59        # \[KlingonY] >     0xF8E9        N       15      0x27        # \[KlingonGlottalStop] >     0xF8F0        N       15      0x29        # \[Klingon0] >     0xF8F1        N       15      0x21        # \[Klingon1] >     0xF8F2        N       15      0x40        # \[Klingon2] >     0xF8F3        N       15      0x23        # \[Klingon3] >     0xF8F4        N       15      0x34        # \[Klingon4] >     0xF8F5        N       15      0x25        # \[Klingon5] >     0xF8F6        N       15      0x5e        # \[Klingon6] >     0xF8F7        N       15      0x26        # \[Klingon7] >     0xF8F8        N       15      0x2a        # \[Klingon8] >     0xF8F9        N       15      0x28        # \[Klingon9] >     0xF8FF        N       15      0x5a        # \[KlingonEmpire] >   **What font and settings do I need to make these visible?** * * * Klingon alphabet:   ![Klingon alphabet](http://i.stack.imgur.com/WSNQJ.gif) Klingon numerals:   ![Klingon numerals](http://i.stack.imgur.com/Fh6oC.gif)


title: Unit testing J/Link projects in Workbench

text: I am having some problems setting up the MUnit testing framework for a J/Link project and would be grateful for advice. I _do_ have J/Link working when running or debugging the .nb notebook in workbench, just can't get it going when trying to run or debug the .mt unit test file. I did the following steps, following the documentation as closely as i can. I created a fresh J/Link project, right-click the inner project folder and choose New / TestFile, and I get a tree like the following in the package explorer of workbench:               fooProject     +-- javaSource     +-- JRE System Library [1.1]     +-- fooProject     |   +-- Java     |   +-- Kernel     |   |   +-- init.m     |   +-- fooProject.m     |   +-- fooProject.mt <---- this is my unit test file; can't get it going     +-- fooProject.nb     <---- this one works well      I put a couple of functions in my .m package file:               (* Mathematica Package *)     (* Created by the Wolfram Workbench Feb 3, 2012 *)     BeginPackage["fooProject`", {"JLink`"}]     (* Exported symbols added here with SymbolName::usage *)      KvpQ::usage = "Tests whether its argument is a KVPair or KVP, that is, a list of two values, the first of which is a string or symbol Key.";     Begin["`Private`"]     (* Implementation of the package *)     SymbolQ[x_Symbol] := True;     SymbolQ[___] := False (* all other cases produce False *);     KvpQ[kvp_List] := (Length@kvp === 2 &&        (StringQ[kvp[[1]]] || SymbolQ[kvp[[1]]]));     KvpQ[___] := False;     End[]     EndPackage[]      Then I open the MUnit Test file, fooProject.mt, do `Ctrl`+`K` and choose the test template, and then fill it out:               (* Mathematica Test File *)     Test[         KvpQ[{}]         ,         False         ,         TestID->"fooProject-20120203-Q0O8P9"     ]      Now, following the directions at the wolfram site on J/Link launching, I create the new configuration as directed accepting all defaults. Then when I try to run the unit tests, I get a dialog with the unsettling message:               The selected file is not a Mathematica notebook or scrapbook file.      Please make sure that a file with extension .nb or .mscrapbook      is selected, then try the run again.      This leads me to suspect that MUnit testing just isn't supported for J/Link projects, which would make me sad :( But it's more likely I've just done something silly wrong. Again, I'd be grateful for any advice or guidance. Thanks.


title: Why does Fourier give a large error in MachinePrecision?

text: Consider this code:               f[x_] = Cos[2 π x];          N0 = 10;          ls = Most @ Array[f, N0, {0, 1}]     (*        {1, Cos[(2 π)/9], Sin[π/18], -(1/2), -Cos[π/9], -Cos[π/9],        -(1/2), Sin[π/18], Cos[(2 π)/9]}     *)      Since the function is a periodic function, I would expect the Fourier transform give only two non-zero coefficients. Using `Fourier` I get               Fourier[ls]     (*        {-6.4763*10^-17 + 0. I, 1.5 + 5.55112*10^-17 I, 1.60247*10^-17 + 2.77556*10^-17 I,         3.23815*10^-17 - 8.01234*10^-18 I, -1.60247*10^-17 - 2.77556*10^-17 I,         -1.60247*10^-17 + 2.77556*10^-17 I, 3.23815*10^-17 + 8.01234*10^-18 I,         1.60247*10^-17 - 2.77556*10^-17 I, 1.5 - 5.55112*10^-17 I}     *)      there is an error about 10^-17. However, if I change the precision, I get               Fourier[SetPrecision[ls, 8]]     (*        {0.*10^-8, 1.5000000 + 0.*10^-8 I, 0.*10^-8 + 0.*10^-8 I, 0.*10^-8 + 0.*10^-8 I,         0.*10^-8 + 0.*10^-8 I, 0.*10^-8 + 0.*10^-8 I, 0.*10^-8 + 0.*10^-8 I,         0.*10^-8 + 0.*10^-8 I, 1.5000000 + 0.*10^-8 I}     *)          Fourier[SetPrecision[ls, 16]]     (*        {0.*10^-16, 1.500000000000000 + 0.*10^-16 I, 0.*10^-16 + 0.*10^-16 I,         0.*10^-16 + 0.*10^-16 I, 0.*10^-16 + 0.*10^-16 I, 0.*10^-16 + 0.*10^-16 I,         0.*10^-16 + 0.*10^-16 I, 0.*10^-16 + 0.*10^-16 I, 1.500000000000000 + 0.*10^-16 I}     *)          Fourier[SetPrecision[ls, 32]]     (*        {0.*10^-32, 1.5000000000000000000000000000000 + 0.*10^-32 I,0.*10^-32 + 0.*10^-32 I,         0.*10^-32 + 0.*10^-32 I, 0.*10^-32 + 0.*10^-32 I, 0.*10^-32 + 0.*10^-32 I,         0.*10^-32 + 0.*10^-32 I, 0.*10^-32 + 0.*10^-32 I,         1.5000000000000000000000000000000 + 0.*10^-32 I}     *)      So why I get the error only in the machine precision case? Are these errors in `Fourier[ls]` coming from _Mathematica_ or related to how numbers are represented in computers? Edit: If we fix the precision in the calculation, we can see that the errors are smaller compared to Machine precision calculation.               Block[{$MaxPrecision = 8, $MinPrecision = 8}, Fourier[SetPrecision[ls, 8]]]     (* {-4.3981121*10^-35, 1.5000000, 1.8230938*10^-34, 2.1989581*10^-35, 1.8230938*10^-34, 1.8230938*10^-34, 2.1989581*10^-35, 1.8230938*10^-34, 1.5000000} *)          Block[{$MaxPrecision = 16, $MinPrecision = 16}, Fourier[SetPrecision[ls, 16]]]     (* {-4.406340574057345*10^-35, 1.500000000000000, 1.816158363592948*10^-34, 2.203268244891241*10^-35, 1.816158363592948*10^-34, 1.816158363592948*10^-34, 2.203268244891241*10^-35, 1.816158363592948*10^-34, 1.500000000000000} *)


title: How to transform a DynamicModule into a Graphic

text: I am generating a graph through a custom function using `DynamicModule`:               graph1 = customFunction[a]      If I try to do:               Show[graph1]      I get the message > "DynamicModule is not a type of graphics." How can I convert the output of my `DynamicModule` function into a graphic? My ultimate goal is to combine multiple graphics with `Show`:               graph1 = customFunction[a]     graph2 = customFunction[b]       Show[graph1,graph2]


title: Connecting to and disconnecting from a continuously running kernel, on demand

text: I realized that there are lots of advantages to driving C/C++/FORTRAN code directly from Mathematica as LibraryLink functions (instead of running them from the command line or a shell script, as I have usually done before). This will give access to a lot of functionality that is difficult or time consuming to implement in a low level language (example). There are disadvantages too, mainly because the running environment is typically a remote server, and not a local workstation (i.e. I don't get a notebook GUI). So, to get around some of the disadvantages, **Is the following feasible to implement (see below)?** Can we have a Mathematica master kernel running a remote kernel, running parallel calculations in subkernels, and do the following: While the calculation is running, connect to the master computer through MathLink from a laptop; check the state of the calculations, perhaps do some quick-to-compute preliminary analysis on the so far calculated results; make decisions about continuing the calculation or not; then disconnect. It should be possible to connect to and disconnect from the server as many times as necessary without aborting the calculations for good. Do you think that such a thing is (theoretically) possible to implement with the current version of Mathematica? Or perhaps the current features are not general enough to allow it? Before sitting down to study the documentation in detail and try to implement this, I was wondering if anyone is aware of any showstopper limitations (or if anyone has tried to implement it).


title: How to fix errors in Gram-Schmidt process when using random vectors?

text: I first make a function to get a random vector on unit sphere in a swath around the equator. That is what the parameter $\gamma$ controls; if $\gamma = 1/2$, the vectors can be chosen anywhere on the sphere; if $\gamma = 0$, the vectors can only be chosen from the equatorial plane etc.               randomVectorOnUnitSphere[\[Gamma]_] := Module[{},     \[Phi] = RandomReal[{0, 2 \[Pi]}];     w = RandomReal[{1/2 - \[Gamma], 1/2 + \[Gamma]}];     nx = Cos[\[Phi]] Sin[ArcCos[2 w - 1]];     ny = Sin[\[Phi]] Sin[ArcCos[2 w - 1]];     nz = Cos[ArcCos[2 w - 1]];     Return[{nx, ny, nz}];     ]      These two random vectors span a plane. I would like to find an orthonormal basis for that plane so I use the Gram-Schmidt process as so:               randMod[\[Gamma]_] := Module[{},     v1 = randomVectorOnUnitSphere[\[Gamma]];(*random unit vector 1*)     v2 = randomVectorOnUnitSphere[\[Gamma]];(*random unit vector 2*)     u1 = v1; (* start Gram-Schmidt process *)     proj = u1.v2/u1.u1 u1;     u2temp = v2 - proj;     u2 = u2temp/Sqrt[u2temp.u2temp];     Return[{u1,u2}] (*the output here is 2 orthonormal vectors that span the plane*)     ];      I look at 10000 pairs and plot on unit sphere:               randTable1 = ParallelTable[randMod[1/10][[1]], {i, 1, 10000}];     randTable2 = ParallelTable[randMod[1/10][[2]], {i, 1, 10000}];     randPlot1 =      ListPointPlot3D[{randTable1, {{0, 0, 1}}},      PlotStyle -> {Black, {PointSize -> 0.025, Red}}];     randPlot2 =      ListPointPlot3D[{randTable2, {{0, 0, 1}}},      PlotStyle -> {Black, {PointSize -> 0.025, Red}}];     {Show[Graphics3D[Sphere[{0, 0, 0}, 1]], randPlot1],      Show[Graphics3D[Sphere[{0, 0, 0}, 1]], randPlot2]}       and get the output for all the $u_1$ (top) and $u_2$ (bottom): ![This is $u_1$](http://i.stack.imgur.com/IlQrW.gif)![This is $u_2$ \(not sure why size larger, sorry\)](http://i.stack.imgur.com/J0EIf.gif) The $u_2$ vectors are concentrated at the equator but there is a sizable number that are spreadout over the sphere. I would expect to get something that looked just like $u_1$ instead. The initial vectors $v_1$ and $v_2$ lie in the same 'swath' as $u_1$ so I know that it is the G-S process that is failing. I have looked at some of the culprit points and have noticed that their initial starting vectors were near parallel. I think this is the cause of the problem. I tried increasing WorkingPrecision when I call RandomReal but that did not seem to have any noticeable effect. Is there a way I can fix this problem?


title: Is the communication protocol underlying MathLink user-customizable?

text: MathLink supports two communication protocols on all platforms: TCPIP or shared memory. There are additional protocols supported on some systems only ("FileMap" and "Pipes" according to the docs). I do not have much familiarity with MathLink's C language interface. **Question:** Is the MathLink communication protocol user-customizable? Can MathLink be extended by users to use an alternative underlying communication protocol (example)?


title: What is the Mathematica way of joining two tables?

text: Is there a special _Mathematica_ way of joining tables of data together, so that I would get similar functionality as if I was running a database with sql? For example, I have one particular table here, and getting data out of it is getting a bit verbose. Here is an example, but is there a better way to work with data. I thought there would be a simple way of creating tables and joining them, something similar to a dataframe in R perhaps?               Tally[       Flatten[         GatherBy[Transpose[{data[[All, 9]], data[[All, 8]]}], # == "Yes"] ,          1       ]     ]      returns               (*         {          {{"Yes", "South West"}, 42}, {{"No", "The North"}, 325},           {{"Yes", "Midlands & East Anglia"}, 92}, {{"No", "Scotland"}, 97},          {{"No", "Midlands & East Anglia"}, 351}, {{"Yes", "Wales"}, 20},           {{"No", "South East"}, 187}, {{"No", "South West"}, 115},           {{"No", "Wales"}, 63}, {{"No", "London"}, 132}, {{"Yes", "London"}, 50},          {{"Yes", "The North"}, 101}, {{"Yes", "South East"}, 65},           {{"Yes", "Scotland"}, 51}        }     *)      Here is an example of the data I am working with:               {{"gender", "age", "maritalStatus", "highestQualification", "nationality", "ethnicity",        "grossIncome", "region", "smoke", "amtWeekends", "amtWeekdays", "type"},       {"Female", 51, "Divorced", "Other/Sub Degree", "English", "White",        "Unknown", "South West", "Yes", 25, 25, "Packets"},       {"Female", 52, "Married", "No Qualification", "English", "White",        "Unknown", "The North", "No", "NA", "NA", ""},       {"Female", 53, "Divorced", "GCSE/O Level", "English", "White",        "Unknown", "Midlands & East Anglia", "Yes", 7, 12, "Packets"},       {"Female", 59, "Divorced", "Degree", "Scottish", "White",        "Unknown", "Scotland", "No", "NA", "NA", ""},       {"Female", 61, "Married", "A Levels", "English", "White",        "Unknown", "Midlands & East Anglia", "No", "NA", "NA", ""},      {"Male", 66, "Married", "No Qualification", "English", "White",        "Unknown", "The North", "No", "NA", "NA", ""},       {"Female", 69, "Widowed", "No Qualification", "English", "White",        "Unknown", "Wales", "Yes", 15, 15, "Packets"},       {"Female", 69, "Widowed", "No Qualification", "English", "White",        "Unknown", "The North", "No", "NA", "NA", ""},       {"Male", 71, "Divorced", "No Qualification", "English", "White",        "Unknown", "The North", "No", "NA", "NA", ""}}


title: Plotting data with exponentials

text: I have some data with 19000 sublists such as :               {"   7.9080000e+01   1.9283193e+04"}      Where the first number is the value for variable `A` and the second for variable `B`. All my attempts to transform this format have failed so far. I think my best guess was using `ToExpression` unsuccessfully. How can I transform such lists to a "plottable" format by   * Changing the `String` format ?   * Computing the `e` ?   * Import the data differently ?


title: Pattern to match a non-empty list of non-empty lists

text: **Is there a pattern to match a list of lists, containing at least one list, with each list containing at least one element?** In the Mathematica documentation it says that the pattern               x:{___List}      will match a list of lists. This is true, but it also matches `{}`, which is a list of zero lists (or zero _anything_ ). To make sure there is at least one list in my list of lists I can remove one of the underscores to change `BlankNullSequence` to `BlankSequence`, i.e. switch to               x:{__List}      which no longer matches `{}`. It does, however, match `{{}}`. How can I also guarantee that each matched sublist is non-empty? Is this even possible, or should I be checking for it programmatically within the `Module` to which I'm passing arguments of this form?


title: Data Table Manipulation

text: Suppose that I have the following               table = List[{"ID", "Variable 1", "Variable 2"}, {"Alpha", 1,         0}, {"Beta", 1, 1}, {"Alpha", 0, 0}, {"Gamma", 1, 0}, {"Gamma", 2,         2}]      Regard to this Post, we can use `select` (user-defined function) to select what we want based on either rows or columns. For example, we can use               select[table, where["ID" == "Alpha"]]      the return will be `{{"Alpha", 1, 0}, {"Alpha", 0, 0}}`. If I want to select multiple categories, for example, I want "Alpha" and "Gamma", I can use               select[table, where["ID" == "Alpha"||"ID" == "Gamma"]]      My point here is that you can do this if you have small table. What if you have very large table and you need to select multiple categories. You may have to write               select[table, where["ID" == "Alpha"||"ID" == "Gamma"||"ID"=="Beta"||....so on]]      What I did was to use               Flatten[select[table, where["ID"==#]]&/@{"Alpha", "Gamma"},1]      but it is slow if you have very large table. Could anyone give me suggestions?


title: Using a Slider to manipulate a Plot

text: Why does this work (displays the curve):               Graphics[Plot[Sin[x], {x, 0, Pi}]]      and this doesn't (no curve)               Graphics[Plot[Sin[a x], {x, 0, Pi}], {Slider[a, 0, 4]}]      ? I would like to work without `Manipulate`.


title: Why ColorReplace does not follow the rules specified?

text: I tried to use `ColorReplace` to change the colors obtained from `MorphologicalComponents`. However some of the changes didn't follow the rules specified, Is there any reasons?               im2 = Binarize@Import["http://i.stack.imgur.com/ZDeYq.jpg"];     im3 = Colorize@ MorphologicalComponents@im2      colors = DominantColors[im3, 5]       ![enter image description here](http://i.stack.imgur.com/5gZkM.gif) Now trying to change the colors accordingly,               ColorReplace[im3, {       colors[[2]] -> Red,        colors[[3]] -> Blue,        colors[[4]] -> Green,        colors[[5]] -> Yellow       }]      One of the changes did not follow the rules specified: ![enter image description here](http://i.stack.imgur.com/aNxL2.gif)


title: How can I solve Tan[t] - t == F[x] for t as a function of x?

text: How can I solve the equation `Tan[t] - t = Ax`, where `A` is a constant for `t[x]`? I know that it's impossible to get a close-form solution, but how can I get a numerical approximation with _Mathematica_?


title: Wolfram Workbench autocomplettition

text: Suppose I have some project in `Wolfram Workbench`. In some packages need DatabaseLink`. I write it in this way:               BeginPackage["test`"]     Needs["DatabaseLink`"];          test::usage="";          Begin["`Private`"]          test[x_]:=SQLConnections[];          End[]          EndPackage[]      All work fine. But autocompletion of DatabaseLink functions don't work. How can I use autocompletion for imported contexts (applications)?


title: Is there any fast way to solve a quadratic matrix equation in Mathematica approximately?

text: Let the square nonsingular matrix $M$ is a given convergent matrix. What are the best scalar values for $\alpha$ and $\beta$ (in the real numbers domain), at which the following quadratic matrix equation _approximately_ holds: \begin{equation} M^2+\alpha M+\beta I\approx0. \end{equation} In fact, I would like to find the scalar values as closely as possible for the following matrix $M$ (as an example)               Clear["Global`*"]     SeedRandom[12345]     n = 1000; Id = SparseArray[{i_, i_} -> 1., {n, n}, 0.];     A = RandomReal[{-1, 1}, {n, n}];     X = 1/SingularValueList[A, 1][[1]]^2 ConjugateTranspose[A];     M = A.X;      Also I tried to use NMinimize or FindInstance, but I failed. Please note that a rapid approach is more better for me to find more accurate values for the scalar paramteres.


title: Using Piecewise in RevolutionPlot3D

text: The documentation for `RevolutionPlot3D` shows that you can specify a parametric curve like this:               RevolutionPlot3D[{u, u}, {u, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/Zppvk.png) I'd like to do this with a `Piecewise` function for `{fx,fz}`:               RevolutionPlot3D[Piecewise[{{{u, u}, u < 0.5}, {{u, 0.5}, u >= 0.5}}], {u, 0,        1}]      but I get messages and a blank plot: > Dot::rect: Nonrectangular tensor encountered. ![Mathematica graphics](http://i.stack.imgur.com/o57ob.png) whereas a `Piecewise` function for `{fx,fz}` works in `ParametricPlot`, for example:               ParametricPlot[Piecewise[{{{u, u}, u < 0.5}, {{u, 0.5}, u >= 0.5}}], {u, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/1pJqp.png) By writing `Piecewise` expressions for `fx` and `fz` separately, it works:               RevolutionPlot3D[{Piecewise[{{u, u < 0.5}, {u, u >= 0.5}}],          Piecewise[{{u, u < 0.5}, {0.5, u >= 0.5}}]}, {u, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/LtPbf.png) How is it possible to piece together a function for `{fx,fz}` in `RevolutionPlot3D`?


title: Two x-axis with different units connected by function using CustomTicks

text: I am trying to make a plot of some photoluminescence data, where wavelength is on the x-axis, and intensity is on the y-axis. Also, I would like to have the graph boxed, with the upper x-axis having units of energy in eV, connected to the wavelength through the function: energy=1240/wavelength. I have tried to use the `TickLabelFunction` in the LevelScheme package, and have only partly succeeded. I can't control the number of decimal points for the ticks on the energy scale. For some reason, `N[]` doesn't work. Also, the energy tickmarks seem to follow the wavelength ticks, i.e. one energy tick for each wavelength tick. I would like those ticks to be spaced nonlinearly and independently of the other axis, e.g. having them increase with steps of 0.2 eV. Here is a small code that I hope will illustrate my problem.               test = List[{500, 50}];     ListPlot[test, Frame -> True, ImageSize -> 600,      PlotRange -> {{400, 800}, {-10, 110}},      FrameLabel -> {"Wavelength (nm)", "Intensity (a.u.)", "Energy (eV)"},     FrameTicks -> {LinTicks[400, 800, 100, 5], LinTicks,      LinTicks[400, 800, 100, 5,      TickLabelFunction -> Function[x, N[1240/x, 2]]],      StripTickLabels[LinTicks]}]      Any input appreciated, either using the LevelScheme package or not. Thanks!


title: How to deal with WebServices error "any is not supported in sequence"?

text: I am trying to aquire data through Mathematica's WebServices and this example works just fine:               <<WebServices`     InstallService["http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"]     ConversionRate["USD","RUB"]      However, when I try to install this service:               InstallService["http://cbr.ru/secinfo/secinfo.asmx?WSDL"]      Mathematica returns with error messages:               LoadSchema::unsupported: any is not supported in sequence.     LoadSchema::elementschema: The element schema cannot be found for {http://www.w3.org/2001/XMLSchema, schema}.      I'm not very well versed in XML however it seems that there's an "any" tag present in the code of the service, is that a provider's mistake?


title: Levels: how do they work?

text: I cannot understand how Mathematica manages levels, and so it's always a painful try-and-fail to use `Flatten`. Can someone please give me a very clear definition? If you feel like giving an example, please tell me how to turn this list `{{a, {a1}}, {b, {b1}}, {c, {c1}}, ...}` into `{{a, a1}, {b, b1}, {c, c1}, ...}` with `Flatten`, if possible.


title: Finding concave hull for separated small clusters

text: Data :                data3D = Import[file, "VertexData"];      Graphics3D[Point[data3D]]      ![enter image description here](http://i.stack.imgur.com/DKD0A.jpg) How to find concave polygon for separated small clusters.


title: Optimizing NIntegrate for higher PrecisionGoal

text: By default, `NIntegrate` works with `MachinePrecision` and its `PrecisionGoal` is set to `Automatic` which is effectively a value near 6:               In[1]:= Options[NIntegrate, {WorkingPrecision, PrecisionGoal}]          Out[1]= {WorkingPrecision -> MachinePrecision, PrecisionGoal -> Automatic}      I need sufficiently higher accuracy when computing the following integral:               dpdA[i_] := NIntegrate[       Cos[φ] Cos[i*φ] Exp[Sum[-Cos[j*φ], {j, 11}]], {φ, 0, Pi},        Method -> {Automatic, "SymbolicProcessing" -> None}]      The integral cannot be taken symbolically, so `"SymbolicProcessing"` is off. The problem is that when I increase `PrecisionGoal` to 15 and consequently `WorkingPrecision` to a value higher than `MachinePrecision` I get very low performance. Is it possible to compute this integral with at least 15 significant digits with high performance?


title: What's the main difference between FindClusters and ClusteringComponents?

text: In many cases, `FindClusters` and `ClusteringComponents` provide similar results. Options for hierarchical and agglomerative clustering are available for both of these functions. So, would you please help me to understand clearly the differences between them? Just to be clear,my main question concerns about choosing appropriate function for different research questions and anlysis. That is, it's not important if the two functions (or other similar functions) produce different outputs with the same meaning rather I want to know when to use which function and why. Also, please post any tutorial for cluster analysis in Mathematica if you aware of.


title: Is there any good way to find and/or plot numerical integrals of non-continuous functions like Tan[x]?

text: I believe that the answer to this may be obvious to some of you, but I just can't think of anything that works. NIntegrate, NDSolve, etc, all throw a temper tantrum when they have to divide by zero, and it's not really an issue that an InterpolatingFunction can deal with either. Is there any way to approach this? **EDIT** Example: If I just type               Plot[NIntegrate[Tan[u],{u,0,x}],{x,0,2Pi}]      I am going to get an error immediately, at least in the form of a graph that goes insane. I can kind of try to get around that by doing this:               ntan[x_] := FunctionInterpolation[Tan[x],{x,0,2Pi}]     Plot[NIntegrate[Tan[u], {u, 0, x}], {x, 0, 2 Pi}      This immediately throws some errors, and you get a plot that is certainly not right. The very large values ruin the calculation completely! This is definitely not right. I know with Tan[x] you can just easily integrate it and plot it and all is well, but I'm curious how to get a more general way of plotting integrals of functions with singularities that cannot be easily integrated.


title: How to make BSplineFunction pass each data point and naturally smooth?

text: ( ** _Old package, works good_** )               Needs["Splines`"];          testData = {{10, 10}, {10, 20}, {10, 25}, {10, 27}, {10, 28}, {9,          26}, {8, 25}, {5, 20}, {3, 1}};          fFit = SplineFit[testData, Cubic];          ParametricPlot[fFit[n], {n, 0, Length[testData] - 1},                     Epilog -> Point[testData]]      ( ** _New spline package, how to make it work like the old one: passing each point exactly and naturally smooth_** )               fFit01 = BSplineFunction[testData];          ParametricPlot[fFit01[n], {n, 0, Length[testData] - 1},                     Epilog -> Point[testData]]      ( ***The fitting results are different: some points are not passed exactly, which is not what I need** )


title: finding poles of a function

text: Is there a command to find the poles of a function $f=f(z)$? example: let $$f(z) = \frac{1}{z^2-1}$$ then we know that the poles are at $z=\pm 1$ but is there a special command in mathematica to do this?


title: Locator following other locator in DynamicModule

text: I'm trying to create a dynamic environment where I specify, using two locators, the initial condition (position (x,y) and velocity angle (alpha)) of a 2D particle. To simplify, I'm assuming the initial position is restricted to a circle, and the velocity angle is always in respect to an angle _in relation to the normal_ vector, perpendicular to the tangent vector. This means that in the end, I would like to have 3 parameters: x,y initial position of the positional locator, and an initial angle, defined as the angle between the vector (positional locator - angle locator) and the normal vector. The main problem resides on the coupling between the positional locator, and the angle locator: when I move the positional locator, I would like to have the angle locator moved in such a way that the initial angle is preserved. To manipulate those, I'm using two Locators: one for position (initialPoint), one for initial angle (pt2)               DynamicModule[{initialPoint = {0, 0}, pt2 = {0, 0}},      Style[Graphics[{         Dashed,         Circle[{0, 0}, 1],         Locator[          Dynamic[pt2, (pt2 =               initialPoint + 0.5 Normalize[# - initialPoint]) &]],          Locator[Dynamic[initialPoint, (initialPoint = Normalize[#]) &]]},         PlotRange -> {{-3.3, 3.3}, {-3.3, 3.3}}, AspectRatio -> 1],        Selectable -> False]]      however, when I dynamically pick the initialPoint, the second locator does not follow it. What can I do it in order to keep pt2 always such that the initial angle is preserved?


title: Taking a percentage of data from a list or a table

text: I have a list of data and for the calculation I only need the a of portion of the data. I know that `Take[data, {1,100}]`, for example, is taking line 1 to 100 of the file. But what I need it for me is to take percentage of the data like, drop first 10% and drop last 10% of the data. So I'll only have 80% of the middle portion to work with. So that if I have multiple list with amount of data changing I would not have to keep counting the number of lines or length to calculate. Thanks.


title: Unwanted parentheses appearing in a notebook that is opened by a button

text: I am writing an interactive document and have an idea to make in-line buttons that on demand would create and bring up separate notebooks containing some explanations or a remindings. One example of the code of such a button is as follows:               Button["Show it",      CreateDocument[       Column[{         Spacer[30],         TextCell["some explanatory text:" , "Text", FontSize -> 20],         Spacer[10],         TextCell[           Row[{Spacer[50], Style["Φ=", 24, Italic],              Style[HoldForm[(ϕ*τ^2*ν^3*ω*θ[                 1 - ν*ω])/(τ^2*ν^2 +                  2*δ*ν*τ + ω^2)^2], Italic, 30]}],            TextAlignment -> Center] // TraditionalForm          }, Alignment -> Left],           WindowTitle -> "An expression", WindowSize -> {400, 300}],           ImageSize -> {70, 18}, Background -> Brown,           BaseStyle -> {"GenericButton", Bold}]       Upon its evaluation a button is created. This button one can copy-pasted into a necessary part of the text, say, into an in-line cell. It works, in principle. It works irreproachably, if there is only a text or a text and any graphics inside. With the formula it is more complex. If the button contains a formula such as the one in the code above, and if I press the button for the first (second and so on ) time I get the document open with the formula that looks as follows: If you see here no picture, try yourself, what I explained in words. And that is what I intended to. Now comes my "however". However, if I save/close the main document (the one containing the button code and the button itself, then open it once more and press the button, I get this: If you see here no picture, try yourself, what I explained in words. As you see there is a lot of unwanted patantheses appeared. The question is how can I get rid of these parasitic parantheses? Small addition: I have forgotten to write that there is an evident work around. The expression in question may be saved as an image and in that form passed into the button statement. Then the code is like this               Button["Show it",      CreateDocument[       Column[{         Spacer[30],         TextCell["some explanatory text:" , "Text", FontSize -> 20],         Spacer[10],         ExpressionCell[          Row[{Spacer[50],             Show["Paste here the image of a formula", ImageSize -> 250]}]]          }, Alignment -> Left],       WindowTitle -> "An expression", WindowSize -> {400, 300}],       ImageSize -> {70, 18}, Background -> Brown,       BaseStyle -> {"GenericButton", Bold}]      This is the way, of course, but I am not fond of it. The reason is that my document contains dozens of such buttons. If each of them will contain an image or two, the document size will rise too much. **To summarize** : after the very helpful answers made by bil s and bobknight I see two ways of coping with the problem. I first outline the problem below and then discuss the solutions. The problem consists in making a button to show a window with a formula as described. The difficulty is that the variables met in the formula may take part in calculations in the document and may have already been assigned to something. Even more, this assignment may be needed in some place of the document after the place where the button is used. I initially tried to cope with it by applying HoldForm. This is not the right way, however, since it is the HoldForm statement that is responsible for extra parentheses that show up when one closes the document, then opens it and then presses the button. I also tried to use the scoping constructs like Module, but with no success, as I explained in discussion with bil s (see comments). In the present form neither of the answers deal with this problem. However, on the basis of these answers I think I understand now how to deal with it. I see two ways. First, it is possible to clear the variables met in the formula. Then one should take care that the necessary variables should be defined before each calculations, or each calculation should use a scoping construct. Like this the bil s solutions works as follows:                Button["Show it",       Clear[Φ, τ, ϕ, ν, ω, θ, \     δ];       CreateDocument[       Column[{Spacer[30],          TextCell["some explanatory text:", "Text", FontSize -> 20],          Spacer[10],          TextCell[           Row[{Spacer[50], Style["Φ=", Italic, 30],              Style[(ϕ τ^2 ν^3 ω θ (1 - ν \     ω))/(τ^2 ν^2 +                 2 δ ν τ + ω^2)^2, Italic, 30]}],            TextAlignment -> Center] // TraditionalForm},         Alignment -> Left], WindowTitle -> "An expression",        WindowSize -> {400, 300}], ImageSize -> {70, 18},       Background -> Brown, BaseStyle -> {"GenericButton", Bold}]      Second, one may use the bobknight's solution, but write the formula as a string:                  Button["Show it", CreateDocument[       Notebook[{         Cell["some explanatory text:", "Text", FontSize -> 20], Cell[""],              Cell[BoxData[           ToBoxes[Row[{TraditionalForm[               Style["Φ", 30, Italic]],               TraditionalForm[Style[" = ", 30, Italic]],               TraditionalForm[               Style["\!\(\*FractionBox[\(ϕ\\\ \*SuperscriptBox[\(\     τ\), \(2\)]\\\ \*SuperscriptBox[\(ν\), \(3\)]\\\ ω\\\ \     θ \((1 - ν\\\ ω)\)\), \     SuperscriptBox[\((\*SuperscriptBox[\(τ\), \(2\)]\\\ \     \*SuperscriptBox[\(ν\), \(2\)] + 2\\\ δ\\\ ν\\\ τ \     + \*SuperscriptBox[\(ω\), \(2\)])\), \(2\)]]\)", Italic,                 30]]}]]], TextAlignment -> Center,           ShowStringCharacters -> False]                         },             WindowTitle -> "An expression", WindowSize -> {500, 300},         ShowCellBracket -> False                   ]                                                                ],           ImageSize -> Automatic, Background -> Brown,       BaseStyle -> {"GenericButton", Bold}]      I like this solution better, since it does not interact with the definitions of the parameters.


title: DateListPlot show all the dates in ticks

text: ![enter image description here](http://i.stack.imgur.com/x79Do.jpg) The code below generates the plot above,               DateListPlot[{Drop[series[7], 1], Drop[series[16], 1]},Joined -> True,                    PlotMarkers -> {Automatic, Small}, Frame -> True,                   DateTicksFormat -> {"MonthNameShort", " ", "YearShort"} ] /.                   x : (FrameTicks -> _) :> (x /. s_String :> Rotate[s, 90 Degree])      I would like to show, on the x-axis, each and every one of the dates for which I have data. If that gets too cluttered then I would like to show a sampling of it that covers some of the staggered months. I will paste this into a pdf so tooltips won't be of use. Maybe for within year data, I can mention just the month, if it will improve readability. With non-date data, I know that I can enter ticknames and tick positions but I don't know how to do it with date data and also, I was wondering if this could be automated where I could tell it to show only the month for certain dates and month-year for others.


title: Measuring time complexity of a method

text: I use               NMinimize[someFunction, Method -> {"RandomSearch", Method ->{"InteriorPoint"},"SearchPoints" -> 2n, "RandomSeed" -> RandomInteger[{0, 100}], "PostProcess" -> {FindMinimum, Method -> "QuasiNewton"}}, MaxIterations -> 1000 n, PrecisionGoal -> 10, AccuracyGoal -> 10]`      where `someFunction` is a function of `n` variables. How could I measure the time complexity of this method?


I have a multidimensional array `A`. `Fourier[A]` finds the discrete Fourier transform over all dimensions. How to find discrete Fourier transform over a custom dimension like `fft(A,[],dim)` function in MATLAB? My current solution:               FourierDim[list_, dim_] :=       Module[{dims, ord, depth = ArrayDepth[list], tr, f},       dims = If[IntegerQ[dim], If[dim > 0, {dim}, {1 + depth + dim}], dim];       ord = Join[Complement[Range[depth], dims], dims];       tr = Transpose[list, Ordering[ord]];       f = ConstantArray[0.0 + 0.0 I, Dimensions[tr]];       With[{nn = Sequence @@ Table[Unique["n"], {depth - Length@dims}]},         With[{lim = Sequence @@ ({{nn}, Dimensions[tr][[1 ;; -1 - Length@dims]]}\[Transpose])},          Do[f[[nn]] = Fourier@tr[[nn]], lim]]];       Transpose[f, ord]       ];      It transposes the array, does Fourier transform in the loop, and transposes the array backward. Examples:               FourierDim[A,2]; (* Fourier over the second dimension *)     FourierDim[A,-1]; (* Fourier over the last dimension *)     FourierDim[A,{1,3}]; (* Fourier over the first and the third dimensions *)


title: probabiliy evaluation fails with equals condition

text: The following evaluation fails (the result is just the copy of the input) $$\text{Probability}[0<x\leq a | x-y=t,\\{x\ {ExponentialDistribution}[\lambda ],y\ {ExponentialDistribution}[\lambda ]\\}]$$ At the same time, the very exact expression evaluates correctly if I replace == with < $$\text{Probability}[0<x\leq a | x-y<t,\\{x\ {ExponentialDistribution}[\lambda ],y\ {ExponentialDistribution}[\lambda ]\\}]$$ Input:               Probability[0 < x <= a \[Conditioned] (x - y == t), {x \[Distributed]         ExponentialDistribution[\[Lambda]],        y \[Distributed] ExponentialDistribution[\[Lambda]]}]      Thank you!


title: Convoluting inverse square root with Gaussian

text: I would like to convolute the inverse square root on the interval `[0,inf]` with a Gaussian function, like so:               f[x_] := 1/Sqrt[x]     g[x_, sigma_] := Exp[-x^2/(2 sigma^2)]     conv[x_, sigma_] := Integrate[f[y] g[x - y, sigma], {y, 0, \[Infinity]}, Assumptions -> {sigma > 0}]     conv[x,sigma]      The result from Mathematica (9) reads               Exp[-x^2/(4 sigma^2)] Sqrt[-x] BesselK[1/4, x^2/(4 sigma^2)]/Sqrt[2]      which is purely imaginary for `x>0`. This is certainly not the answer to the question I had in mind, which should be a positive real-valued function for all real-valued x (correct?). Please tell me what is going wrong and (if possible) what I need to change to get the result I am looking for. P.S. Adding assumptions like `x>0` also doesn't seem to help (it simply will replace `Sqrt[-x]` by `I Sqrt[x]`).


title: Lie algebras packages (with E6, F4 & alii ... included)

text: I am looking for an add-on that deals seriously with computations inside exceptional Lie algebras (and obviously classical ones ...): I want at least all standard basic data concerning them & their representations to be included. I found some old ones but quite incomplete (no E6 or above). Do you have any recommendations or links to suggest . Thank you very much in advance.


title: Result of symbolic integration changed drastically by making assumptions

text: I would like to know the underlying reason for different outcomes for the two integration operation below. One of them includes a few assumptions, otherwise both have the same integrand:               Clear[a, b, c, d]     Integrate[(1/(a q^2 + b q Cos[θ] - c) - 1/(a q^2 + b q Cos[θ] + c)), {θ, 0, 2 π},        Assumptions -> {a, c, b} ∈ Reals]      > >     ConditionalExpression[-((2 Log[-((c - b q + a q^2)/Sqrt[-c^2 + b^2 q^2 - > 2 a c q^2 - a^2 q^4])])/ Sqrt[-c^2 + b^2 q^2 - 2 a c q^2 - a^2 q^4]) + (2 > Log[(c - b q + a q^2)/ Sqrt[-c^2 + b^2 q^2 - 2 a c q^2 - a^2 > q^4]])/Sqrt[-c^2 + b^2 q^2 - 2 a c q^2 - a^2 q^4] + (2 (-Log[-((c + q (b - a > q))/Sqrt[-c^2 + b^2 q^2 + 2 a c q^2 - a^2 q^4])] .... >                 Integrate[(1/(a q^2 + b q Cos[θ] - c) - 1/(a q^2 + b q Cos[θ] + c)), {θ, 0, 2 π}]      > >     -((2 π Sqrt[1 - (2 b q)/(-c + q (b + a q))])/( c + q (b - a q))) - >      (2 π)/((c + q (b + a q)) Sqrt[1 - (2 b q)/(c + q (b + a q))]) >


title: Plotting Laplace's equation on an infinite domain

text: I am trying to plot my solution to a Laplace equation on an infinite domain. However, when I try to plot it, _Mathematica_ just runs with nothing happening.               f[x_, y_] = Sinh[u*(5 - y)]/Sinh[u*5]*100/π*Cos[u*(ξ - x)];      DensityPlot[Integrate[f[x, y], {u, 1, 10}, {ξ, -5, 5}], {x, -5, 5}, {y, 0, 5}]      The code I have tried is above. The solution is $$ f(x, y) = \frac{100}{\pi}\int_0^{\infty}\int_{-\infty}^{\infty}\frac{\sinh(u(5-y))}{\sinh(5u)}\cos(u(\xi - x))d\xi du $$


title: How to change the variables Qi's to Ri's in one or two steps

text: I was wondering if there is a command in Mathematica to change all the following Qi's to Ri's? For example, change Q1 to R1, Q2 to R2, etc.                Q1 a1 + Q2 a2 + Q3 a3 + Q4 a4 + Q5 a5 + Q6 a6 + Q7 a7 + Q8 a8 +       Q9 a9 + Q10 a10 + Q11 a11 + Q12 a12 + Q13 a13 + Q14 a14 + Q15 a15 +       Q16 a16 + Q17 a17 + Q18 a18 + Q19 a19 + Q20 a20 + Q21 a21 + Q22 a22 +      Q23 a23 + Q24 a24 + Q25 a25 + Q26 a26 + Q27 a27 + Q28 a28 +       Q29 a29 + Q30 a30 + Q31 a31 + Q32 a32 + Q33 a33 + Q34 a34 + Q35 a35 +      Q36 a36 + Q37 a37 + Q38 a38 + Q39 a39 + Q40 a40 + Q41 a41 +       Q42 a42 + Q43 a43 + Q44 a44       I could go through and change the Qi's by hand, but I think there should be a more efficient way to do this. Thank you.


title: Mathematica + Numerical Recipes

text: the idea of combining Mathematica with the new routines in the 3rd edition of Numerical Recipes (NR) is very interesting. In fact, there is a NR library to Matlab which works very well because not only it allows one to create NR code (in C++) and install it as a function in Matlab, but it also cleverly handles the input and output of data. Does anyone know anything about this topic? I have asked the NR forum about this and received no answer. I know MathLink can be used to link C code to Mathematica, but seeing the coding level of it's Matlab counterpart, I wouldn't even dare to try and do this myself. In my view, the true power of scientific computing is in combining different libraries/platforms, efficiently exploiting their merits and deficits.


title: Flow in pipeline graph

text: I have pipeline directed graph which has one source and several sinks               getWeights = Function[{g},        res = {};        s = Flatten[{#1} & @@@ g, 1];        For[i = 1, i <= Length[s], i++,          AppendTo[res, 1/Count[Flatten[{#1} & @@@ g, 1], s[[i]]]];];        res        ];          egdes = {0 -> 1, 0 -> 2, 0 -> 3, 1 -> 4, 1 -> 5, 1 -> 6, 3 -> 6,        3 -> 7 , 2 -> 5, 2 -> 6, 4 -> 8, 5 -> 8, 5 -> 9, 6 -> 9, 7 -> 9,       5 -> 10, 7 -> 10};     wghts = getWeights[egdes]     Graph[egdes, EdgeWeight -> wghts,       VertexLabels -> Placed["Name", Center], VertexSize -> Medium,       EdgeLabels -> Table[egdes[[i]] -> wghts[[i]], {i, Length[egdes]}]]     sinks = Complement[DeleteDuplicates[Flatten[{#2} & @@@ egdes, 1]],        DeleteDuplicates[Flatten[{#1} & @@@ egdes, 1]]]     sources= Complement[DeleteDuplicates[Flatten[{#1} & @@@ egdes, 1]],        DeleteDuplicates[Flatten[{#2} & @@@ egdes, 1]]]      ![enter image description here](http://i.stack.imgur.com/iHSLa.png) Now I would like to calculate the the flow in sinks assuming the flow at source is equal to 1. I did it by finding all paths from source to sink and then summing the products of all edges weight in the path for all paths. My code is rather ugly and slow for large graphs so I do not put it here. I hope that someone could help me to find more elegant and fast decision. For the case in the figure there are three sinks {5,6,7} I found flows {3/8,1/4,3/8}


title: Any way to prevent Mac firewall from asking to allow connections all the time?

text: Whenever I start Mathematica 8 on my Mac the built-in Mac OS firewall asks if I want to allow JLink to accept incoming connections. Then, during running, I'll get the same question about Mathematica.app. Sometimes the requests occur several times during the day, though not always. It's a minor irritation but it'd be nice to know if there is a way to avoid it while keeping the firewall switched on. I already have the Mac firewall configured to allow connections permanently for Mathematica.app and JLink. Thanks


title: Random Matrix with integer coefficients and inverse also having integer coefficients

text: I'm trying to build a function that gives me matrices such that each:   1. Has integer coefficients.   2. Is non singular.   3. Has inverse which also has integer coefficients. I have some code that one of my teachers gave me, but it is code written in Derive. I have reproduced the code, but I'm not getting what a really need. The code for Derive requires a function that takes a column, multiplies it by a constant and adds it to another one, lest call this function `ColSum[M, i, j, α]`, which takes the i-th column multiplied by α and adds it to the j-th column. The code for the matrix in Derive is:               Matrix(n) ≔        \prod_{h=1}^{n-1}  \prod_{k=h+1}^{n} ColSum(IDENTITYMATRIX(n), h, k, (1 + RANDOM(2))·(-1)^h)*       \prod_{k=1}^{n-1}  \prod_{h=k+1}^{n} ColSum(IDENTITYMATRIX(n), k, h, (1 + RANDOM(2))·(-1)^k)*       VECTOR(VECTOR(IF(i_ < j_, 0, IF(i_ = j_, (-1), RANDOM(2) + 1)), i_, 1, n_), j_, 1, n_)       I think the problem is either in the `ColSum` function because it is where I've seen that things go wrong, or in the fact that `Product` does not perform an iterated `Dot`. I want to translate this function into _Mathematica_. My code so far is:               RowSum[v_,i_,j_,a_] := Table[If[m ==i , Part[v,i] + a*Part[v,j],Part[v,m]],{m,Dimensions[v][[1]]}]          ColSum[v_,i_,j_,a_]:=Transpose[RowSum[Transpose[v],i,j,a]]]               Matrix[n_] := Product[ColSum[IdentityMatrix[n], h, k, (1 + RandomInteger[2])*(-1)^h ], {h,1, n - 1}, {k, h + 1,n}].Product[ColSum[IdentityMatrix[n], k, h, (1 + RandomInteger[2])*(-1)^k ], {k, 1, n - 1}, {h, k + 1, n}].Table[Table[If[i < j, 0, If[i == j, (-1)^i,RandomInteger[2] + 1]], {i, n}], {j, n}]      I think the problem is either in the `ColSum` function because it is where I've seen that things go wrong, or in the fact that `Product` does not perform an iterated `Dot`. Thanks for helping.


title: Visualizing nested lists for easier human understanding

text: When interacting with Mathematica, I often find myself staring blankly at waves of curly braces, trying to understand how data is organized hierarchically. For example, the beginning of the result to               WolframAlpha["temperature in Toronto yesterday", "DataRules"]      looks like this: ![Waves of curly braces](http://i.stack.imgur.com/3Trq8.png) To visualize the hierarchy, I typically turn to TreeForm, but that's often unwieldy. There's no way to collapse parts of the tree you don't care about (as there would be in, say, a file system browser), so the visualization frequently spreads well off screen or is illegibly small. For example,               TreeForm[WolframAlpha["temperature in Toronto yesterday", "DataRules"]]      produces: ![TreeForm of a WolframAlpha query](http://i.stack.imgur.com/TmeJ4.png) Is there a better way?


title: Factoring a differential equation into an operator product

text: Following the fundamental theorem of algebra, I can (as stated here in Sec. 1.1.4) factor an $n$th-order linear ordinary differential equation $$ a_n \frac{d^n x}{dt^n} + a_{n-1} \frac{d^{n-1} x}{dt^{n-1}} +\cdots+a_1 \frac{dx}{dt}+a_0 = 0 $$ into $$ a_n \left( \frac{d}{dt} - r_1 \right) \left( \frac{d}{dt} - r_2 \right) \cdots \left( \frac{d}{dt} - r_n \right) x = 0 . $$ The Mathematica representation of the former is trivial, and I would represent the latter as               difOp[t, r] = (Dt[#, {t}] - r) &     an difOp[t, r1][ difOp[t, r2][x[t]] ] == 0      Is there any way to get the Mathematica kernel to connect the two, e.g. to compute the second from the first?


title: Harmonious graph labeling

text: Is it possible to harmoniously label a graph in _Mathematica_? I would like a function, that when given a graph, would return a harmonious labeling. If not, is there other software that can do it? A _Mathematica_ program that can do it for me would be great. Maybe use heruistics to do it. Consider all labelings and find one/several harmonious labelings? I dont think I have the programming chops to do it myself.


title: Finding simpler implied formulas while preserving contradiction

text: I have two Presburger formulas A and B such that A∧B≡False. From these I need to find "simpler" formula A′ (as simple as I can make it) such that A→A′ and A′∧B≡False. Is there any simple way to automate this for largish formulas in Mathematica? The formulas start off in sum of products form, with thousands of products and less than 20 variables. I'm already using FullSimplify to simplify A and B preserving equivalence, but I need to go even simpler, hence this weaker set of conditions.


title: Group list of lists by Total

text: I have some list which looks like               {{0,1},{4},{0,0,1},{2,0,1},{3,0,0},{3,1},{0,0,0,4}}      and I need to group lists with equal sum of elements in ascending order like               {{{0,1},{0,0,1}},{{2,0,1},{3,0,0}},{{4},{3,1},{0,0,0,4}}}      and for               {{0, 0, 0, 0, 0}, {1, 1, 0, 0, 0}, {1, 1, 1, 1, 0}, {1, 1, 0, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 1, 1, 0}, {0, 0, 0, 1, 1}}      I expected to see               {{{0, 0, 0, 0, 0}}, {{1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 1, 1, 0}, {0, 0, 0, 1, 1}}, {{1, 1, 1, 1, 0}, {1, 1, 0, 1, 1}, {0, 1, 1, 1, 1}}}


title: Histogram For Non-Numerical Data

text: I have a non-numerical data, let say               data = Table[RandomChoice[{0.2, 0.3, 0.25, 0.15, 0.1} -> {"A", "B", "C", "D", "E"}], {500}];      and i want to make a histogram for this data. My solution so far               datanew = data;     label = Sort@DeleteDuplicates[data];     Do[datanew = ReplaceAll[datanew, label[[i]] -> i], {i, 1, Length[label]}]     Histogram[datanew, Ticks -> {None, Automatic}, ChartLabels -> {None, Placed[label, Below]}]      Is there any better way to do this? Thank you.


title: Generating and plotting hypocycloids

text: Hypocycloids are curves generated by following a fixed point on a smaller circle rolling around the inside of a larger circle. The following code is from the recent book of P. Wellin (with modified `PlotRange` by myself).               HypocycloidPlot[R_, r_, θ_] :=       Module[{Hypocycloid, center},        Hypocycloid[{a_, b_},          t_] := {(a - b) Cos[t] + b Cos[t (a - b)/b], (a - b) Sin[t] -           b Sin[t (a - b)/b]};        center[{a_, b_}, t_] := (a - b) {Cos[t], Sin[t]};        Show[{ParametricPlot[Hypocycloid[{R, r}, t], {t, 0, θ},           Axes -> None, PlotStyle -> Red],          Graphics[{{Blue, Thick, Circle[{0, 0}, R]},            Circle[center[{R, r}, θ]], {Thick,             Line[{center[{R, r}, θ], Hypocycloid[{R, r}, θ]}]}, {Orange,             PointSize[0.02], Point[center[{R, r}, θ]]}, {Red,             PointSize[0.03], Point[Hypocycloid[{R, r}, θ]]}}]},         PlotRange -> 1.5 (R + r), GridLines -> Automatic]]      For instance,               Table[HypocycloidPlot[R, 1,         θ], {R, {3, 7/2, Sqrt[7/2]}}, {θ, {Pi/3, 3 Pi/2, 2 Pi,          3 Pi}}] // TableForm      produces the following ![enter image description here](http://i.stack.imgur.com/MrnpI.jpg) (It can be verified that the curve only "closes up" when the ratio R/r is an integer or a rational number.) My first question. If we set `R = 3` and `r = 2`, for example, the inner circle loses the contact with the outer circle. (The author does not pose any restricition to r.) I think the problem arises due to the fixed center of the outer circle               Circle[{0, 0}, R]      Am I correct or am I missing something? And if I am indeed correct, how should the code be modified in order to circumvent the issue? My second question. Suppose that I have the following               Manipulate[      HypocycloidPlot[R, r, θ], {θ, 0.01,        2 π Denominator[(R - r)/r]}, {R, {3, 4, 5, 6, 7, 8, 5/3, 7/2},        Setter}, {r, Range[5], Setter}]      How can I make videos like the following one? http://en.wikipedia.org/wiki/Hypocycloid **Update** The thread is relating to Plotting an epicycloid There my second answer about animation is answered. So, it remains only the first one.


title: Any ideas on how to use the Region` context?

text: If you type               ?Region`*      you'll get: ![Mathematica graphics](http://i.stack.imgur.com/5a67H.png) which seems a bunch of interesting and not documented symbols. Any idea (or experience) on how to use them? **Edit** By using our "collective spelunking" **I was able to work outthis answer** \- Great! :) And Silvia used it to write another one!


title: How to enter and solve this equation in finite fields?

text: Is there a way in Mathematica 9 to enter and solve the following equation $p(x) = r^x$ where $p(x)$ is a polynomial whose coefficients are drawn from a finite field, and $r$ is a primitive root of the field modulus ? EDIT As an example, how to solve $x^3 + x^5 == 3^x$ mod 7


title: InterplationOrder, ListPlot3D and using AbsoluteOption to find value used. Slow using InterpolationOrder

text: What lead to this, is when I noticed that `ListPlot3D` was much slower when adding a specific `InterpolationOrder->n` vs. not and letting the default take care of it. To find out why it is so much slower (timing is below), I asked Mathematica to tell me what default `InterpolationOrder` it used for the current plot. So I used the command                     AbsoluteOptions[p, InterpolationOrder]      To do that, which supposed to return the value used in p. From the excellent book `Mathematica Navigator`: ![Mathematica graphics](http://i.stack.imgur.com/pAfvp.png) But Mathematica gave an error and said that `InterpolationOrder is not a known option for` this plot. But http://reference.wolfram.com/language/ref/ListPlot3D.html shows it there. ![Mathematica graphics](http://i.stack.imgur.com/2ed8a.png) So my question is, how does one find what `InterpolationOrder` is used for current plot of `ListPlot3D`? My sub question is actually (the reason why I wanted to find the above), is why ListPlot3D slows down so much when specifying this option vs. not? Here is the MWE               Clear[x, y, z];     nElem = 10; h = 1/(nElem - 1);     grid = N@Table[{i*h, j*h}, {i, -10, 10, h}, {j, -10, 10, h}];     f[x_, y_] := Sin[x*10 y] Exp[-x y];     force = Map[f[#[[1]], #[[2]]] &, grid, {2}];     p = ListPlot3D[force, InterpolationOrder -> 1, AxesLabel -> {x, y, z}]      ![Mathematica graphics](http://i.stack.imgur.com/tYbdD.png)                AbsoluteOptions[p, InterpolationOrder]      (*error*)           Timing[ListPlot3D[force, InterpolationOrder -> 1, AxesLabel -> {x, y, z}]]        (*5.647236*)           Timing[ListPlot3D[force, AxesLabel -> {x, y, z}]]          (* 0.624004 *)      And as an extra reward, if you can answer how can one use `InterpolationOrder -> 1` and still have fast plot, I will up-vote you 2 times if I can. Version 10.0 on windows 7.


title: Select elements of a Matrix that are the same (or have certain relationship) and return their position and the element itself

text: I have a matrix and I want to pick the elements that are the same and return their positions and their values. It seems easy to me, but all I know is how to pick elements that satisfy certain conditions, but not in relation to other elements.


title: BindEvent binding own function

text: I need to change property of window when button gets pressed. There are pretty enough examples on Wolfram's website, but all they bind predefined function "Print[]" and I have no problems with binding Print function. But I can't bind something different. I need call my own function and methods of Widgets.      This is a window whose property I want to change:               widget4 = Widget["TextPanel", {     "preferredSize" ->      Widget["Dimension", {"width" -> 800, "height" -> 660}],     "contentType" -> "text/html",     "editable" -> False, "path" -> html1path}, Name -> "MainOutput"]            functio[]:=(Print["fffff"]);      This is my button:               html2path="some text which I want to change";     butto = Widget["Button", {     "Text" -> "Update",     BindEvent["Action",     Script[    {SetPropertyValue[{"MainOutput", "path"}, html2path] ,        Print["fdfdf"], ref@InvokeMethod[{"Frame", "getX"}], functio[] } ]]     }]      I launch it all together so:               ref = GUIRun[ Widget["Frame", {widget4, butto}, Name -> "Frame" ]];      As result out of all my tries only function Print["fdfdf"] was called. ![enter image description here](http://i.stack.imgur.com/9psJb.png) I got stuck with it.   Thanks in advance.


title: Gram Schmidt inner and outer products

text: I know the Gram-Schmidt orthogonalization generates an orthonormal basis from an arbitrary basis. I need help with: > **Write a program that inputs a list $\\{b_1,\dotsc,b_n\\}$ of linearly > independent vectors and an inner proudct and outputs a list of orthonormal > vectors $\\{e_1,\dotsc,e_n\\}$ with the same span.**                           innerproduct1[f_,g_]:=Sum[(f/.t->i)(g/.t->i), {i,1,4}]                      gramschmidt2[innerproduct1_,list2_]:=                   Module[{k,u,v,e},                    k=Length[list2];                    Do[Subscript[v,i]=list2[[i]],{i,1,k}];                    Do[Subscript[u,i]=                      Subscript[v,i]-                       Sum[(innerproduct1[Subscript[v,i],Subscript[u,j]]/                           innerproduct1[Subscript[u,j], Subscript[u,j]]*Subscript[u,j],  {j,1 ,i-1}];                   Subscript[e,i]=                    Subscript[u,i]/Sqrt[innerproduct1[Subscript[u,i].Subscript[u,i]]],{i, 1,k}];                 Table[Subscript[e,i],{i,1,k}]                 ]      Sorry if the program is wrong. I might be going ahead of what I read which I probably am. I just learned somethings about the Gram-Schmidt process from reading an analysis text a couple days ago. I saw this question online and thought I would try to solve it with what I read. I came to some frustration and really wanted to know how to write a _Mathematica_ program for this.


title: How to obtain a Symplectic 4×4 matrix?

text: I have a problem in obtaining a $2n \times 2n$ Symplectic matrix $T$, with $n=2$. I couldn't find a direct command in _Mathematica_ to achieve this. Conditions:               Transpose[T].HH.T={{v1,0,0,0},{0,v2,0,0},{0,0,v1,0},{0,0,0,v2}     Transpose[T].JJ.T = JJ      where:               JJ={{0, 0, 1, 0}, {0, 0, 0, 1}, {-1, 0, 0, 0}, {0, -1, 0, 0}};     T={{T11,T12,T13,T14},{T21,T22,T23,T24},{T31,T32,T33,T34},{T41,T42,T43,T44}};     HH={{HH11,HH12,HH13,HH14},{HH21,HH22,HH23,HH24},{HH31,HH32,HH33,HH34},{HH41,HH42,HH43,HH44}};


title: Error while transponsing a tensor

text: I am trying to execute following:               TensorTranspose[Outer[D, metric, x], {2, 3}].       And _Mathematica_ says me > >     TensorTranspose::symmperm: "Invalid permutation or symmetry generator > {2,3}. >   While for permutation `{1,2}` there would not be an error. metric has dimentions `{5,5}`, `x` has `{5}`. Could anyone tell what is wrong with `{2,3}`?


title: How to get the boolean value of an inequality involving an InterpolatingFunction?

text: Here's the code:               yan = FunctionInterpolation[x^2, {x, -1, 1}];     FullSimplify[yan[x] > -1, -1 < x < 1]      Needless to say, what I expect to see in the output is "True", but `FullSimplify` doesn't seem to work. What function should I turn to? * * * @J.M. @belisarius @acl 囧…A very simple solution suddenly struck me, it is:               yan = FunctionInterpolation[x^2, {x, -1, 1}];     MinValue[{yan[x], -1 < x < 1},x]>-1


title: Strange NSum behavior for slightly larger number of terms

text: For some sums, NSum gives me the result nicely for some number of terms, but if I add one more term, it suddenly becomes much slower. I haven't found the minimum example for which this can be reproduced, but here is a problem I was just trying to compute:               NSum[Sin[x0*n*Pi]*Sin[d*n*Pi/2]*Exp[(n*Pi)^2 *t]*(2 - Cos[n*Pi] -      2*BesselJ[1, n*Pi/2]*Sin[n*Pi/2]), {n, 1, 24}]      Here t=-0.3, d=0.1 and x0=0.5. For 24 terms, this evaluates just fine (and gives me 0.015118), but for 25 terms, the calculation takes much longer. It seems to me that adding just one more term to the sum should not take much longer than the original calculation. What is going on here? I'm using Mathematica version 9.0.1.0.


title: Looking for mismatches between two lists

text: I'm able to do what I need, but it seems like there's always a better way. I have two lists, epiExcel and epiDB. Each has 3 columns and about 2,500 rows. I need to find out if the first 2 columns of each match, and when they don't where the mismatches are. I did the following:               z = Position[epiDB[[All, {1, 2}]], #] & /@ epiExcel[[All, {1, 2}]];     Position[z, {}]     z = Position[epiExcel[[All, {1, 2}]], #] & /@ epiDB[[All, {1, 2}]];     Position[z, {}]      This worked for the specific case I have at the moment. Is there a better way to do this?


title: Asking for input in an event handler

text: Why won't               EventHandler["text", {"MouseClicked" :> (output = Input[];)}]      work? When I click "text" the kernel hangs.


title: Why doesn't Mathematica pack Boolean arrays?

text: I've been wondering about this for a while now, so I'm going to ask. This is a question about the design of _Mathematica_ , which perhaps cannot be directly answered by anyone but the designers, however similar queries have been fruitful in the past. Simply: why aren't arrays of `True` and `False` values packed? `Compile` handles `True | False` so it seems _Mathematica_ has some understanding of optimizing for this type, yet:               boolean = Developer`ToPackedArray @ RandomChoice[{True, False}, 1*^6];          Developer`PackedArrayQ @ boolean      > False This is rather frustrating because packing would be particularly effective on binary data:               bigint = FromDigits[Boole@boolean, 2];          ByteCount[boolean]          ByteCount[bigint]      > 8000032 > > 125040 Yes, one can sometimes fall back to this storage format and use `Bit*` operations, but that is inconvenient and it doesn't always help; data must be converted for functions that expect `True` or `False` and the opportunity for internal optimizations may be lost. **Is there some reason I fail to comprehend that makes implementing packing of Boolean arrays a bad idea?**


title: Running Mathematica via JLink from a Servlet on Tomcat 7 Problem

text: I'm trying to make a java servlet running on Tomcat 7 for specilized mathematical calculations. So I want to link Wolfram Mathematica 8.0 mathkernel from my servlet via JLink (webMathmatica is not an option). I placed JLink.jar and JLinkNativeLibrary.dll into WebContent/WEB-INF/lib directory and wrote the following code:               String[] mlArgs = {"-linkmode", "launch", "-linkname", "\"path-to-mathkernel.exe\""};     mathKernelLink = MathLinkFactory.createKernelLink(mlArgs);      But, when I launch my servlet on Tomcat, it shows dilog box with title "Choose a MathLink programm to launch". If I choose mathkernel.exe from the Mathematica folder, further calculations run fine. I think that "path-to- mathkernel.exe" is incorrect to automaticaly run mathkernel.exe. I tried to use a global path c:\program files\wolfram research\mathematica\8.0\mathkernel.exe, but i didn't succeed. Witch path should I use? Or should I configure Tomcat to run external applications? Thanks.


title: Mathematica for Computer Scientists

text: ## Background I've coded in C/Scheme for 10 years. I have a BS CS. I've recently become very interested in pattern-matching (lisp's match macro), and term rewriting systems, which brought me to Mathematica. I would like to read a book on Mathematica that will show me lots of cool term-rewriting as a programming style techniques. ## Question: What should I read?


title: Using MapIndexed only at certain elements of a list

text: `MapIndexed` is a very handy built-in function. Suppose that I have the following list, called `list`:               list = {10, 20, 30, 40};      I can use `MapIndexed` to map an arbitrary function `f` across `list`:               {f[10, {1}], f[20, {2}], f[30, {3}], f[40, {4}]}      where the second argument to `f` is the part specification of each element of the list. But, now, what if I would like to use `MapIndexed` only at certain elements? Suppose, for example, that I want to apply `MapIndexed` to only the second and third elements of `list`, obtaining the following:               {10, f[20, {2}], f[30, {3}], 40}      Unfortunately, there is no built-in "`MapAtIndexed`", as far as I can tell. What is a simple way to accomplish this? Thanks for your time.


title: Is SynchronousUpdating->False supposed to make this simple Dynamic example work?

text: x = 0; Dynamic[{x, Button["+1", Pause[6]; x++]}, SynchronousUpdating -> False]      The documentation states that Dynamic and Manipulate will abort synchronous computations that take longer than 5 seconds. The stated solution to this is to set SynchronousUpdating to False. That does not seem to work here. If I pause for 5 or fewer seconds it always works, but if I pause for 6 or more seconds, x always stays at 0 no matter the setting for SynchronousUpdating.


title: how to find iso-cost contours on a 2d plot efficiently

text: Consider a 2D plot in which dimension 1 and 2 represent quantity 1 and 2 respectively ranging over 0 to 100. Each point in the space corresponding to (x,y) represent cost of choosing quantity 1 as x and quantity 2 as y. Assume cost increases monotonically with increase in quantities. I want to find iso- cost lines(contours) in the space. Say all those points whose cost is equal to some K. How do I find it efficiently without checking cost of all the points in the space which is 100 cross 100.?


title: Strange result from evaluating a Limit expression

text: When I evaluate the limit of `(1-Cos[x]) Sin[1/x]` at `x = 0` in _Mathematica_ 9, I obtained `Interval[{-2, 2}]`. The problem is that this limit is 0. It is also 0 when I compute it by Maple and _Mathematica_ 7\. So, I wonder whether I've found a bug in _Mathematica_ 9?               Limit[(1 - Cos[x]) Sin[1/x], x -> 0]      > >     Interval[{2, 2}] >


title: Change size of a saved plot or image (post-processing)

text: I have many plots (that take a long time to run) and each is saved to a variable name. For simplicity, say one was:               m = Plot[Sin[x], {x, -1, 1}, ImageSize -> 600]        If I call for the plot               m        it will be presented as it should be, with ImageSize 600. I can click and drag the corners to change the size of the plot (instantaneously, so I know mathematica is not re-computing the plot, but simply adjusting the output image size continuously). Therefore, what I wish to accomplish must be possible to do, but I don't know how to instruct mathematica to do it. What I want is a command, something similar to, say               m/.ImageSize->200        etc. that can present m with a new, prescribed size, rather than manually sliding it to a new size, and certainly without having to re-compute the code that produced the saved plot. Help?


title: Area of the largest rectangle bounded by $y=x^2$ and the x-axis within the unit interval

text: I am trying to find the area of the largest rectangle (whose sides are parallel to the coordinate axes) contained in the region bounded by the graphs of $y = 0, y = x^2,$ and $x = 1$ using _Mathematica_. I am not sure where to begin other than that the area of a rectangle is $l w$. Any ideas?


title: Centrality measures and normalisation

text: Are centrality measures normalised in _Mathematica 9_? Only `ClosenessCentrality` is normalised. How I can normalise other centrality measures notably `DegreeCentrality` and `BetweennessCentrality`?               g = GridGraph[{5, 5}];     ClosenessCentrality[g] // Short     BetweennessCentrality[g] // Short     DegreeCentrality[g] // Short      > > {0.24,0.282353,0.3,0.282353,0.24,0.282353<14>>,0.24,0.282353,0.3,0.282353,0.24} > {2.6881,17.2071,21.5429,17.2071,<<18>>,21.5429,17.2071,2.6881} > {2,3,3,3,2,3,4,4,4,3,3,4,4,4,3,3,4,4,4,3,2,3,3,3,2}


title: Plotting multiple parametric functions with different intervals

text: I want to make a parametric plot like this:               ParametricPlot[{{2 t, -10 t^2}, {t, 2 t}}, {t, 0, 2}]      I have tried the following but it doesn't work:               ParametricPlot[{{2 t, -10 t^2}, {t, 2 t}}, {{t, 0, 2}, {t, 4, 7}}]


title: How to define a matrix with all elements 0?

text: A matrix can be defined as               M = Array[m, {3, 3}]      which gives               {{m[1, 1], m[1, 2], m[1, 3]}, {m[2, 1], m[2, 2], m[2, 3]}, {m[3, 1], m[3, 2], m[3, 3]}}      How to give all `m[i, j]` the value `0` (if `M` is a `NxN` matrix)?


title: Can I make V9 prompt witb "In[1]:=" before I enter an expression?

text: Using an older version of _Mathematica_ , I was used to the system automatically beginning each notebook line with `In[1]:=`. All I did was enter the expression and press enter on the keyboard to evaluate the expression. Now however, using the default _Mathematica_ Input (v.9), there is no initial `In[1]:=`. I enter the expression and press enter, and then the `In[1]:=` appears, followed by the value of the expression or the symbolic output. I would prefer to have each new line begin with a numbered `In[]:=`, I would like to know if it is possible to get back the old behavior that I was familiar with? If so, what preferences do I need to set?


title: Stop use of scientific notation when displaying FrameTicks

text: I have a dynamic graph which changes depending on the current selection from a drop down box. All selections from the drop down box give fine results except one. For the one selection it shows the `y` axis in scientific notation. I understand that this is due to the values being large but I don't want this to happen. I also can't specify the `y` axis values manually, I need to use the `FrameTicks->Automatic` functionality. Is there any way to stop the y-axis ticks from displaying in scientific notation? ![enter image description here](http://i.stack.imgur.com/rUbhw.jpg)


title: Compile: Putting integers into a list

text: The first part below is already answered, but I've got another question which I think is closely related to this one, so I edited my question. **First part:** I started compiling in Mathematica a few weeks ago. In the code below, I want to put the integer value 0 into the list "Pre". If I "Print" the list, it will look like {0,0,....,0}. But the output of the code is {0.,0.,0.,....,0.}. So, my question is, how can I manage it, that the output looks like the "Print", i.e. I want the list to have integer values and not real numbers.               In[1]:= CInit = Compile[{{v0, _Integer, 0}, {s0, _Integer, 0}},               Module[{s = s0, v = v0, d, Pre},               d = Table[$MaxMachineNumber, {v}];               Pre = Table[0, {v}];               Print[Pre];               d[[s]] = 0.;               {d, Pre}               ], CompilationTarget -> "C"];             CInit[5, 1]           During evaluation of In[1]:= {0,0,0,0,0}           Out[2]= {{0., 1.79769*10^308, 1.79769*10^308, 1.79769*10^308,               1.79769*10^308}, {0., 0., 0., 0., 0.}}      **Second part:** If I have an empty list and I want to put Integers into it, how can I let Mathematica know that it is a list of Integers and not Reals? I tried to manage this with the third argument in Compile, but that didn't work. For example:               In[22]:= CTest = Compile[{{s, _Integer}}, Module[{Perm = {s}},              Perm = {};              Append[Perm, 1]              ], {{Perm, _Integer, 1}}, CompilationTarget -> "C"]      > Compile::cset: Variable Perm of type {_Integer,1} encountered in assignment > of type >{_Real,1}. >> > > Compile::cset: Variable Perm of type {_Integer,1} encountered in assignment > of type >{_Real,1}. >> I can avoid this error by doing this rather unnecessary thing below:               In[25]:= CTest = Compile[{{s, _Integer}}, Module[{Perm = {s}},              Perm = Delete[Perm, 1];              Append[Perm, 1]              ], CompilationTarget -> "C"]      So, is there another way to tell Mathematica that Perm is a list of Integers without doing it like in the last example? Thanks in advance!


title: Solve a PDE on a domain $\Omega$ with given boundary conditions

text: I'm starting to study the behavior of some PDEs and I would like to run simulations in mathematica to help me visualize solutions. For example, a prime example that I would like to study is $$ \left\\{ \begin{array}{cc} -\Delta\phi + u\cdot\nabla\phi=1 & \text{in }\Omega\\\ \phi=0& \text{on }\partial\Omega \end{array}\right. $$ for a fixed (smooth enough) $u$ which is divergence free and flows tangentially to the boundary. For one dimensional problems, inputting boundary conditions is easy since there are typically only two bounary points at most. But I would like to study this PDE (in 2-d) with a variety of different $\Omega$'s. I can't find anything in the mathematica documentation about how to input arbitrary boundary conditions. To make things simpler, I will restrict myself to reasonably nice $\Omega$'s which have nice boundaries. Suppose that $\partial\Omega$ is given implicitly by $F(x,y)=0$, e.g. $x^2+y^2-1=0$. What would be the easiest/best/most efficient way to input the boundary condition $\phi(x,y)=0$ when $F(x,y)=0$? Edit: Feel free to use any reasonable discretization technique, or to assume that you have a function like `isInRegion[x,y]` if you need it.


title: Mathlink and Fortan: A list with more than 10 elements as result

text: I have a problem with Mathlink (Mathematica 9.0), form which I call a Fortran subroutine which should return a list of 13 numbers. I have written a C-wrapper to call the Fortran subroutine (called "hubclus") from C. The main part of this wrapper looks as follows:               void hubclusML P((int, int, int, double, double, double, int));          :Begin:     :Function:       hubclusML     :Pattern:        HubClus[ Nx_Integer, Ny_Integer, Ne_Integer, U_Real, t_Real, Temp_Real, fulldiag_Integer  ]     :Arguments:      { Nx, Ny, Ne , U, t, Temp, fulldiag }     :ArgumentTypes:  { Integer, Integer, Integer, Real, Real, Real, Integer }     :ReturnType:     Manual     :End:          #include "mathlink.h"     extern void hubclusML( int Nx, int Ny, int Ne, double U, double t, double Temp, int fulldiag );               void hubclusML( int Nx, int Ny, int Ne, double U, double t, double Temp, int fulldiag )     {            double results[12];            /* Call hubclus */       hubclus_(&Nx, &Ny, &Ne, &U, &t, &Temp, &fulldiag, &results);            /* Send the Results to Mathematica via MathLink */       MLPutReal64List(stdlink, results, 13);            return;     }      This wrapper calls the Fortran subroutine "hubclus" which in turn calculates a list with 13 elements as result and should pass it via Mathlink back to Mathematica. **Now here is the problem:** It always worked well as long as the list "results" contains not more than 10 elements. But if the list "results" contains more than 10 elements the Link to this function dies after the execution in Mathematica without giving any error message except "$Failed". I would be thankful for any help.


title: Save selection as PDF - non-image format

text: I am trying to save the following plot as a pdf, so that I can import it into LaTeX:               Grid[{{RegionPlot[{x<y,x>y},{x,-2-1/10,2+1/10},{y,-1/10,3+1/10},PlotPoints->20,PlotStyle->{Texture[Graphics[Table[Circle[{i,j},1/4],{i,20},{j,20}]]],Texture[Graphics[Table[Polygon[{{1+i,0+j},{0+i,Sqrt[3]+j},{-1+i,0+j}}],{i,2,80,4},{j,2,80,4}]]]},BoundaryStyle->Black,PlotRange->{{-2,2},{0,3}},ImageSize->350],Grid[{{Graphics[Table[Circle[{i,j},1/4],{i,3},{j,3}],ImageSize->30,Frame->True,FrameTicks->None],"(Min, Min) & (Mix, Max)"},{Graphics[Table[Polygon[{{1+i,0+j},{0+i,Sqrt[3]+j},{-1+i,0+j}}],{i,2,10,4},{j,2,10,4}],ImageSize->30,Frame->True,FrameTicks->None],"(Mix, Max)"}},Spacings->{1,1/2}]}},Spacings->{2,1}]      However, if I right-click on the output and click 'save selection as', the pdf I get changes the `RegionPlot` into a image (probably jpeg). However, it does manage to keep the `Graphics`, to the right of the `RegionPlot`, as a non- image pdf code. I believe this is due to the function `Texture`, which turns the `Graphics` inside `Texture` into an image. How can I get the full output into non-image pdf code?


title: Evaluation indicator for a notebook

text: I have a GUI with a number of `TabView` and other `Manipulate` controls. Sometimes clicking from one tab view to the other can take a while, and I would like to have a global "Please wait" indicator. So one way is to implement it for each button or slider, but I would essentially like to have a visual indicator that will show if any cell in my notebook is being evaluated. Any ideas or suggestions? (Have searched for answers here but I only found those related to progress bars for a specific calculation)


title: Determining which rule NIntegrate selects automatically

text: I need to numerically integrate a highly oscillatory function over the semi- infinite domain $(0,\infty)$: $$\int_0^\infty \frac{\sin^2(x) \sin^2(1000 x)}{x^{5/2}}\mathrm dx$$ Since the Levin rule (which was recently added to _Mathematica_ , starting in version 8) was developed specifically for oscillatory integrals such as this, I thought I'd try it:               ans = NIntegrate[Sin[x]^2 Sin[1000 x]^2/x^(5/2), {x, 0, Infinity},                       Method -> {"LevinRule"}, PrecisionGoal -> 8, MaxRecursion -> 30]      Using an exact solution for this integral, I can confirm the relative accuracy of the _Mathematica_ result is $1 \times 10^{-11}$, and moreover the calculation is very quick. At first, this led me to believe that Levin's method works great for this problem, but... It turns out that _Mathematica_ must be automatically switching to non- oscillatory rule behind the scenes, because forcing it not to do so gives a very poor result:               ans = NIntegrate[Sin[x]^2 Sin[1000 x]^2/x^(5/2), {x, 0, Infinity},                        Method -> {"LevinRule", "MethodSwitching" -> False},                      PrecisionGoal -> 8, MaxRecursion -> 30]      > NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after > 30 recursive bisections in x near {x} = {0.}. NIntegrate obtained -3497.5 > and 3510.0321785369356` for the integral and error estimates. >> Is there any way to find out which alternative non-oscillatory rule _Mathematica_ is automatically selecting? I've tried to guess which rule is being used by manually specifying few rules but the results I've obtained with other rules are inaccurate, slow, or both:               ans = NIntegrate[(Sin[x])^2 (Sin[1000 x])^2/x^(5/2), {x, 0, Infinity},                       Method -> "ClenshawCurtisRule", AccuracyGoal -> 8, MaxRecursion -> 30]      > NIntegrate::slwcon: Numerical integration converging too slowly; suspect one > of the following: singularity, value of the integration is 0, highly > oscillatory integrand, or WorkingPrecision too small. >> > > NIntegrate::eincr: The global error of the strategy GlobalAdaptive has > increased more than 400 times. The global error is expected to decrease > monotonically after a number of integrand evaluations. Suspect one of the > following: the working precision is insufficient for the specified precision > goal; the integrand is highly oscillatory or it is not a (piecewise) smooth > function; or the true value of the integral is 0. Increasing the value of > the GlobalAdaptive option MaxErrorIncreases might lead to a convergent > numerical integration. NIntegrate obtained 0.000013202052151832003` and > 1.0480362255168103`*^-6 for the integral and error estimates. >> I'd like to know what rule _Mathematica_ is using so that I can try adjusting options for the best performance possible. I need to calculate this integral several hundred thousand times, as the innermost integral of a nested double integration. Furthermore, when it comes to publishing my results, I would like to be able to state the integration strategy that was actually used, rather than " _Mathematica_ knew how to handle it".


title: Mathematica 9 link in OriginLab

text: Hi (I am an absolute newbie), I need to send Mathematica data to the program OriginLab to plot and change the graphs. Does anyone know if it is possible to send data from Mathematica 9 via Mathematica link to OriginLab? I have tried, but it was only possible to send data from OriginLab to the Kernel and use the programming power of Mathematica 9 to receive the results back in OriginLab.


title: How to initialize several elements per iteration with Table?

text: I would like to initialize this kind of vector : `{0,0,1,1,0,1,0,1,1,1,1,1}` with `Table`.   I tried `Table[{x, y, 1}, {y, 0, 1, 1}, {x, 0, 1, 1}]` but it outputs `{{0,0,1},{1,0,1},{0,1,1},{1,1,1}}`.   What is the right method to correctly initialize my vector without creating sub-lists ?


title: Most efficient way to sum over matrix products?

text: I have two lists. The first, `coefficientlist`, is dense and has dimension `{176,176}` elements. The second, `cubelist`, is a list of three-dimensional lists, i.e. `cubelist` has dimension `{176,65,65,65}`. I need to perform the following summation:                   sumlist=Table[0,{65},{65},{65}];         Do[         If[coefficientlist[[n,m]]!=0,           sumlist += coefficientlist[[n,m]] (cubelist[[n]]cubelist[[m]]) ];           ,{n,176},{m,176}];      Essentially I want to perform a sum like $S = \sum\limits_{i ,j} T_{ij} \phi_i \phi_j $ where the $T$ matrix is called `coefficientlist` in the code above and the $\phi_i$ are represented as grids over real space. I have to do this several times, so I want to find the most efficient way to do it. Thanks in advance.


title: How to return a string from LibraryLink?

text: I need to return a string from a LibraryLink function. The documentation states: > When a string is returned as a result, the Wolfram Language accesses the > memory to convert it to its own internal string format, but does not attempt > to free the memory. Thus, if your program allocates a string for a result, > it also needs to free that memory, but in a separate function from the one > setting the string result, since the Wolfram Language needs to access the > string memory after the library function has returned. Does this really mean that I need to have _two_ functions to be able to return the string, one to return it and one to free the memory? Is there really no simpler way? Based on my interpretation the _minimal_ work needed to return a dynamically allocated string is what's shown at the end of the post. Is this correct? This looks quite tedious. Is there a way to let Mathematica manage the memory for the string (including allocation and freeing, as with MTensors)? (To be fair: it can be expected that in many cases one would want to return a pre-defined string in which case there is no need to free it. Sometimes the string is dynamically allocated though, and it becomes necessary to free it.) * * * In this example use C++'s `std::string` to save some work, but using simple `char *` in C would be analogous, with some added tedium.               std::string *str = NULL; // ugly global variable          extern "C" DLLEXPORT int get_string(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {         str = new std::string("some string to return");         MArgument_setUTF8String(Res, const_cast<char *>(str->c_str()));         return LIBRARY_NO_ERROR     }          extern "C" DLLEXPORT int free_string(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {         delete str;         str = NULL;         return LIBRARY_NO_ERROR     }      Then in Mathematica:               iGetString = LibraryFunctionLoad["lib", "get_string", {}, "UTF8String"]     iFreeString = LibraryFunctionLoad["lib", "free_string", {}, "Void"]          getString[] :=        PreemptProtect@AbortProtect@Module[{str},         str = iGetString[];         iFreeString[];         str       ]


title: How can I change the MPS format in Linear Programming samples of Mathematica?

text: I am trying to play with some linear programming examples of _Mathematica_ as `ExampleData[{"LinearProgramming", "blend"}, "Equations"]`. It gives me the MPS format of the samples. How can I change them?


title: Display negative exponents always as fraction

text: I want _Mathematica_ to display negative exponents always as fractions. I already tried:               Needs["Notation`"]     (* Notation[1/a_^b_ <==> a_^-b_] *)     Notation[       ParsedBoxWrapper[RowBox[{"1", "/", RowBox[{"a_", "^", "b_"}]}]]       ⟺        ParsedBoxWrapper[RowBox[{"a_", "^", RowBox[{"-", "b_"}]}]]]      While I do have               x^-z      > >     1/x^z >   the following doesn't work:               x^-(2z)      > >     x^-2z >   Some hints ? Thank you very much !


title: How can I modify the interval of the function Image[]?

text: I think the default interval is [0,1]. when I have all positives I find it easy to rescale but when I included negative values it doesn't give me the results that I expect. for example how can I change the interval to [-1,1] ?? Thank you very much


title: How to find non zero elements of a list containing zeros and symbols

text: I have a list, obtained after differentiating a list of expressions, which contains zeros and symbols, say:               A = {x1^2, x2^2, x3^2, x4^2}     D[A,x3]      results in the list:               {0, 0, 2 x3, 0}      How do I get the position of the non-zero entry, mathematica cannot compare symbols to zero directly. I could convert the elements of the list to strings but is there a faster way?


title: Picking random items out of a list only once

text: I'm trying to create a function that randomly returns a value from a list but remembers the values that have been given before. At the end when the list is empty it should return an empty list. Basically like emptying a bucket full of eggs one at a time. Suppose I have two lists:               data1 = Range[10];     data2 = Range[20];      Assume a function               getRandomItem[l_List]      I tried playing with down-values but that doesn't work. Calling `getRandomItem[data1]` two times would give (e.g) `{1}` and `{3}`. Calling `getRandomItem[data2]` two times would give (e.g) `{15}` and `{20}` At the end as stated before when all items are chosen both `getRandomItem[data1]` and `getRandomItem[data2]` should return `{}`. I would like to do that without declaring `data1` and `data2` as global variables nor do I which to change/alter them. So, basically I presume the function itself should remember which data has been given to it and where it had left the previous time.


title: Why doesn't FullSimplify drop the Re function from an expression known to be real?

text: For some reason Mathematica does not properly simplify this expression:               In[7]:= FullSimplify[ArcTan[-Re[x + z], y], (x | y | z) \[Element] Reals]     Out[7]= ArcTan[-Re[x + z], y]      Obviously, if `x` and `z` are real, then so is `x+z`, so `Re[x + z]` should be replaced by `x + z`. Strangely enough, dropping any small part of the input fixes the problem, here are some examples.   No minus sign:               In[8]:= FullSimplify[ ArcTan[Re[x + z], y], (x | y | z) \[Element] Reals]     Out[8]= ArcTan[x + z, y]      No `z`:               In[9]:= FullSimplify[ArcTan[-Re[x], y], (x | y | z) \[Element] Reals]     Out[9]= ArcTan[-x, y]      No `y`:               In[10]:= FullSimplify[ArcTan[-Re[x + z]], (x | y | z) \[Element] Reals]     Out[10]= -ArcTan[x + z]      Of course I can just drop the `Re` function manually, but this is just a small fragment of the actual expression I'm trying to simplify, and I would like to avoid going though the whole expression looking for this specific pattern.   Anyone knows how to fix this? Is this a bug or what? (I'm using version 8.0.4.0)


title: Automatically evaluating related cells

text: I have the cells:               In[1]:= l = 2 + 2;          In[2]:= l >= 5      After evaluating them:               Out[2]:= False      Is there a way to evaluate all related cells, so if I change `In[1]` to `l = 2 + 5`, `Out[2]` would become `True` without evaluating the whole notebook?