title: Import CSV with "Numeric"->True and "DateStringFormat" problem

text: The CSV file linked below has 3 columns: "PT_ID" (char 4), "PHYS_ID" (char 2) and "VISIT_START_TIME" (varchar eg "0:00:15" hours minutes seconds) "https://docs.google.com/spreadsheet/pub?key=0AqPfEWYQJhXSdGF4ck5pblVlaHB0bkE0MWhsOWZ6M2c&output=csv"               Import["https://docs.google.com/spreadsheet/pub?key=\     0AqPfEWYQJhXSdGF4ck5pblVlaHB0bkE0MWhsOWZ6M2c&output=csv",       "DateStringFormat" -> {"Hour", ":", "Minute", ":", "Second"},       "Numeric" -> False]      Setting `"Numeric" -> False` will result in this output, so the hh:mm:ss is not matched {Q001,01,0:12:15} While setting `"Numeric" -> True` results in the following 2 seemingly unrelated problems: {Q001,1,{2014,1,1}}   1. "PHYS_ID" is cast to `Integer`   2. the 3-element List contains Year, Month, Day rather than Hours, Minute, Second Are there obvious solutions to both 1 and 2? http://reference.wolfram.com/mathematica/ref/format/CSV.html isn't very usable. EDIT (based on answers/comments): If it is known a priori which elements (columns) should be handled (here column 3, rows >=2), then using "Numeric"->False but not using DateStringFormat, the data can be post-processed using: MapAt[DateList[#][[4 ;;]] &, tmp, {2 ;;, 3}] But the ideal is to have Import deal with it given the documented options in CSV. DateStringFormat almost works. Used along with "Numeric"->True, it incorrectly returns the first 3 elements of DateList@"0:12:15" --> {2014, 1, 1, 0, 12, 15.} rather than the entire list. But if DateStringFormat is not used (and with "Numeric" -> True), then "0:12:15" is imported as-is (String).


title: How to use Compile

text: Consider the code below:               variable = Sin[x];     fun = Compile[{x}, variable ];     fun[1]      When I do this I get the error:                CompiledFunction::cfse: Compiled expression Sin[x] should be a machine-size real number       CompiledFunction::cfex: Could not complete external evaluation at instruction 1; proceeding with uncompiled evaluation. >>      However, if I use:                fun = Compile[{x}, Sin[x]];      Everything is fine. I need to compile as I presented first, the one which gives error because in my case `variable` is a huge very big expression. How can I achieve this goal?


title: Converting hierarchies of rules to associations

text: The impossibility of `MatchQ`-ing inside and `Association` MatchQ-ing Associations (MMA 10) explains a problem I have. I would like to convert hierarchical lists of rules to hierarchies of Associations. As an example:               rdata = {"a" -> {"b" -> 1, "c" -> {7, 8, 9}}, "d" -> 3}      Then               rdata /. List -> Association      returns > >     <|"a" -> <|"b" -> 1, "c" -> Association[7, 8, 9]|>, "d" -> 3|> >   where a value that happens to be a list is converted to something meaningless, which is not wanted. I have tried a variety of things like:               rdata /. x : {__Rule} :> Association[x]      or               (rdata /. List -> Association) /. x_Association /; NotAssociationQ[x] :> List @@ x      or               rdata /. {x__Rule} :> Association[x]      but none of them solves the problem.   I finally managed it by picking out the locations of all the lists of `Rule`s, as follows:               rtoA = (# /. {x__Rule} -> Association[x]) &     RulesToAssociation[rdata_] := Module[{pos},       pos = Drop[#, -1] & /@ Position[rdata, Rule];       Association @@ MapAt[rtoA, rdata, pos]]     RulesToAssociation[rdata]      which returns the desired result > >     <|"a" -> <|"b" -> 1, "c" -> {7, 8, 9}|>, "d" -> 3|> >   In my real application the rules list comes from the `Import` of a fairly complicated _JSON_ file. This solution seems to work but I'm not sure how robust it is. Does anyone have a better idea?


title: Find fit for complex function for smooth derivatives

text: I need to fit my data dropbox of the form `{x,y}` because I need the fit function for further derivative calculation. My derivative curve should be smooth. I tried                BSplineFunction[data, SplineDegree -> 5]      and also               Interpolation[data, InterpolationOrder -> 2]      but both derivates are not smooth. Therefore I ended up by using least square fit (LSF) by using a polynomial with varying the degree of the polynomial (DOP) to find the best fit:               DOP = 21;      LSF = Fit[data, Evaluate[Table[x^i, {x, 0, DOP}]] , x];      The problem is that even choosing a high DOP, the experimental data are not fitted very well in the important section of the curve (between local minimum and -maximum) ![fit vs experimental](http://i.stack.imgur.com/xf2uZ.png) (blue: experimental data; red: LSF) and/or the derivative seems to start to oscillate at the beginning or end of the curve (in this example at the beginning, pointed to by black arrow): ![enter image description here](http://i.stack.imgur.com/fPRxo.jpg) Zooming the experimental curve in the first section does not reveal something that could cause that error: ![enter image description here](http://i.stack.imgur.com/Pvi5M.png) Has that something to do with Runge's phenomenon or how can I solve that easily?


title: FEM: Nicer Element Shape for Spherical Region

text: I'm trying to generate a mesh for later use in the Finite Element Method of the `DSolve` command. It is basically a parallelepiped with a spherical indentation. I'm trying to generate the mesh as follows:               Needs["NDSolve`FEM`"]     region = ImplicitRegion[!(Norm[{x, y, z}] < 1), {{x, -5, 5}, {y, -5, 5}, {z, 0, 5}}];     mesh = ToElementMesh[region];     Show[mesh["Wireframe"], PlotRange -> {{-2, 2}, {-2, 2}, {0, 1}}]      However, as you an see on the picture below this produces a really irregular and inaccurate (as I think) mesh for the spherical part. Is there a way to improve it and to generate more and homogeneously distributed elements on the spherical part? ![enter image description here](http://i.stack.imgur.com/YAC8D.png)


title: Slider moving in irregular steps

text: Sorry - bit of a yes/no question: Is it possible to make the slider from a manipulation jump in irregular steps? Or would the best way to overcome this be to just create a series of buttons that jump the manipulation to the desired position?


title: Strange behavior of function (memory leaks)

text: I have some funtion:               GetOptimalWarpingPathMod[cumulativeCostMatrix_List, a_Integer,         b_Integer] := Module[{optimalPath, j, i, min, argMin},        {i, j} = {a, b};        optimalPath = Reap@While[(i >= 3) && (j >= 2),           min =             Min[cumulativeCostMatrix[[i, j - 1]],              cumulativeCostMatrix[[i - 1, j - 1]],              cumulativeCostMatrix[[i - 2, j - 1]]];           Switch[min,            cumulativeCostMatrix[[i, j - 1]], argMin = {i, j - 1}; j--,            cumulativeCostMatrix[[i - 1, j - 1]], argMin = {i - 1, j - 1};             i--; j--,            cumulativeCostMatrix[[i - 2, j - 1]], argMin = {i - 2, j - 1};             i -= 2; j--,            _, Throw["Error in GetOptimalWarpingPathNewMod"]            ];           Sow@argMin;           ];        optimalPath =          If[Length[optimalPath[[2]]] == 0, {}, optimalPath[[2, 1]]];        PrependTo[optimalPath, {a, b}];        optimalPath = Reverse@optimalPath;        optimalPath        ];      When I call it with random argument this leads to memory leaks:               $HistoryLength = 1;     someMatrix = RandomReal[{0, 20}, {10, 5}];         memoryBefore = MemoryInUse[];         Do[           GetOptimalWarpingPathMod[someMatrix , Length[someMatrix ],             Ordering[someMatrix [[-1]]][[1]]],           {i, 1, 10}];         MemoryInUse[] - memoryBefore         (*17752*)      But calling this function with predefined matrix all work fine               savedMatrix={{3.3004394437748807`,10.881946255573773`,4.362690908144572`,7.407440543303238`,7.345486257827773`},{14.508362563589763`,0.7356685771730973`,8.779141880113663`,14.969579494157415`,8.685346276624468`},{14.917882497227396`,17.430051988389053`,10.513304852635628`,16.791683365979523`,12.646147419315149`},{1.0588495204942632`,2.2005278583930767`,16.75277676811745`,4.0963643230729865`,13.369846181008235`},{14.413222169933519`,12.715945901646649`,12.488814903450923`,0.5015257662166803`,18.833930414984806`},{10.97588310006406`,8.811907048532749`,13.721241067651995`,17.829727310320855`,2.9585195950653898`},{1.85685418882683`,13.50702995493117`,16.501883534317372`,12.896932254223422`,14.724301159710564`},{8.246316747888361`,8.819447634430265`,11.769957506935448`,6.171909927482631`,12.075720584292299`},{2.3538532552195015`,18.372378238597122`,1.767319259063889`,8.244194544322362`,1.239398836296214`},{10.33557094657684`,11.650188299063093`,4.182059630971807`,17.839911646054595`,8.060657545219925`}};     memoryBefore = MemoryInUse[];          Do[       GetOptimalWarpingPathMod[savedMatrix, Length[savedMatrix],         Ordering[savedMatrix[[-1]]][[1]]],       {i, 1, 10}];     MemoryInUse[] - memoryBefore     (*8*)      What difference in that function calling? **EDIT** Of cource this function do nothing. But there the same problem               GetOptimalWarpingPathSimple[cumulativeCostMatrix_List, a_Integer,         b_Integer] := Module[{optimalPath, j, i, min, argMin},        {i, j} = {a, b};        While[(i >= 3) && (j >= 2),         min =           Min[cumulativeCostMatrix[[i, j - 1]],            cumulativeCostMatrix[[i - 1, j - 1]],            cumulativeCostMatrix[[i - 2, j - 1]]];         Switch[min,          cumulativeCostMatrix[[i, j - 1]], argMin = {i, j - 1},          cumulativeCostMatrix[[i - 1, j - 1]], argMin = {i - 1, j - 1},          cumulativeCostMatrix[[i - 2, j - 1]], argMin = {i - 2, j - 1}          ];         RandomChoice[{j--, {i--; j--}, {i -= 2; j--}}];         ];        ];      PS: probably problem in `Switch` fucntion becouse when I comment it the is no memory leaks


title: how to change the distance between tick mark and tick label

text: On similar lines as Is there an option to change the space/distance between tick labels and axes labels for plots? but I would like to reduce the distance between the tick mark and the tick label that appears below it. For eg: In this figure, I would like to reduce the distance between -2 in the x axis and the tick mark corresponding to it ![enter image description here](http://i.stack.imgur.com/ggGqf.png) Edit: Adding the code that generated this figure:                   cutoff = 0.52;     grp1 = {{-4.10855, 1}, {-3.18, 2}, {-2.97477, 3}, {-2.40408,          4}, {-2.19854, 5}, {-1.77951, 6}, {-1.76863, 7}, {-1.75573,          8}, {-1.71227, 9}, {-1.64262, 10}, {-1.48712, 11}, {-1.42243,          12}, {-1.29815, 13}, {-1.18774, 14}, {-1.03156, 15}, {-0.978796,          16}, {-0.971106, 17}, {-0.922292, 18}, {-0.862833,          19}, {-0.807821, 20}, {-0.775937, 21}, {-0.750941,          22}, {-0.737334, 23}, {-0.715059, 24}, {-0.712102,          25}, {-0.693181, 26}, {-0.69129, 27}, {-0.674491, 28}, {-0.644356,          29}, {-0.620938, 30}, {-0.59347, 31}, {-0.589228,          32}, {-0.581852, 33}, {-0.580016, 34}, {-0.56826, 35}, {-0.566551,          36}, {-0.561733, 37}, {-0.55583, 38}, {-0.551104,          39}, {-0.549835, 40}, {-0.535232, 41}, {-0.53486, 42}, {-0.533395,          43}, {-0.523652, 44}, {-0.520547, 45}, {-0.508359,          46}, {-0.506626, 47}, {-0.491825, 48}, {-0.490019, 49}, {-0.477,          50}, {-0.473228, 51}, {-0.470723, 52}, {-0.470415,          53}, {-0.454857, 54}, {-0.454278, 55}, {-0.452099,          56}, {-0.421126, 57}, {-0.41768, 58}, {-0.415444, 59}, {-0.402139,          60}, {-0.387403, 61}, {-0.380952, 62}, {-0.374082,          63}, {-0.373277, 64}, {-0.370055, 65}, {-0.364634,          66}, {-0.361553, 67}, {-0.361208, 68}, {-0.360869, 69}, {-0.34248,          70}, {-0.340748, 71}, {-0.33172, 72}, {-0.330729,          73}, {-0.311965, 74}, {-0.310625, 75}, {-0.304104,          76}, {-0.302831, 77}, {-0.302533, 78}, {-0.29397, 79}, {-0.291521,          80}, {-0.289982, 81}, {-0.27621, 82}, {-0.264455,          83}, {-0.256689, 84}, {-0.250929, 85}, {-0.246889,          86}, {-0.228836, 87}, {-0.22671, 88}, {-0.202538, 89}, {-0.196612,          90}, {-0.187845, 91}, {-0.187817, 92}, {-0.179211,          93}, {-0.173247, 94}, {-0.165728, 95}, {-0.163806,          96}, {-0.153261, 97}, {-0.132747, 98}, {-0.122831,          99}, {-0.117507, 100}, {-0.113069, 101}, {-0.102309,          102}, {-0.0976552, 103}, {-0.0951561, 104}, {-0.0894875,          105}, {-0.0876338, 106}, {-0.087434, 107}, {-0.0845464,          108}, {-0.0757364, 109}, {-0.0635816, 110}, {-0.0621387,          111}, {-0.0580457, 112}, {-0.0558367, 113}, {-0.0529842,          114}, {-0.0478612, 115}, {-0.0444608, 116}, {-0.0410887,          117}, {-0.0398071, 118}, {-0.0322021, 119}, {-0.0200628,          120}, {-0.0182955, 121}, {-0.0144614, 122}, {-0.0138035,          123}, {-0.00716598, 124}, {0., 125}, {0.0103846, 126}, {0.0205011,          127}, {0.0341349, 128}, {0.059813, 129}, {0.0954803,          130}, {0.123192, 131}, {0.123591, 132}, {0.147797,          133}, {0.166342, 134}, {0.16952, 135}, {0.186956, 136}, {0.206183,          137}, {0.210853, 138}, {0.260639, 139}, {0.287231,          140}, {0.30835, 141}, {0.314636, 142}, {0.329798, 143}, {0.334356,          144}, {0.36056, 145}, {0.383386, 146}, {0.45576, 147}, {0.457104,          148}, {0.46041, 149}, {0.482364, 150}};          grp2 = {{0.559846, 151}, {0.603893, 152}, {0.692402, 153}, {0.736425,          154}, {0.742579, 155}, {0.750076, 156}, {0.879458,          157}, {0.967285, 158}, {0.988934, 159}, {1.04353, 160}, {1.06206,          161}, {1.12605, 162}, {1.13691, 163}, {1.14313, 164}, {1.22551,          165}, {1.24425, 166}, {1.32567, 167}, {1.35547, 168}, {1.3873,          169}, {1.46251, 170}, {1.48027, 171}, {1.48587, 172}, {1.50248,          173}, {1.50557, 174}, {1.52349, 175}, {1.52676, 176}, {1.61266,          177}, {1.6306, 178}, {1.71358, 179}, {1.73984, 180}, {1.79301,          181}, {1.81201, 182}, {1.86031, 183}, {1.90378, 184}, {1.91104,          185}, {1.932, 186}, {1.94978, 187}, {1.96444, 188}, {1.97321,          189}, {1.98785, 190}, {1.99161, 191}, {2.02637, 192}, {2.04347,          193}, {2.05299, 194}, {2.07511, 195}, {2.08866, 196}, {2.17186,          197}, {2.19635, 198}, {2.2132, 199}, {2.22343, 200}, {2.22452,          201}, {2.24434, 202}, {2.25782, 203}, {2.2627, 204}, {2.27745,          205}, {2.46167, 206}, {2.48096, 207}, {2.54055, 208}, {2.64996,          209}, {2.65934, 210}, {2.73535, 211}, {2.78724, 212}, {2.79484,          213}, {2.79819, 214}, {2.88538, 215}, {2.89362, 216}, {2.96651,          217}, {3.00729, 218}, {3.07063, 219}, {3.11961, 220}, {3.19508,          221}, {3.2295, 222}, {3.23329, 223}, {3.27631, 224}, {3.3876,          225}, {3.41121, 226}, {3.46174, 227}, {3.61129, 228}, {3.61579,          229}, {3.64525, 230}, {3.77605, 231}, {3.91162, 232}, {3.91579,          233}, {3.9266, 234}, {4.12641, 235}, {4.15509, 236}, {4.21151,          237}, {4.25269, 238}, {4.41959, 239}, {4.4295, 240}, {4.45912,          241}, {4.70492, 242}, {4.72227, 243}, {4.93772, 244}, {5.7519,          245}, {5.92314, 246}, {6.20269, 247}, {6.23834, 248}, {7.70686,          249}};          Show[ListPlot[{grp1, grp2}, Frame -> True,        FrameLabel -> {Column[{Style["x", FontFamily -> "Courier"],            Style["y", FontFamily -> "Courier"]}, Center], "(b) z", None,          None, None}, AspectRatio -> 1.8,        PlotStyle -> {{Blue, PointSize[0.01]}, {Red, PointSize[0.01]}},        FrameTicks -> {{{-2, -2, {0, 0.03}}, {0, 0, {0, 0.03}}, {cutoff,            "   " <> ToString[N[Round[cutoff, 10^-1]]], {0, 0.03}}, {2,            2, {0, 0.03}}, {4, 4, {0, 0.03}}, {6, 6, {0, 0.03}}}, {{1,            1, {0, 0.03}}, {50, 50, {0, 0.03}}, {100, 100, {0, 0.03}}, {150,            150, {0, 0.03}}, {200, 200, {0, 0.03}}}, None, None},        AxesOrigin -> {1, 0}, Axes -> False, ImageSize -> {211, 335},        ImagePadding -> {{50, 0}, {50, 0}},        PlotRange -> {{Automatic, Automatic}, {1, 250}}],       Graphics[{Dashed, Black, Line[{{cutoff, 1}, {cutoff, 249}}]}]]


title: How to understand the usage of Inner and Outer figuratively?

text: ## Description: In _Mathematica_ the functions like `Thread`, `Inner`, `Outer` etc. are very important and are used frequently. For the function `Thread`: ThreadUsage1:               Thread[f[{a, b, c}]]      > >     {f[a], f[b], f[c]} >   ThreadUsage2:               Thread[f[{a, b, c}, x]]      > >     {f[a, x], f[b, x], f[c, x]} >   ThreadUsage3:               Thread[f[{a, b, c}, {x, y, z}]]      > >     {f[a, x], f[b, y], f[c, z]} >   And I understand the `Usage1`, `Usage2`, `Usage3` easily as well as I use them masterly. However I always cannot master the usage of **`Inner`** and **`Outer`** so that I must refer to the _Mathematica_ Documentation every time when I feel I need using them. I find that I cannot master them owing to that I cannot understand the results of **`Inner`** and **`Outer`** clearly. Namely, I always forget what construct they generate when executed. The typical usage cases of `Inner` and `Outer` are shown below: ## InnerUsage:               Inner[f, {a, b}, {x, y}, g]      > >     g[f[a, x], f[b, y]] >                 Inner[f, {{a, b}, {c, d}}, {x, y}, g]      > >     {g[f[a, x], f[b, y]], g[f[c, x], f[d, y]]} >   ## OuterUsage:               Outer[f, {a, b}, {x, y, z}]      > >     {{f[a, x], f[a, y], f[a, z]}, {f[b, x], f[b, y], f[b, z]}} >   ## Questions:   1. How to master the usage **`Inner`** and **`Outer`**? Namely, how can I use them without referring to the _Mathematica_ Documentation?   2. How to understand the result of `Out[3]`,`Out[4]`,`Out[5]` figuratively? Namely, by using graphics or other way.


title: Solving $L=\frac{3}{2} \sqrt{4 \pi ^2 A^2+W^2}-\frac{\sqrt{5 W \sqrt{4 \pi ^2 A^2+W^2}+6 \pi ^2 A^2+3 W^2}}{\sqrt{2}}+\frac{3 W}{2}$ for $W$

text: When I solve the aforementioned equation for $W$ or $A$ on Mathematica I get a long and ugly equation in return, namely one of the solutions for $W$ is: (attempt to read at your own health)               Solve[L == (3 W)/2 + (3 Sqrt[4 A^2 Pi^2 + W^2])/2 - Sqrt[6 A^2 Pi^2 + 3 W^2 +       5 W Sqrt[4 A^2 Pi^2 + W^2]]/Sqrt[2], W]      $W=\frac{3 L}{10}-\frac{1}{2} \sqrt{\frac{\sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}{15 \sqrt[3]{2}}+\frac{9 L^2}{25}-\frac{4}{15} \left(10 \pi ^2 A^2+3 L^2\right)+\frac{4 \sqrt[3]{2} \left(640 \pi ^4 A^4-246 L^2 \pi ^2 A^2-3 L^4\right)}{15 \sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}}-\frac{1}{2} \sqrt{-\frac{\sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}{15 \sqrt[3]{2}}+\frac{18 L^2}{25}-\frac{8}{15} \left(10 \pi ^2 A^2+3 L^2\right)-\frac{4 \sqrt[3]{2} \left(640 \pi ^4 A^4-246 L^2 \pi ^2 A^2-3 L^4\right)}{15 \sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}-\frac{\frac{216 L^3}{125}-\frac{48}{25} \left(10 \pi ^2 A^2+3 L^2\right) L+\frac{48}{5} \left(L^2-2 A^2 \pi ^2\right) L}{4 \sqrt{\frac{\sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}{15 \sqrt[3]{2}}+\frac{9 L^2}{25}-\frac{4}{15} \left(10 \pi ^2 A^2+3 L^2\right)+\frac{4 \sqrt[3]{2} \left(640 \pi ^4 A^4-246 L^2 \pi ^2 A^2-3 L^4\right)}{15 \sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}}}}$ The above just makes the point that the solution can't be written by hand (or by mine at least). So my question is, can I represent the solution using an easily-written function of $A$ and $L$ (for instance, as a infinite summation)?


title: NSolve for large models

text: I'm a Mathematica rookie running version 7.0 for Mac OS X x86 (64-bit) (February 19, 2009) on a 2010 MacBook Pro. (I'm also a stackexchange "newbie" who originally posted this on stackoverflow, thus missing the target audience. I hope I'm not breaking any sacred rules by reposting the question here.) Context: I'm trying to solve an economics problem with a large number of firms, where each firm is given a maximum production quota (i.e., rights to produce). The firms are of different sizes, larger ones being more efficient than smaller ones. There is a market for quotas, thus small, inefficient firms can shut down and sell their quota rights to larger ones; the quota price k must be computed endogenously. By and large, the bigger the number of firms, the bigger the number of equations to solve simultaneously. The issue is as follows: with a small number of firms n (from 2 to 3), only Solve works, whereas NSolve erroneously yields {}, i.e., no solution. With a medium number of firms (from 4 to 7), only NSolve works. Solve does not seem to work for any problem with 4 or more firms. With 8 and 9 firms, NSolve again erroneously yields {}. With 10 to 16 firms, NSolves works fine. With a larger number of firms (17 and above), the evaluation keeps running without end and I end up aborting (I waited up to 15 minutes). My hope was to run the model with thousands of firms. My questions are   (1) how can I systematically get Mathematica to converge to the solution for an arbitrary large system and   (2) why does NSolve not work for small systems. Two remarks: (1) You will notice some awkwardness in the way I set up the model, starting with a guess k0 for k, which determines which firms are operating and which ones are shutting down. Upon that, for the list of operating firms, I compute the profit maximizing amount of labor, total output, and equilibrium k. If k is different from k0, I restart the computation with k0=k. The question of how to create a more elegant one-step program is a separate issue, though, and I don't think it is connected to what appears to be a model size limitation. (2) If I solve the model for, say, 11 firms and then jump trying to solve for, say, 13 firms, Mathematica ends up running "endlessly". But if I solve for 12 firms first, then solving for 13 firms is a matter of seconds. So it would seem that despite the ClearAll["Global`*"] statement at the beginning of the notebook, it is as if Mathematica seemed to start with a better starting point. I'm ready to be humbled :) UPDATE 1: I'm now running version 10.0 and NSolve works fine with all cases involving less than 16 firms, which generate a system of at most 4 equations in 4 unknowns. The case with 17 firms generates a system with 5 equations and 5 unknowns, which _appears_ to be too much for NSolve. I changed the question title accordingly, to focus on NSolve only. UPDATE 2: If we use the case with 12 firms as an illustration, the generated set of equations is $ \left\{ \begin{array}{l} \frac{5154.55 (5-k)}{\text{tl}_1^{0.3}}-100=0 \\ \frac{5727.27 (5-k)}{\text{tl}_2^{0.3}}-100=0 \\ \frac{6300 (5-k)}{\text{tl}_3^{0.3}}-100=0 \\ 7363.64 \text{tl}_1^{0.7}+8181.82 \text{tl}_2^{0.7}+9000 \text{tl}_3^{0.7}=1000000 \end{array} \right. $ which can be rewritten $ \left\{ \begin{array}{l} \text{tl}_1^{0.7} = (5-k)^{7/3} 51.5455^{7/3} \\ \text{tl}_2^{0.7} = (5-k)^{7/3} 57.2727^{7/3} \\ \text{tl}_3^{0.7} = (5-k)^{7/3} 63^{7/3} \\ (5-k)^{7/3} \left( 7363.64 \times 51.5455^{7/3} +8181.82 \times 57.2727^{7/3} +9000 \times 63^{7/3} \right)=1000000 \end{array} \right. $, a problem simple enough to be solved with a pocket calculator. With more firms, i.e., more equations and more unknowns, the structure should be just as simple; it is therefore a mystery to me why NSolve appears to be overwhelmed. Here is the code:               $Version     ClearAll["Global`*"]     (* Aggregate Quota Allocation *)     alloc=1000000;     (* Number of firms, variable that I would like to increase arbitrarily; *)     nv=4;     (* Equal quota allocation to each firm; *)     qbar = alloc/nv;     (* Firm sizes vary in amount of capital from smallest to largest;*)     vsmin=0 ;     vsmax=900000 ;     (* Assume discrete uniform distribution of firm sizes;*)     dvs=(vsmax-vsmin)/(nv-1) ;     (* List all firms by size; *)     listvs=Table[vs,{vs,vsmin,vsmax,dvs}]  ;     (* A firm's capital cost per annum is 10 percent of capital size;*)     g=0.1 ;     (* Avoidable fixed cost of operation;*)     f=5000 ;     (* Parameters of production function (same for all firms);*)     a=0.01 ;     alpha=0.7 ;     (* Price of output; *)     p=5;     (* Price of labor (daily wage);*)     wa=100 ;     (* Firm vs is a profit maximizer setting optimal number of days of operation tl[vs] ;     Firms that are too small are better off leasing their quota allocation to larger ones;      The quota leasing price k is computed endogenously;     Firms will exit if "netprofitstay" is less than 0;     We are looking for threshold firm, whose size nvs1 is just above threshold size vs0;     All firms whose size is nvs1 or larger are operating, the others are shutting down;     For now, we are setting the problem up as a manual loop, setting k0 = "k opt"      from previous computation ; *)          k0=4.891714989052472` ;          profitstay0[tl0_,vs0_]:= (p-k0)(a vs0 tl0^alpha) - wa tl0 + k0 qbar - g vs0 - f  ;     netprofitstay0[tl0_,vs0_]:=(p-k0)(a vs0 tl0^alpha) - wa tl0 - f  ;     sol0:=NSolve[{D[profitstay0[tl0,vs0],tl0]==0 ,netprofitstay0[tl0,vs0]==0} ,{tl0,vs0}]  ;     vs1:=vs0/.Last[sol0]      nvs0:=Part[Nearest[listvs,vs1],1] ;     nvs1:=If[nvs0<vs1,nvs0+dvs,nvs0] ;     (* List of firms who operate when k=k0; *)     listvsop:=Table[vs,{vs,nvs1,vsmax,dvs}]  ;          (* Production function;*)     eq[tl[vs_],vs_]:=a vs tl[vs]^alpha ;     (* Profit; *)     profitstay[k_,tl[vs_],vs_]:=(p-k) eq[tl[vs],vs] - wa tl[vs] + k qbar - g vs - f  ;     (* List of first-order conditions for a maximum; *)     foc:=Table[D[profitstay[k,tl[vs],vs],tl[vs]]==0,{vs,listvsop}]  ;     (* List of all endogenous variables; *)     variables:=Flatten[{k,Table[tl[vs],{vs,listvsop}]},1] ;     Print[variables] ;     (* List of all equations, including the one specifying that aggregate quota demand = aggregate     quota supply; *)     equations:=Flatten[{foc,Sum[eq[tl[vs],vs],{vs,listvsop}]==alloc }] ;     Print[equations] ;          (* Find solution;*)     NSolve[equations,variables]


title: Extending a plot over a secondary variable

text: Apologies for the vague title; couldn't really think of a better way of putting it. I have a function $F$ of two variables, $\rho\in[0,\infty)$ and $f\in[0,1]$, that I wish to create a plot over (e.g. with `CountourPlot` or `DensityPlot`). I can numerically generate the entire curve of $F$ over $f$ for a particular value of $\rho$ relatively cheaply, but I can't directly compute $F$ for individual values of $f$. Is there an efficient way of taking such a curve and plotting it for a range of $\rho$ without Mathematica having to evaluate the function independently at every $(\rho,f)$? * * * Here's how I compute $F$:               Lorentz[data_] := Module[{xs, ys},        xs = Range[0, Length[data]];        ys = Prepend[Accumulate[Sort[data]], 0];        Transpose[{xs/Last@xs, ys/Last@ys}]];          L = Interpolation[Lorentz[data], InterpolationOrder -> 1];     F = 1 - L[1 - #] &;      `data` is a list of real numbers generated according to the value of $\rho$. Essentially, I generate a Lorentz curve numerically as a list of $(x,y)$ tuples, turn it into a function via `Interpolation`, reflect it a couple of times, and that's my function $F$.


title: Indenting bulleted lists in Notebooks

text: I currently use Word for notes, making nested bulleted lists as I go. I've just started using Mathematica and would like to do the same in its Notebooks, but it doesn't look like it has that capability. There isn't any automatic indenting of the entire line (so when it wraps, it doesn't start at the indent of the bullet point, but it starts at the beginning of the page). Is an option that turns it on or a module that allows for it?


title: Gather dependency on list order?

text: I get intrigued about `Gather` behavior on this post. I thought that `Gather` was invariant under list order? Here is the result I spect:               l1={{1, 1}, {0, 0}, {2, 2}, {5, 5}, {4, 4}, {6, 6}}     Gather[l1,ManhattanDistance[#1, #2] <= 2 &]      > {{{1,1},{0,0},{2,2}},{{5,5},{4,4},{6,6}}} When the list order is changed, I get this:               l2={{0, 0}, {1, 1}, {2, 2}, {4, 4}, {5, 5}, {6, 6}}     Gather[l2,ManhattanDistance[#1,#2]<= 2&]      > {{{0,0},{1,1}},{{2,2}},{{4,4},{5,5}},{{6,6}}} Someone know why?


title: Quick multiple selections from a list

text: What is the fastest way to make multiple selections from a list? Compiled methods included. For example, here are two methods for selecting a subset, compared:-               biglist = {{5, "e", 500}, {4, "d", 400},        {3, "c", 300}, {2, "b", 200}, {1, "a", 100}};     subset = {2, 5, 4};          Cases[biglist, {#, __}] & /@ subset      > {{{2, "b", 200}}, {{5, "e", 500}}, {{4, "d", 400}}}               Cases[biglist, {Apply[Alternatives, subset], __}]      > {{5, "e", 500}, {4, "d", 400}, {2, "b", 200}} Only first method returns items in the order matched in the subset list, but it is much slower:-               n = 10000;     biggerlist = Map[{#, FromCharacterCode[Mod[# - 1, 26] + 97], #*100} &,        Range[n]];     unsortedbiglist = RandomSample[biggerlist, n];     unsortedsubset = RandomSample[Range[n], Round[n/10]];          Row[{First[Timing[selection1 = Map[Cases[unsortedbiglist, {#, __}] &,            unsortedsubset];]], " seconds"}]      > 1.123 seconds               Row[{First[Timing[selection2 = Cases[unsortedbiglist,            {Apply[Alternatives, unsortedsubset], __}];]], " seconds"}]      > 0.171 seconds The selections are the same, but differently ordered:-               SameQ[Flatten[selection1, 1],      Extract[selection2,       Flatten[Map[Position[First /@ selection2, #] &,         unsortedsubset], 1]]]      > True Including the sorting routine in the selection process still gives a better timing:-               Row[{First[Timing[selection3 = Function[selection2,             Extract[selection2,              Flatten[Map[Position[First /@ selection2, #] &,                unsortedsubset], 1]]][Cases[unsortedbiglist,             {Apply[Alternatives, unsortedsubset], __}]];]], " seconds"}]      > 0.359 seconds               SameQ[Flatten[selection1, 1], selection3]      > True Nevertheless, only the slow `Cases` method returns `{}` when there are unmatched subset items, which is sometimes useful. Ideas for speedy selections would be great.


title: Why does one Monitor expression work while another fails?

text: I have a (somewhat involved) function `f[x?NumericQ, y?NumericQ]` and for some reason it behaves differently when given a `Table` than when given a `RegionPlot`.               Monitor[Table[f[x, y] > 2, {x, 2, 50, 1}, {y, 0, 500, 1}], {x, y}]      shows the values of `x` and `y` as the grid is scanned and returns the table. However,               Monitor[RegionPlot[Tan[x, y] > 2 {x, 2, 50}, {y, 0, 500}], {x, y}]      returns nothing and the monitor gets stuck on unevaluated `x, y` after the initial point of the evaluation (close to (2, 0)) has been done. Any idea about   * What kind of trouble might arise in `RegionPlot` that did not happen with `Table`   * How I could investigate what's going on in the `RegionPlot`


title: How to define a derivative/Variation operation in Mathematica from scratch

text: I am looking for a method in Mathematica 8 to define my own derivative/variation (independent of built-in operations). I do not want to re-define built-in objects since I fear that this could cause subtle changes at different places. Does anybody know how to define such a "proto-derivative"? I would be thankful for posting a code and some explanations/documentation or a link to some document where it is described in detail.


title: Simplify matrix algebra

text: I'm trying to simplify some matrix linear algebra, for example, simplify $$\big(a1\times(A1\cdot A2)\big)\cdot\Big(a2\times A3\cdot A4+(a3\times A5)\cdot(a4\times A6)\Big)^{T}$$ where lower case variables (a1-a4) are numbers and upper case variables (A1-A6) are matrixes. "$\times$" is the Times function and "$\cdot$" is the Dot function, $\text{T}$ is the transpose operation. I have these math identities for my matrixes in my case: $$ (A\cdot B)^{T}=B^{T}\cdot A^{T}\\ (A+B)^{T}=A^{T}+B^{T}\\ c\times(A+B)=c\times A+c\times B\\ c^{T}=c $$ so the expresion will simplify into $$ a1~a2~A1\cdot A2\cdot A4^{T}\cdot A3^{T}+a1~a3~a4(A1\cdot A2\cdot A6^{T} \cdot A5^{T}) $$ My major question is how can I use Simplify or FullSimplify to do this simplification in MMA in an elegant and extensible way? For extensible I mean that one can easily add more operation rules into the simplification identities, for example, we could add inverse operation and its identities such as $(A\cdot B)^{-1}=B^{-1}\cdot A^{-1}$ and $(A^{-1})^T=(A^T)^{-1}$ etc. * * * Here is my try (I'm a novice and apparently my code is not elegant in any sense so please don't hesitate to advice suggestions or to point out any mistakes I made, I'm very welling to learn from you guys. And please pardon my poor English :P): 1.First simplify $(A\cdot B)^{T}$ to $B^{T}\cdot A^{T}$ and $(A+B)^{T}$ to $A^{T}+B^{T}$, I define a transformation function               g1[expr_] := expr /. Transpose[A_] :> If[Head[A] == Dot || Head[A] == Times || Head[A] == Plus,      Head[A] @@ Reverse[Transpose /@ A], Transpose[A]]      which changes `Transpose[Dot[A,B]]` to `Dot[Transpose[B],Transpose[A]]`, and `Transpose[Plus[A,B]]` to `Plus[Transpose[B],Transpose[A]]`. And then define a ComplexFunction that prefers the form that Transpose is in the inside, for example, prefer `Dot[Transpose[B],Transpose[A]]` to `Transpose[Dot[A,B]]` :               cpfunc[expr_] := Module[{funcls},      If[Length[expr] > 1, 0,        If[Depth[expr] <= 2, 0,        funcls = Reverse[Part[#, 0] & /@ (Level[#, {0, Depth[#] - 2}])] &@expr;        If[Max[Position[funcls, Transpose]] - Max[Position[funcls, Dot]] < 0 ||           Max[Position[funcls, Transpose]] - Max[Position[funcls, Times]] < 0 ||            Max[Position[funcls, Transpose]] - Max[Position[funcls, Plus]] < 0,        10^3, 0] (*gives punishment when found Dot inside Transpose, etc.*)     ]]]      This works for `Transpose[A1.B1.C1]`:               Simplify[Transpose[A1.B1.C1], TransformationFunctions -> {Automatic, g1},       ComplexityFunction -> cpfunc]     (*Transpose[C1].Transpose[B1].Transpose[A1]*)          Simplify[Transpose[a*A1], TransformationFunctions -> {Automatic, g1},        ComplexityFunction -> cpfunc]     (*Transpose[a] Transpose[A1]*)      2.Second simplify $(a\times A)^{T}$ to $a~A^{T}$ : I define a transformation function:               g2[expr_] :=       expr /. Transpose[x_] :> If[x \[Element] Reals, x, Transpose[x]]      then               Simplify[g2@Simplify[Transpose[a*A1], TransformationFunctions -> {Automatic, g1},         ComplexityFunction -> cpfunc],         Assumptions -> a \[Element] Reals && A1 \[NotElement] Reals]     (*a Transpose[A1]*)      Initially I was trying to do something like this but it doesn't work(could you point out the mistakes?)               g2[expr_] := expr /. (Transpose[x_];/NumberQ[x]) :> x     Simplify[Transpose[a*A],TransformationFunctions->{Automatic,g1,g2},        ComplexityFunction->cpfunc,Assumptions->a\[Element] Reals&&A1\[NotElement]Reals]     (*Transpose[a] Transpose[A]*)      3.Simplify the whole expression:               Simplify[(a1*A1.A2).Transpose[a2*A3.A4 + (a3*A5).(a4*A6)],       TransformationFunctions -> {Automatic, g1},      ComplexityFunction -> cpfunc]     (*      (a1 A1.A2).((Transpose[a4] Transpose[A6]).(Transpose[a3] Transpose[A5])       + Transpose[A4].Transpose[A3] Transpose[a2])     *)          Simplify[g2@%, Assumptions -> {a1 \[Element] Reals, a2 \[Element] Reals,       a3 \[Element] Reals, a4 \[Element] Reals, A1 \[NotElement] Reals,       A2 \[NotElement] Reals, A3 \[NotElement] Reals,       A4 \[NotElement] Reals, A5 \[NotElement] Reals,       A6 \[NotElement] Reals}]     (*      (a1 A1.A2).(a2 Transpose[A4].Transpose[A3]       + (a4 Transpose[A6]).(a3 Transpose[A5]))     *)      the output is $$ (\text{a1} \text{A1}\cdot\text{A2})\cdot(\text{a2} \text{A4}^{\mathsf{T}}\cdot\text{A3}^{\mathsf{T}}+(\text{a4} \text{A6}^{\mathsf{T}})\cdot(\text{a3} \text{A5}^{\mathsf{T}})) $$ This final answer is close to the result I want to achieve. I tried to go further but without any luck. Here is my thinking(questions) about this:   1. Is there some more elegant way to do this? For example, it is possible to set some kind of attributes to these different operations so that Dot, Times, Pulse etc have different priority in the calculation, and one can sort them directly by their attributes in order to simplify or expand an expression?   2. I'm very curious how MMA Expand an algebra expression like `(a + b)*(c + d*e)`.   3. How to make a transformation function work on different assumptions? For example, when only x is a number, that the transformation Transpose[x_]:>x will apply. Thank you very much for the help.


title: Why doesn't Normal[] work?

text: I have a polygon on which I'm applying a `GeometricTransform` and I want to get the coordinates of the transformed polygon. `Graphics[g]` works and shows it nicely, but `Normal@g` doesn't seem to work. What am I doing wrong?               g = GeometricTransformation[          Polygon[{           {-0.36551249999999996`, -0.29021463333333336`},            {-0.36509784999999995`, -0.2812481916666667`},            {-0.3619309499999999`, -0.2645122083333334`},            {-0.3592788999999999`, -0.25668636666666667`},            {-0.3520880999999999`, -0.2419782333333334`},            {-0.34271569999999996`, -0.22834049999999997`},            {-0.3254433499999999`, -0.209398275`},            {-0.3055169`, -0.19159769999999998`},            {-0.26311249999999997`,-0.15638130000000006`},            {-0.24333994999999997`, -0.13744537499999998`},            {-0.22632409999999997`, -0.11661089999999996`},            {-0.21717969999999998`, -0.10129116666666663`},            {-0.21341764999999996`, -0.09311782500000006`},            {-0.16110257499999997`, 0.0714712708333333`},            {-0.1087875`, 0.23606036666666666`},            {-0.3035939666666666`, -0.33778329166666676`},            {-0.32013196666666666`, -0.3382103666666666`},            {-0.33230609999999994`, -0.33689943333333333`},            {-0.3425458333333333`, -0.3340813000000001`},            {-0.3508735666666666`, -0.32955116666666673`},            {-0.3558780916666666`, -0.3249068666666666`},            {-0.36091372499999996`, -0.3168879333333333`},            {-0.3634749`, -0.3093918333333333`},            {-0.365004675`, -0.3005295333333334`},            {-0.36551249999999996`, -0.29021463333333336`}}          ],           {{-0.14929987960875826`, -1.065591641272026`},            {1.0642599291951356`, -0.14911329363618442`}          }        ]


title: Speeding up the numerical integration of a certain function

text: I'm using the following function               f[t_] :=        3/4 t^-3 NIntegrate[(x^4*Csch[x/2]^2), {x, 0, t},          Method -> {Automatic, "SymbolicProcessing" -> 0}];      I have to apply large lists against it as well as use it in fitting routines like `NonLinearModelFit`. I can already significantly reduce the evaluation time by switching off the SymbolicProcessing option. Is there any other way to speed up the evaluation of `f` significantly? A close to real-case example would be the following:               data = Table[250/t, {t, 0.1, 3000, 0.1}];     f /@ data; // AbsoluteTiming      For sure, the minimum and maximum argument of the function would be {0.001, 100000}. //Edit Sorry for the confusion about Min,Max arguments. The range can vary, but in the worst case Min,Max of data is `{0.001, 100000}`. Therefore any simplification has to yield the correct result within that Range. //Edit2 Symbolical Integration would be perfect, but due to the `PolyLog` functions, relative errors become very large, especially for `t>1000` and very small t. Also for me this is even more time consuming.               f[t_?NumericQ] :=  3 t^-3 NIntegrate[(x^4 Exp[x])/(Exp[x] - 1)^2, {x, 0, t}, Method -> {Automatic, "SymbolicProcessing" -> 0}]     h[t_] = 3/4 t^-3 Integrate[x^4 Csch[x/2]^2, {x, 0, t}, Assumptions -> t \[Element] Reals && t > 0]     LogLogPlot[{Abs[h[x] - f[x]]/f[x], 10^-4}, {x, 0.001, 100000}, PlotRange -> Full]     LogLinearPlot[{Abs[h[x] - f[x]]/f[x], 10^-4}, {x, 0.001, 100000}]     data = Table[250/t, {t, 0.1, 3000, 0.1}];     f /@ data; // AbsoluteTiming     h /@ data; // AbsoluteTiming      I would like to have the relative error less than 10^-4.


title: Convert BSplineFunction into two Interpolating Functions

text: Is there a way to decompose a `BSplineFunction` output into two functions `x[t]`, `y[t]` parametrizing the curve `BSplineFunction[{{x1, y1}, {x2, y2}, ...}][t]` in a form which allows easy calculation of derivatives of arbitrary order of `x[t]` and `y[t]` and of composite functions which use `x[t]` or `y[t]` like               f[t] = y''[t]/Sqrt[x'[t]^2+y'[t]^2]     f''[0.5]      etc. ? Edit: I would also like to do this avoiding `SetDelayed` as much as it's possible.


title: Do people actually use UpValues?

text: I know what they are and how to define them. They have to serve some purpose - else why include them? But I never used them and all examples on this site and the docs never show a practical use of `UpValues`. Can someone give me an example to see when they are actually needed?


title: Functional Programming: modify EdgeList based on condition

text: I have a simple functional programming question: I have a simple EdgeList defined in Mathematica, I would like to modify the value of certain element of the list based on a condition. I see how to define the conditional `If`, but I don't know how to "scan" my EdgeList and modify the elements so that it returns another EdgeList. Could someone show me a simple example on how to accomplish this in _Mathematica_?


title: Renaming files of form FileName(i).csv to NewNamej(k).csv where j increments and k resets to 1 when there is a jump in i?

text: **Edit up top:** The accepted answer works splendidly except I had to add `//ToExpression` to the end of the definition of `ns` given by the submitter. Without this, the numbers were not actually being treated as numbers by Mathematica. **Original Question Follows:** Sorry for the very verbose title, but I couldn't think a very succinct way to put it. I have a list of file names:               samplenames = {"FileName(2).csv", "FileName(3).csv",      "FileName(4).csv", "FileName(10).csv", "FileName(15).csv",      "FileName(16).csv", "FileName(17).csv", "FileName(18).csv",      "FileName(25).csv", "FileName(30).csv", "FileName(31).csv"};      I would like some code to take these and rename them so that the output is               {"NewName1(1).csv", "NewName1(2).csv", "NewName1(3).csv",      "NewName2(1).csv", "NewName3(1).csv", "NewName3(2).csv",      "NewName3(3).csv", "NewName3(4).csv", "NewName4(1).csv",      "NewName5(1).csv", "NewName5(2).csv"}      So you can see what happens: The number in parentheses is incremented starting from 1 until there is a jump in the original list of file names. At this point, the number NOT in parentheses is incremented by 1 in the new name and the number in parentheses restarts from 1 again. To make the language easier to follow, let's call the two forms "FileName(i).csv" and "NewNamej(k).csv". I can imagine there's some way to do this by splitting the list of file names using Split, maybe in a way similar to the "Split at Jumps" example found in the documentation (although I'm not familiar with working with strings), and then using the index of the sublist to determine j. The index within each sublist could be used to determine k. Of course, there may be far better ways to do it and I am open to any solutions. I have almost no experience with string manipulation in Mathematica so the syntax is a little scary for me right now. I would greatly appreciate as much detail as possible about what is going on in any suggested solutions. Lastly, I'd be willing to forgo the full version of what I'm asking for, as long as I could just batch rename any directory of files of the form "FileName(i).csv" to "NewName(j).csv" where j starts from 1 and increases in increments of 1 regardless of where i starts from and how it increments. Figure I'd ask for the stars first though :)


title: How do I solve for the real and complex parts of an equation simultaneously?

text: If I were to have an equation, say something similar to...               (1-Sqrt[x - I y])/(1+Sqrt[x - I y]) = A + I B      Where I = Sqrt[-1], is there a way for Mathematica to give me A = ... and B = ..., i.e. both real and imaginary parts of the equation simultaneously?


title: How to set MouseAppearance to void?

text: I need to get an output graphics which does not show mouse cursor over itself. I didn't find a corresponding value in `MouseAppearance` documentation and ended up with               MouseAppearance[Graphics@Circle[{0, 0}], Graphics[{Opacity[0.01], Point[{0, 0}]}]]      Is there a right way of doing this?


title: Plotting a graph with conditions

text: I am a newbie in Mathematica and is currently using Mathematica v9.0. I would like to consult if anyone knows how can I plot a given functions with conditions as shown below on how they look like. $$ g(x)= \left\{\begin{split} \frac{(\pi-x)}{2} &\text{, } 0 \leq x \leq \pi \\ -\frac{(\pi+2)}{2} &\text{, } -\pi \leq x < 0 \end{split}\right. $$ Then together in the same graph, I would like to plot its partial sums $S_{4}$ and $S_{8}$ based on the fourier series of the function $\sum^{n}_{k=1} \frac{\sin kx}{k}$. Note: If there is anyone who can edit the above latex to mathematics form, please do so as I don't know how to convert the above $\LaTeX$ code into mathematical wordings. Sorry about that.


title: Manipulate with formatted output

text: I would like to have 4 output fields for something like the following:               Manipulate[     n*x     n/x     n + x     n - x,     {n, 1, 10}, {x, 1, 10}, ControlType -> InputField]      but this just outputs all 4 calculations combined.


title: Gateaux (directional) derivatives and higher order differentials of a functional

text: I would like to calculate the Gateaux derivative of a functional (i.e. a function depending on functions). A simple example for the Dirichlet functional: $L(u(x))=\int_0^1 \frac{1}{2} (u'(x))^2 dx$ Its derivative in the direction of $v(x)$ is then calculated by: $dL[u](v)=\left.\frac{\partial}{\partial t}L(u(x)+t v(x))\right|_{t=0}=\int_0^1 u'(x) v'(x) dx$ In Mathematica I define the functional under consideration without arguments, like that:               L[u_] := Integrate[(1/2)*D[u, x]^2, {x, 0, 1}]      and in order to compute the derivative I use the following recipe:               d[functionalHead_, functions_, testfunctions_, independentvar_] :=       Block[{t},          myop[x_, y_] := Operate[x, y, 0];          (D[#, t] &)[functionalHead @@            Flatten[{             Inner[myop, Flatten[{functions}], Flatten[{independentvar}], List] +                 t*Inner[myop, Flatten[{testfunctions}], Flatten[{independentvar}],                  List]}]] /. t -> 0]          d[L, u, v, x]      > $\int_0^1 u'[x] v'[x] \, dx$ The funny list constructions in the definition of `d` is because I need to allow for multiple arguments that do not exclusively depend on the same space variables. Notice the the output functional is in a slightly different (more correct) form than the input functional. Now I would like to calculate higher order derivatives, here's the second one: $d(dL[u](v))[w]=\left.\frac{\partial}{\partial t}dL[u+t w](v)\right|_{t=0}=\int_0^1 w'(x) v'(x) dx$ and higher ones are then defined recursively (in this case the Dirichlet functional is quadratic and hence third and higher order derivatives are zero), and problems appear: If I want to use my function I have to redefine the output of the first derivative so that it looks like               dL[u_] := Integrate[D[u, x] D[v[x], x], {x, 0, 1}]      then we get               dL[u]      > >     0 >   but               d[dL, u, w, x]      > $\int_0^1 v'[x] w'[x] \, dx$ Since I need to calculate a bulk of higher (third, fourth, fifth etc.) derivatives of some nonlinear functionals the workaround of redefining without an argument is very ineffective. Does anybody have any idea how to make the process more systematic? EDIT: I came up with a solution. I redefined my derivative operator (now called `d1`) to use pure functions instead of symbols and produce a correct output which can then be used for an iteration. Here's the code:               d1[functionalHead_, functions_, independentvar_, i_: 1] :=       Block[{t,             testfunctions :=                 Flatten[ToExpression[StringReplace[ToString[{functions}],                         s : Except["," | "}" | "{" | "[" | "]"] .. :> s <>                                                                                ToString[i]]]]},                 myop[x_,y_]:=Operate[x,y,0];                (D[#,t]&)[functionalHead@@                           Flatten[                            Inner[Function,                             Flatten[{independentvar}],                             Flatten[                              Inner[myop, Flatten[{functions}],                                                                            Flatten[{independentvar}],List]                              +t*Inner[myop,Flatten[{testfunctions}],                                       Flatten[{independentvar}], List]                                   ],List]]]/.t->0];          d[functionalHead_, functions_, independentvar_, n_: 1] :=       Block[{i, tempfunc, tempfunctions, temp, dtemp},             tempfunctions = functions;             ToExpression[              ToString[temp]<>"["<>               StringReplace[ToString[{tempfunctions}],{s:"{"|               "}"..:>"",s:Except[","|"}"|"{"|"["|"]"]..:>s<>"_"}]<>"]:="                  <>ToString[functionalHead]<>"@@Flatten["               <>ToString[{tempfunctions}]<>"]"];             For[i = 1, i <= n, i++,                ToExpression[ToString[dtemp]<>"["                  <>StringReplace[ToString[{tempfunctions}],{s:"{"|                 "}"..:>"",s:Except[","|"}"|"{" |"["|"]"]..:>s<>"_"}]<>"]=d1["                 <>ToString[temp]<>","<>ToString[tempfunctions]<>","                 <>ToString[independentvar]<>","<>ToString[i]<>"];"];                ToExpression[ToString[temp]<>"["<>StringReplace[ToString[                 {tempfunctions}],{s:"{"|"}"..:>"",s:Except[","|"}"|"{"|                 "["|"]"]..:>s<>"_"}]<>"]="<>ToString[dtemp]<>"@@Flatten["                   <>ToString[{tempfunctions}]<>"]"];];             temp @@ Flatten[{tempfunctions}]]      The recursion step is sadly very messy: I wanted that the test functions are automatically named u1, v1 for the first derivative or u2 for the second and so on. This led me to a confusing manipulation of variable names which I was unable to do in a Mathematica-way so I transformed everything to strings, did the manipulation and pulled everything back as expressions. Note the `Except` command is being used because I also wanted to include greek and special characters as function names. The whole thing now works like so:               L[u_,v_,w_]:=Integrate[(1/2)*D[u[x],x]^2+(1/2)*D[v[x],x]^2,{x,0,1}]+(1/2)*w[s]^2     d[L, {u, v, w}, {x, x, s}]      > $\int_0^1 \left(u'[x] \text{u1}'[x]+v'[x] \text{v1}'[x]\right) \, dx+w[s] > \text{w1}[s]$               d[L, {u, v, w}, {x, x, s},2]      > $\int_0^1 \left(\text{u1}'[x] \text{u2}'[x]+\text{v1}'[x] > \text{v2}'[x]\right) \, dx+\text{w1}[s] \text{w2}[s]$ EDIT2: I've changed the title since it seems to be some discrepancies with respect to the terminology used in Wikipedia and in other references: to be concise, I am following the book from Ambrosetti and Prodi on nonlinear analysis.


title: Ignore missing data while doing a Mean

text: I want to compute the mean of a list while ignoring missing values, but I don't find a lot of information on how to deal with Missing data in Mathematica. I have a list like :               a = {{{0, 1}, {2, Na}} , {{0, 3}, {2, 5}}}       and I want to compute the mean but ignoring the Na values. So my output would be:               a = {{0, 2}, {2, 5}}       How can I do that? Thanks.


title: How to solve an operator form of an integral equation by iteration method?

text: How I can obtain the $n^{th}$ approximation of the following Operator form integral equation? $F(t)=A(t)+\int_0^tds B(s)F(s)$, where $A(t)=\bigg{(}\begin{matrix}t&0\\Cos(t)&1 \end{matrix}\bigg{)}$, $B(s)=\bigg{(}\begin{matrix}e^s&0\\0&e^{-s} \end{matrix}\bigg{)}$


title: How to find the values of $m$ so $A \cap B = \emptyset$ and $A \cup B = (-3,+\infty)$?

text: I have two intervals $A = (-3, m^2- 2]$ and $B=[m, +\infty)$. How to find the values of $m$ so that $A \cap B = \emptyset$ and $A \cup B = (-3,+\infty)$? I tried               {a = x > -3 && x < m^2 - 2, b = x >= m} {Reduce[a || b]}      and               {a = x > -3 && x < m^2 - 2, b = x >= m}     {Reduce[a && b]}      We have $A \cap B = \emptyset$ when and only when $$\begin{cases} m^2 - 2 > -3&\\ m^2 - 2 <m. \end{cases}$$ and $A \cup B = (-3,+\infty)$ when and only when $$\begin{cases} m^2 - 2 > -3&\\ m^2 - 2 \geqslant m. \end{cases}$$ Therefore we need to solve two systems of inequalities.


title: How I can make a menu with different graphs with modifiable parameters?

text: I want a user friendly window in which to have a menu where you can choose the chart you want to display, in which you can move parameters in order to note the width or height of the chart, but I try to declare a function which call control so that using TraditionalForm displayed as the user can understand it, but it is no longer displayed graph. My question is: How I can do to have a function declared prior to Manipulate plot and also will allow me to move the parameters?                 a = "Algebraicas";       b = "Trigonometricas";       c = "Tercer Grado";       y = w + 1;       Module[{myPlot}, myPlot[f_] := Plot[f[x], {x, -5, 5}];             Manipulate[             myPlot@selection,             {x, {a, b, c}, ControlType -> PopupMenu},                 {{selection, None}, selChoice, ControlType -> SetterBar},                     {selChoice, Which[                       x == a, {Sqrt[y] -> TraditionalForm[Sqrt[y]] &, #^2 &},                       x == b, {#^3 &, Abs@# &},                       x == c, {Sin, Cos}]}, None}]]      but I need to do is you can move the graph parameters, such as:               Manipulate[Plot[Sin[a x + b], {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]      Now I want to have a label on each graph which is observed as the values are updated manipulate the slide, this is the code that I have.                Clear[a, b, c];      types = {"Algebraicas", "Logaritmicas y exponenciales",        "Trigonometricas", "Trigonometricas Inversas", "Hiperbolicas",        "Hiperbólicas Inversas"};            Manipulate[          Plot[              selection /. {a -> a0, b -> b0}, {x, -5, 5},               PlotRange -> {{-5, 5}, {-10, 10}}, PlotStyle -> {Blue, Thick},               PlotLabel -> selection],      {type, types, ControlType -> PopupMenu},          {selection, Dynamic[type /.            Thread[types -> {{Sqrt[a x + b] -> TraditionalForm[Sqrt[a x + b]],             a x^2 + b, a (x - b)^3, a Abs[x - b]}, {Log[10, 1000],             Log[E, x], Log[1000.]}, {Sin[a x + b], Cos[a x + b],             Tan[a x + b]}, {Cot[a x + b], Csc[a x + b],             Sec[a x + b]}, {"a"}, {"b"}}]],            ControlType -> SetterBar},            {{a0, 1, a}, 1, 4}, {{b0, 0, b}, 0, 10}]      This is the new code.                  Clear[Seleccion, tipos, Tipo, selecciones, funciones, a, b, c, d, a0, \        b0, c0, d0]        tipos = {"Algebraicas", "Logaritmicas y exponenciales",         "Trigonometricas", "Trigonometricas Inversas", "Hiperbolicas",         "Hiperbólicas Inversas"};        funciones = {{c ( x/d + a) + b, c Sqrt[ x/d + a] + b,         c ( x/d + a)^2 + b, c (x/d + a)^3 + b, c Abs[x/d + a] + b,         c/(x/d + a) + b, c/(x/d + a)^2 + b}, {c Log[E, x/d + a],         c Log[2, x/d + a] + b, c Log[(1/2), x/d + a] + b,         c Exp[x/d + a] + b, c 2^(x/d + a) + b,         c (1/2)^(x/d + a) + b}, {c Sin[x/d + a] + b, c Cos[x/d + a] + b,         c Tan[ x/d + a] + b, c Cot[x/d + a] + b, c Csc[x/d + a] + b,         c Sec[ x/d + a] + b}, {c ArcSin[ x/d + a] + b,         c ArcCos[ x/d + a] + b, c ArcTan[ x/d + a] + b,         c ArcCot[x/d + a] + b, c ArcCsc[x/d + a] + b,         c ArcSec[ x/d + a] + b}, {c Sinh[x/d + a] + b,         c Cosh[x/d + a] + b, c Tanh[ x/d + a] + b, c Coth[x/d + a] + b,         c Csch[x/d + a] + b,         c Sech[ x/d + a] + b}, {c ArcSinh[ x/d + a] + b,         c ArcCosh[ x/d + a] + b, c ArcTanh[ x/d + a] + b,         c ArcCoth[x/d + a] + b, c ArcCsch[x/d + a] + b,         c ArcSech[ x/d + a] + b}};             Manipulate[Seleccion = tipos /. Thread[tipos -> funciones[[All, 1]]];        Dynamic@Plot[        Seleccion /. {a -> a0, b -> b0, c -> c0, d -> d0}, {x, -5, 5},         PlotRange -> {{-5, 5}, {-10, 10}}, PlotStyle -> {Orange, Thick},         PlotLabel ->         Style [Framed[        Pane[TraditionalForm[         Seleccion /. {a -> a0, b -> b0, c -> c0, d -> d0},          3], {Automatic, 40}]], White, Background -> Lighter[Gray]],         AxesLabel -> {Style[x, Large, Bold, Blue],         Style[y, Large, Bold, Blue]},         LabelStyle -> Directive[Black, Bold], ImageSize -> 540], {Tipo,         tipos, ControlType -> PopupMenu}, {Seleccion,         Dynamic[Tipo /.         Thread[tipos ->          With[{selecciones = Map[# &, funciones, {2}]}, selecciones]]],          ControlType -> SetterBar}, {{a0, 0, "a"}, -3, 3}, {{b0, 0, "b"}, -3,         3}, {{c0, 1, "c"}, -3, 3}, {{d0, 1, "d"}, -3, 3}]


title: Is it possible to use Mathematica to record sound and/or vision?

text: I think the title says it all. I know about `ImageCapture` which seems to capture stills. Can `ImageCapture` be made to capture a movie analogous to using say QuickTime player (and export to video format)? Likewise, if a microphone is connected to your computer (e.g. something that can be used by QuickTime to record) can Mathematica record sound? **Edit** Because I was aware of `ImageCapture` prior to posting this question I did some searches looking for functions that may involve recording e.g.:               ?*ecord*      But got no hits. It is frustrating to find that capturing an image gets its own intuitive function name whereas recording sound does not. But even more frustration that on my Mac I get this:               SystemDialogInput["RecordSound"]     SystemDialogInput::unsupt: "The \!\(\"RecordSound\"\) dialog type is not currently supported on this platform. "      **Edit 2** Thanks for the frame by frame type capture solutions posted below but I was hoping for a more direct (native) solution -- even if undocumented -- that would be analogous to me just controlling QuickTime from within Mma (which can be done). As for recording sound, does anyone know why `SystemDialogInput["RecordSound"] ` isn't supported on Macs and what potential methods exist for Mac? thanks Mike **Edit 3** In Version 9 `SystemDialogInput["RecordSound"]` works on Macs.


title: Efficiently deleting rows in many large text files

text: I have 500 text files each of about 200000 rows. I need to delete one row in each of them as fast as possible (later such operations will repeat). What is the best way to do this with Mathematica? Solutions using `NETLink`, `JLink` etc. are welcome! **Update:** I have found a solution for C#: "Efficient way to delete a line from a text file" but I don't know how to adapt it for using through `NETLink`. Another option probably is to use the `java.io.RandomAccessFile` class in Java but I am not very familiar with Java and `JLink`. Any help will be appreciated!


title: Grid - Item - Alignment to decimal problem

text: Still present in version 10. * * * I've run into a `Grid` layout problem for which I don't know a solution. I want to specify alignment to a specific character such as a decimal _and_ an `ItemSize` on a per-`Item` basis. When I try to do this the decimal ends up on the right edge of the field rather than somewhere in the middle. My application is part of a larger, more complex Grid layout but here is a simple illustration:               gridIt[itemopts__] :=      Module[{x},       x = {{1.234, 12.34}, {123.4, 1234.}, {1234, 1.234}};       x = Map[Item[#, itemopts] &, x, {2}];       x = Prepend[x, {"Title", SpanFromLeft}];       Grid[x, Alignment -> {Center, Center}, Dividers -> All]      ]          gridIt[Alignment -> "."]      ![Mathematica graphics](http://i.stack.imgur.com/wiCqi.png)               gridIt[Alignment -> ".", ItemSize -> 4.4]      ![Mathematica graphics](http://i.stack.imgur.com/J2LI3.png) Why does this happen and how can I work around it?


title: How to make all values positive?

text: So I have a list of data that contain both positive and negative values, and I am wondering what I have to do in order to make all the numbers positive.


title: Create a CDF file with a plot that cannot be edited by double-clicking

text: I have created a CDF file that contains a `Manipulate` object with a plot. I intend to embed the file in a web site, so that users can use interactive sliders to change the parameters of the plot. My problem is that when opening the CDF file in a browser, the user can double-click on the plot and edit it (move lines, move points, etc.). The only interactive content I want in the web site are the sliders produced by `Manipulate`. How can I create a CDF file that doesn't allow the user to edit the plot?


title: Grid - sizing and spacing problems with spanning cells

text: I am trying to set up a `Grid` with cells that span two rows and are centered on those rows, but I am having troubles with the sizing and, therefore, spacing of the elements. For illustration I can get something that has at least part of the layout right by using `TableForm`, but this will not work in practice because the columns do not align, there is no `Dividers` option, `Item` is not fully supported, etc.               dot = Graphics[{Pink, Disk[]}, ImageSize -> 40];          dat = {{"Angel Falls", "17.7 m", "0.82", "9.2"},        {"Bridalveil Fall", "6.9 m", "0.94", "9.8"},        {"Cascata delle Marmore", "8.25 m", "0.87", "6.3"},        {"Cumberland Falls", "182.0 m", "0.87", "6.3"},        {"Dettifoss", "7.41 m", "0.88", "6.7"}};          table = {dot, {#, {##2}}} & @@@ dat;          TableForm[table, TableSpacing -> None]      ![Mathematica graphics](http://i.stack.imgur.com/JGphG.png) Notice that the pink dot is roughly centered between the two lines, and there is no excess space around the text. If the dots are resized the alignment is retained: ![Mathematica graphics](http://i.stack.imgur.com/wXQlW.png) Now compare the result of `Grid`:               {       {dot, Item[#, Alignment -> Left], \[SpanFromLeft], \[SpanFromLeft]},       {\[SpanFromAbove], Item[#2, Alignment -> "."], #3, #4 "cms"}     } & @@@ dat;          Grid[Join @@ %,      Alignment -> {Center, Center},      Spacings -> {Automatic, 0},      Dividers -> All     ]      ![Mathematica graphics](http://i.stack.imgur.com/BbbrU.png) The spacing and alignment is all wrong because the second element on the first row of each pair (e.g. "Angel Falls") is given the vertical size of the dot. If the dots are a different size the alignment changes: ![Mathematica graphics](http://i.stack.imgur.com/z7It8.png) How can I get the vertical alignment shown in the `TableForm` example while retaining all the features of `Grid`? To clarify, it is fine if the lines end up further apart when the size of the dot is increased, but they should remain centered. Also, I expect that when the size of the dot is twice as high as a line of text (or other objects) that there will be no extra space. To fully answer this question I need a way for the cell containing "Angel Falls" to have _less height_ than the dot.


title: How can I add points on a plot?

text: I have a list of points that I want to a plot, but I can't figure out how to do it with `Epilog`. Here's the code I have so far:               Gammaconst = 1.67;      Pa = 975.452; Pb = 975.452; Pc = 384.269; Pd = 384.269;     Ta = 355; Tb = 355; Tc = 295; Td = 295;     R = 8.3144; n = 0.000137;     V1 = 4.97*(10^-6); V2 = 2.736*(10^-5); V3 = 2.902*(10^-5); V4 =       6.63*(10^-6);     P[V_, T_] := n*R*T/V;     Plot [{P[V, T = 355], P[V, T = 295]}, {V, 0.000005, 0.00003       }, AxesOrigin -> {0, 0},       AxesLabel -> {"Volume (\!\(\*SuperscriptBox[\(m\), \(3\)]\))",         "Pressure (Pa)"},      Epilog -> {Line[{{V1, P[V1, 355]}, {V4, P[V4, 295]}}],        Line[{{V3, P[V3, 295]}, {V2, P[V2, 355]}}]}]     Plot[{{V1, 101325 - Pa}, {V2, 101325 - Pb}},       PlotStyle -> PointSize[0.015]]      I get a nice graph and I want to mark a few points on it to show where they are. After the first `Plot` command is a second plot containing the points I was testing with. I get an error mesage that says > "PLot called with one argument, two expected." I am now utterly convinced that the people who write error messages don't want anyone to understand them. Sorry, but this is just frustrating as all getout because the whole thing should take an hour and I have been messing with this all bloody day.


title: 3D Printing in Mathematica Tutorials

text: Are there thorough tutorials on 3D printing for _Mathematica_? It seems that being able to export _Mathematica_ files for 3D printing is unfortunately still a novelty, but it's vital for my business plans. It would be much appreciated to specifically make                ContourPlot3D[3 Sin[E^x] == (x^2 + y^2 + z^2)^(.5), {x, -1, 1}, {y, -4, 4}, {z, -4, 4}]      3D printable for MakerBot. _Mathematica_ would not allow using `Thickness` for `ContourPlot3D`, but did for `ParametricPlot3D`.


title: Truncated Distribution Parameter Search Produces Singular Jacobian Using FindRoot

text: I'm trying to find the 2 parameters of a truncated Weibull distribution using version 10 and FindRoot. I would like to truncate the distribution between t =0 and t = 3600 with the probability of survival,POS(360)=0.7 and POS(1080)=0.6 If this is not possible using WeibullDistribution, any other smooth distribution will work. My code is below for the non-truncated, tmax = Infinity case which is easier to solve.               Remove["Global`*"]     {ta = 360., ra = 0.70};     {tb = 1080., rb = 0.60};     tmin = 0;     tmax = \[Infinity];     plotmax = 4320;     dist = TruncatedDistribution[{tmin, tmax},      WeibullDistribution[\[Beta], \[Eta]]];     soln = FindRoot[{SurvivalFunction[dist, ta] == ra,      SurvivalFunction[dist, tb] == rb}, {{\[Beta], .32}, {\[Eta],       8427.}}, Method -> "Newton"];     {\[Beta] = soln[[1, 2]], \[Eta] = soln[[2, 2]]}     dist = TruncatedDistribution[{tmin, tmax},      WeibullDistribution[\[Beta], \[Eta]]];     pdf[t_] := PDF[dist, t]     cdf[t_] := CDF[dist, t]     ps[t_] := SurvivalFunction[dist, t]     plot1 = Plot[pdf[t], {t, 0, plotmax}, Frame -> True,      FrameLabel -> {"Time", "PDF"},      FrameTicks -> {Range[0, plotmax, 720], Automatic, None, None},      PlotRange -> All, PlotLabel -> "PDF"];     plot2 = Plot[cdf[t], {t, 0, plotmax}, Frame -> True,      FrameLabel -> {"Time", "CDF"},      FrameTicks -> {Range[0, plotmax, 720], Automatic, None, None},      PlotRange -> {All, {0, 1.05}}, PlotLabel -> "CDF"];     plot3 = Plot[ps[t], {t, 0, plotmax}, Frame -> True,      FrameLabel -> {"Time", "Probability  of Survival"},      FrameTicks -> {Range[0, plotmax, 720], Automatic, None, None},      PlotRange -> All, PlotLabel -> "Probability of Survival"];     GraphicsRow[{plot1, plot2, plot3}, ImageSize -> 800]     check1 = {ta, ps[ta]}     check2 = {tb, ps[tb]}     sse = (ra - ps[ta])^2 + (rb - ps[tb])^2      The solution to this non-truncated case is Beta = 0.326961 Eta = 8426.8 and these are the plots, so far so good. ![enter image description here](http://i.stack.imgur.com/ectFp.jpg) Next I truncate to a tmax = 50000 and it found a solution, Beta = 0.284 Eta = 394334 Next I truncate to tmax = 37500 (note I really need 3600) and I get a this error: FindRoot::jsing: "Encountered a singular Jacobian at the point {[Beta],[Eta]} = {0.2,1.4*10^13}. Try perturbing the initial point(s)" I've tried different initial points to no avail. Does anyone have a suggestion ? If this can be made to work using another smooth distribution that would be fine. I chose the Weibull for its flexibility. Thanks for any suggestions.


title: Testing a package in Mathematica 9

text: I am in the process of writing a package, but my way of testing it just seems wrong and inefficient. Each time I edit the .m file, I save it, quit the kernel, call the package in a separate notebook and proceed to test. Is there a more efficient way to test a package without having to save/quit kernel/rerun everything?? Thanks


title: Difficult to solve the equation using FindInstance and not able to solve it numerically

text: I hope to find the range of `a` which leads to non-zero solution of `H` when you are given a specific value of B. And I hope to get the the corresponding B, range of a and number of solutions in a table. All the variables should be real. I tried to do it, the most difficult part is to determine the number of solutions when changing the value of a. And it is also difficult when I tried to manually change the value of a to get a range of the solution. Is there any systematic way of doing this ? ![enter image description here](http://i.stack.imgur.com/oC3Hb.png)


title: Combination and Permutation

text: How could I obtain the list of all the groups of 5 numbers taken from `Range[12]` such that the 2 lists have an empty intersection : `{{1,2,3,4,5},{6,7,8,9,10}}` would be a solution while `{{1,2,3,4,5}, {5,6,7,8,9}}` should be rejected as 5 is common to both. I am currently trying to do so using `Position` of empty `Intersection` very unsuccessfully.               allCombinations =       DeleteDuplicates@(Sort /@ Permutations[Range[12], {5}])          Function[base,       Flatten[        Position[         Intersection[allCombinations[[base]], allCombinations[[#]]] & /@           Drop[Range[792], {base}], {}], 1]] /@ Range[792]      With which I am trying to obtain the position of the lists in allCombination s, but I still get duplicates...


title: How to modify the elements of a list in a loop?

text: I have a list with points coordinates. And I'm trying to traverse it and perform some matrix operations on each point. But I have a problem with storing modified points in the initial list instead of the original points. Here is the complete entry point example:               (* the matrix of the linear operator of rotation around OX axis *)     rx = {         {1, 0, 0, 0},         {0, Cos[ax], -Sin[ax], 0},         {0, Sin[ax], Cos[ax], 0},         {0, 0, 0, 1}     };          (* translation matrices *)     t1 = {         {1, 0, 0, -j},         {0, 1, 0, -k},         {0, 0, 1, -l},         {0, 0, 0, 1}     };     t2 = {         {1, 0, 0, j},         {0, 1, 0, k},         {0, 0, 1, l},         {0, 0, 0, 1}     };          (* projection onto OXY plane *)     f = {         {1, 0, 0, 0},         {0, 1, 0, 0},         {0, 0, 0, 0},         {0, 0, 0, 1}     };          points = {         {{100},{0},{0},{1}},         {{155},{0},{0},{1}}     };          ax = Pi/4;     j = 100;     k = 100;     l = 0;      And this is my solution to it, which I try to improve               For[i1 = 1, i1 < 3, i1++, {         item = t1 . Part[points, i1];         item = rx . item;         item = t2 .item;         item = f . item;         xP = N[Part[item, 1]];         yP = N[Part[item, 2]];         zP = N[Part[item, 3]];         homogP = N[Part[item, 4]];         Print[{xP, yP, zP, homogP}];     }];      the output is:               {{100.},{29.2893},{0.},{1.}}          {{155.},{29.2893},{0.},{1.}}      And this seems to be correct. But if I change the `For` loop with the solution inspired by Alexei Boulbich               Map[{t1.#, rx.#, t2.#, f.#, N[#]} &, points];     Print[points];      I get this:               {{{100},{0},{0},{1}},{{155},{0},{0},{1}}}       That is the original list without any operations applied.


title: Why is FileNameJoin not working?

text: I can not figure out why the code below doesn't work?               aaa >> FileNameJoin[{Directory[],"input"}]      error message came out saying > OpenWrite::noopen: Cannot open FileNameJoin[{Directory[],"input"}]. If I evaluate               FileNameJoin[{Directory[],"input"}]      directly, then I can get               C:\Users\m&p\AppData\Local\Temp\input      And the code below always works               aaa >> "C:\\Users\\m&p\\AppData\\Local\\Temp\\input"


title: How do you ContourPlot3D an implicit function of x,y, and z?

text: This is what I am trying to do:               ContourPlot3D[4 Log[x^2 + y^2 + z^2] == 1, {x, -10, 10}, {y, -10, 10}, {z, -10, 10}]      but all I get is the empty box. Can anyone help me? Thanks!


title: Styling ticks, axes and other elements in a Plot of a step function

text: To display the effect of uniform quantization (step size Q) I would like to draw a curve as shown below ![enter image description here](http://i.stack.imgur.com/ohlaS.jpg) I tried this using               Plot[Round[n], {n, -3, 3},        Ticks -> {{-3, -2, -1, 1, 2, 3}, {-3, -2, -1, 1, 2, 3}},        AspectRatio -> Automatic, ExclusionsStyle -> Opacity[1],        AxesLabel -> {Input, Output}]       but couldn't get it to look perfectly as shown. As shown above tick lebels appear on different sides of the Y-axis. Can this be attained too?


title: CharacterEncoding failed when Import or Export as pdf

text: folowing is the content my test nb File: pdfTest.nb, contain some chinese characters:               SampleCode1:pdf输入不正常。      After Save as or Export, pdf file looks well for the Chinese content. But when Import, it seems become WindowsANSI Encoding. When I Import the pdf file               Import["E:\\Users\\Quaternions\\Desktop\\pdfTest.pdf","Plaintext",CharacterEncoding->"CP936"]      Show this               SampleCode2:pdfÊäÈë\.b2»Õý\.b3£¡£      When I Export and Re-Import the .txt file, it works fine.               Import[Export["temp1.txt",%,CharacterEncoding->"WindowsANSI"],CharacterEncoding->"CP936"]      good result:               pdf输入不正常。      my-enviroment is windows 8 mathematica 9.0 chinese version.               $CharacterEncoding     CP936      Maybe someone is hard to test. My question is: 1: How to directly import the pdf file contain chinese characters and show well. 2: if the solution for question 1 is not possible, is it necessary to Export using CharacterEncoding->"WindowsANSI" and re-Import? , ie. How to convert the characterEncoding in notebook without the export manipulation? Convert SampleCode2 to SampleCode1 _Futhermore, When I import some pdf generated by Tex or obtain other where, also will encouter with CharacterEncoding Problem. I think Import Pdf File should better add an Elements that Import pdf pages as Rasterized image list._


title: “Strange” behavior of Rule

text: According to the Help > lhs->rhs evaluates rhs immediately. How to understand the output of the following code?               ClearAll@x;     {1, 3.5} /. x_?IntegerQ -> {x}      Output is               {{1},3.5}      Since `Mathematica` evaluate the rhs **immediately** , I think the “correct” output should be this               {{x},3.5}      And of course, if x has `OwnValues`, the output will be changed.               x=”why”;     {1, 3.5} /. x_?IntegerQ -> {x}      Output is               {{"why"},3.5}      As expected. In my opinion, the two examples expose the contradictions. In the first one, `Rule` behaves like `RuleDelayed`; it relates the local x with global x. (The color of the two variables in front-end tells me this.) But in the second one, `Rule` makes a clear distinction between the local and global. (There are also something similar between `Set` and `SetDelayed`) Why does this happen? Did I misunderstand the mechanism? ## Update What I'm really confusing is Why **sometimes** _Mathematica_ **does not distinguish** the global x and the local x in Rule. ## Solution As Aky has metioned in his comments and answer. The documentiation says, > Symbols that occur as pattern names in _lhs_ are treated as local to the > rule. This is true when the symbols appear on the right-hand side of `/;` > conditions in _lhs_ , and when the symbols appear anywhere in _rhs_ , even > inside other scoping constructs. So if `x` doesn't have `OwnValues`, then the `Head` of `x` is `Symbol` and the name of x is the same as pattern name, as the documentation said , _Mathematica_ will treat the two 'x's as the same. If `x` has `OwnValues`,take `x=y` for example, (`Head` of `y` is also `Symbol`) Even if `x` (actually y) is `Symbol`, the "name" of x is y which is different from the pattern name. So in the following case,               x=y;     {1,3.5}/.x_?IntegerQ->{x}      _Mathematica_ will return `{{y},3.5}` not `{{1},3.5}`. Thanks for everyone's attention:)


title: How do I limit the iterations in a while loop?

text: Is there a way to limit the number of iterations in a while loop? Right now I am cleaning up the code, and for now if I make a mistake, the loop keeps going forever. I'd like to be able to limit the number of times it will run through while I am working on it. Is that possible?


title: ContourPlot from Vector Data

text: I have data in the form of x, y, vx, vy where vx and vy are components of the velocity vector at point x,y. I want to plot a contourplot of this. How can I do that since contourplot asks for three values?               testBC = Import["...test.dat", "Table", "IgnoreEmptyLines" -> True];     testBCx = testBC[[All, 1]];     testBCy = testBC[[All, 2]];     ux = testBC[[All, 3]];     uy = testBC[[All, 4]];     u = Transpose[{ux, uy}];     testbdry = Transpose[{testBCx, testBCy}];     ListContourPlot[testbdry, u]      I am not sure which one is right, ContourPlot or ListContourplot. I am trying to look for something that provides "heat plotting"


title: Clustering a set of points

text: I have a set of 2D points in the square defined by `{-1, -1}` and `{1, 1}`. These points typically form compact groups. I need to break them into clusters in such a way that the rectangular bounding boxes of the clusters will not overlap. The bounding boxes are expanded by a pre-specified margin, denoted `dist`. I managed to implement this by computing the pairwise Manhattan distance, building a corresponding graph and taking the connected components of the graph (see attached code). I was hoping that there would be a simper solution which avoids computing the complete pairwise distance matrix. I tried using `FindClusters`, but not having any experience with the underlying methods I did not manage to get it to return the appropriate number of clusters (it typically lumps everything together, even when points are "visually" separate). So the question is: _Is it possible to implement this using`FindClusters`?_ The key is in choosing the correct `Method` option for `FindClusters`, which is unfortunately not documented in a way that's easy to understand for someone not familiar with these methods. Requirements: The clustering does not need to be precise. If the method returns a bit fewer clusters than what I show in the image below, that's okay. I need the results for a heuristic decision anyway. But it should not lump together things which are rather far compared to the size of the visually perceived clusters. It is very easy for us humans to recognize these clusters, and I'd like to get the computer to give me same output one would naturally construct by hand after looking at the image. All points sets I have have a very similar structure to the one I show below, but the groups may have different size scales. This is why it makes sense to ask "I'd like to have the clusters similar to what I perceive visually". The method must work without any user intervention (manual estimation of parameters). * * *               pts = Import["http://ge.tt/api/1/files/7sHEVob/0/blob?download", "WDX"];          dist = 0.01;          comp = ConnectedComponents@        AdjacencyGraph[         UnitStep[2 dist - Outer[ManhattanDistance, pts, pts, 1]]];          Graphics@MapIndexed[       With[{p = pts[[#1]]}, {{GrayLevel[.9],            Rectangle[{Min[p[[All, 1]]], Min[p[[All, 2]]]} -              dist, {Max[p[[All, 1]]], Max[p[[All, 2]]]} +              dist]}, {ColorData[3][First[#2]], Point[p]}}] &, comp]      Click for a larger image: ![](http://i.stack.imgur.com/dvAjz.png)


title: How to make 3D object smooth?

text: _This thread considers mathematical methodshere to make the 3D object smooth but this question consider how to achieve the goal of smoothing a 3D object in Mathematica._ I want to get smoother geometrical objects, some messing up here. Suppose for example a tetrahedron where I would like to make the corners rounded with either convolution or interpolation. I would have to select two control points on different faces and then select one adjusting point -- I could use a NURBS aka spline approximation with a polynomial then aka Mathematica's BezierCurve[...] command. Now I am trying to do a ready command that would do this for me without me traversing different vertices and making sure of selecting right faces for control/adjusting points. Example data about the coordinates with the tetrahedron's faces here. **Does Mathematica have some ready function to do Interpolation or Convolution for geometric objects?** * * * I think the by-far-easiest solution is to use Convex hull but it hides some information if you have a lot of details. This is an answer in progress. **Different methods**   1. Convex hull of a 3D object?


title: Is there a callback for notebook exit?

text: I know that `$Epilog` is called when _Mathematica_ is exited; is there a callback upon exiting the notebook? If so, what is it?


title: A more efficient way of fitting a non-linear model that returns an entire list?

text: I have a function that takes two parameters, `del` and `nu`, and returns a list `npoints` long with a bin-width of `dt`:               ktDynaList[npoints_?NumericQ, dt_?NumericQ, del_?NumericQ, nu_?NumericQ] :=       Module[{alphaN, Npad, tt, expwei, gg, padgg, ff, FF, dkt},       alphaN = 10;       Npad = 2*npoints;       tt = Table[dt i, {i, 0, Npad - 1}];       expwei = Exp[-(alphaN/(npoints*dt))*tt];       gg = (1/3)*(1 + 2*(1 - del^2*tt^2)*Exp[-0.5 del^2 *tt^2]);       padgg = PadRight[Take[gg, npoints], Npad];       ff = Fourier[padgg*expwei*Exp[-nu*tt], FourierParameters -> {1, 1}];       FF = Exp[-nu dt]*ff/(1 - (1 - Exp[-nu dt])*ff);       dkt = Take[InverseFourier[FF, FourierParameters -> {1, 1}]/expwei, npoints];       dkt      ]      I want to fit this function to a dataset using `NonlinearModelFit`, so I have an edited version that returns one value from this array at a particular abscissa `t`:               ktDyna[npoints_?NumericQ, dt_?NumericQ, del_?NumericQ, nu_?NumericQ, t_?NumericQ] :=       Module[{alphaN, Npad, tt, expwei, gg, padgg, ff, FF, dkt},       alphaN = 10;       Npad = 2*npoints;       tt = Table[dt i, {i, 0, Npad - 1}];       expwei = Exp[-(alphaN/(npoints*dt))*tt];       gg = (1/3)*(1 + 2*(1 - del^2*tt^2)*Exp[-0.5 del^2 *tt^2]);       padgg = PadRight[Take[gg, npoints], Npad];       ff = Fourier[padgg*expwei*Exp[-nu*tt], FourierParameters -> {1, 1}];       FF = Exp[-nu dt]*ff/(1 - (1 - Exp[-nu dt])*ff);       dkt = Take[InverseFourier[FF, FourierParameters -> {1, 1}]/expwei, npoints];       dkt[[ Round[t/dt] ]]      ]      Now, this can be passed to `NonlinearModelFit`, and will fit a dataset rather successfully. However, the problem is that in its current state it is incredibly inefficient, as the `dkt` list is recalculated for every single abscissa. I'm trying to find a way of storing the `dkt` array such that it does not need to be fully recalculated for each `t` value, and am wondering if anyone in the community has encountered a problem of this type before? My current thoughts are either   1. An If statement at the beginning of the function which checks if the parameters `del` or `nu` have been varied since the last iteration - if they haven't then one can just return the list element from the previously calculated `dkt` list and avoid a lot of calculation steps. My problem here is that _Mathematica_ doesn't appear to have static variables (that I know of). Is there any way around this?   2. Some sort of flag system that can be passed between function calls which indicates if the full calculation needs to be performed, or if a previously stored list element can be returned. Or is there some other solution that doesn't require the use of `NonlinearModelFit`?


title: How to Merge Date and Time?

text: Given the following time series data where row is date and column is time intervals.                  rawdata = {{"Date", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30",            "11:00", "11:30", "12:00", "12:30",            "13:00"}, {{2011, 1, 4, 0, 0, 0.}, 47., 59., 71., 77., 115., 111.,            103., 75., 101., 121., 135.}, {{2011, 1, 5, 0, 0, 0.}, 20., 51.,            33., 68., 97., 82., 101., 78., 104., 119.,            137.}, {{2011, 1, 6, 0, 0, 0.}, 3., 39., 61., 59., 63., 108., 66.,            85., 108., 119., 114.}, {{2011, 1, 7, 0, 0, 0.}, 13., 55., 74., 70.,            105., 95., 71., 82., 86., 113., 124.}}      I can't figure out how to merge date and time together so that my desired output will be               output = {{Date}, {{2011, 1, 4, 8, 0, 0.}, 47.}, {{2011, 1, 4, 8, 30, 0.},        59.}, {{2011, 1, 4, 9, 0, 0.}, 71.}, ..., {{2011, 1, 6, 13, 0, 0.},        124}}      Thank you


title: replacement rules from a pattern and a matching expression

text: (This seems to be a very basic necessity in a language having pattern-matching capabilities such as Mathematica, yet I struggled for many hours to find a common solution to this problem.) Suppose there is a pattern with some of its sub-elements named, and there is an expression that matches it. How do I generate a list of replacement rules that maps sub-element names into their values in the matching expression? E.g.,               patt=f_[_, s_, x___];     expr=ab[c, d, e, f];     mkMatchRules[expr,patt]     >> {f -> ab, s -> d, x -> Sequence[e, f]}      I have written a solution to this,               collectAllPattVars[patt_] := Union[Map[Part[#, 1] &,       Cases[patt, _Pattern, {0, Infinity}, Heads -> True]]];     mkMatchRules[expr_, patt_] := Module[       {pattVars = collectAllPattVars[patt], mkRhs},       mkRhs = Block[{$}, ReleaseHold[Hold[patt :> $] /. $ -> With[{$ = Map[List, pattVars]}, $]]];        If[MatchQ[expr, patt],          MapThread[Rule[#1, If[Length[#2] == 1, #2[[1]], Sequence @@ #2]] &,                     {pattVars, Replace[expr, mkRhs]}],          $Failed]];      which produces the result in the example above However, I hope somebody knows a more elegant way to do this.


title: Plotting ContourLabels on ContourPlot3D

text: Is there a way to add ContourLabels on ContourPlot3D ? (tried in Mathematica 9) I tried doing the following code :               f[x1_, x2_, x3_] := x1 + x2^2 + x2 x3 + 2 x3^2     h[x1_, x2_, x3_] := x1^2 + x2^2 + x3^2 - 1     a = 1;     ContourPlot3D[      h[x1, x2, x3] == 0,      {x1, -a, a}, {x2, -a, a}, {x3, -a, a},      MeshFunctions -> {f[#1, #2, #3] &},      PlotPoints -> 20,      ContourLabels -> Automatic      ]      It throws the following error :               ContourPlot3D::optx: "Unknown option ContourLabels->Automatic in ContourPlot3D[h[x1,x2,x3]==0,{x1,-a,a},{x2,-a,a},{x3,-a,a},MeshFunctions->{f[#1,#2,#3]&},PlotPoints->20,ContourLabels->Automatic]"      If I **removed** ContourLabels -> Automatic, it works fine and I get the following output ![ContourPlot's output when ContourLabels option is removed](http://i.stack.imgur.com/nMQJM.jpg) Edit 1: I would like to add the contours for the mesh (black) lines as shown in the figure


title: Updating the format style of input cells from an older/'pre-styled' notebook

text: I have been given a large notebook that was created in mathematica 6. It contains a structure of sections and subsections and the input text is formatted in an unusual (possibly just old) style (see screen grab below). ![original formatting](http://i.stack.imgur.com/ByUyG.jpg) My main aim is to update the formatting of the input cells to the standard mathematica 8 format as I find this format much easier to read/debug (example below). ![new formatting](http://i.stack.imgur.com/TRyNd.jpg) My first thought was to simply copy the entire notebook into a text editor and then copy back into a notebook. However, this results in the generation of a single large input cell that is prohibitively tedious to break up... Applying a new stylesheet does not change the input cell style. Is it possible to update the formatting/style throughout a notebook whilst preserving the cell structure and hierarchy? Edit: An excerpt from the original notebook can be found here, and here is the same excerpt after clearing formatting (but without syntax highlighting).


title: Define functions from two lists

text: I have two lists               {G[x_,y_],F[x_,y_],C[x_,y_]}       and               {x*y-x, 3x+y, x^y}      Now I need to define 3 functions               G[x_,y_]:=x*y-x;     F[x_,y_]:=3x+y;     C[x_,y_]:=x^y;      How to do it correctly?                Table[%%[[i]] := %[[i]], {i, Length[%%]}]       does not work


title: Setting options of expressions similar to using SetOptions on objects

text: **Introduction** I often have the problem that in an expression, I want to change an option. If we are sure the option is not present, we could simply use `Append[expression, opt -> val]`. But sometimes such an expression is very long and it can be a bit of a pain to see if this option is already present. _Example_ We have               Notebook[{Cell["hello", "Text"]}]      we want               Notebook[{Cell["hello", "Text"]}, Background -> LightGreen]      _Mathematica_ has some built in functions for setting options. They are `SetOptions`, `Option` in combination with `Set` (which I think does the same thing as `SetOptions`) and `CurrentValue` in combination with `Set`. None of these seem to do what I want. **Silly things I tried** The fact that we can use `Options` with `Set` may sound promising, but although we can ask the value of an option in an expression, we cannot set it. _Example_               kkkk:=f[2,q->c,z->x,zz->xx];     Options[kkkk]     Options[kkkk, q]      > >     {q -> c, z -> x, zz -> xx} >     {q -> c} >   But               Options[kkkk] = {q -> d, z -> x, zz -> xx}      gives an error and               Options[Unevaluated@kkkk] = {q -> d, z -> x, zz -> xx}      does something strange. **Nice function** So I have made my own function               setExpressionOptions[       head_[        a__,        b : Longest[ OptionsPattern[], 1],        Longest[(symb_ -> _) ..., 2],        d : OptionsPattern[]        ],       symb_ -> val_       ] := head[a, b, symb -> val, d]      _Examples of use_               setExpressionOptions[f[2, q -> b, z -> x, zz -> xx], q -> c]      > >      f[2, q -> c, z -> x, zz -> xx] >                 setExpressionOptions[f[2, z -> x, zz -> xx], q -> c]      > >      f[2, z -> x, zz -> xx, q -> c] >   The function also works with `Unevaluated`               setExpressionOptions[Unevaluated[Plot[x, {x, 0, 1}]], PlotStyle -> Red]      > >      (*a plot with a red line*) >   Note that we really need `Unevaluated` here, otherwise the expression with head `Plot` evaluates to an expression with head `Graphics`, which does not work with `PlotStyle`. **Possible extension** We can define the function `setOptions` like this               setOptions[       x_ /; MemberQ[{NotebookObject, CellObject, FrontEndObject, InputStream,           OutputStream, Symbol, String}, Head[Unevaluated@x]], y___       ] := SetOptions[x, y]          setOptions[z___] := setExpressionOptions[z]      _Examples of use_               setOptions[EvaluationNotebook[], Background -> LightGreen]      > >     (*makes the background LightGreen*) >                 setOptions[f[1], q -> r]      > >     f[1, q -> r] >   **Question** I like the functions quite a lot, but they could be better. It would be nice if we could set any number of options at once using `setExpressionOptions`. _Example of desired evaluation_               setExpressionOptionsBetter[      Notebook[{Cell["hello", "Text"]}, Background -> LightGreen],      Background -> Cyan,      DynamicUpdating -> True      ]      > >      Notebook[{Cell["hello", "Text"]}, Background -> Cyan, DynamicUpdating > -> True] >   Note that `SetOptions` works the same way; beyond position one there are any number of `Rule`s. That also makes integrating this case in `setOptions` easier. Also I am sure I left out a lot of heads in the test in `setOptions`. The Q&A How can I work out which functions work with SetOptions? sounded promising for making the list more complete, but I guess it is not helpful.   * Main question*: Can we add the additional functionality?     * _sub Question 1_ : Did I overlook anything and can this be done easier?     * _sub Question 2_ : Can this use of `Longest` lead to bad performance? (probably no)


title: NMaximize and Accuracy

text: I have a problem with NMaximize which is best depicted by the following figure. The result indicates, that the solution mathematica finds seems to be smooth except a few outliers. How can I get rid of them? I tried to change the method NMaximizes uses, e.g. SimulatedAnnealing etc. but it did not improve. Moreover, changing WorkingPrecision was also not a viable option, too (increase up to 400). Any kind of help is appreciated! ![Solution of NMaximze](http://i.stack.imgur.com/9C56L.jpg) The code is as follows:               RS[a_, p_, v_, t1_, T1_, x0_, i1_, i2_, t2_]:=Module[{z, T0, dT0, b, n1, d, i},       b := 1/2 - (a/v^2) + Sqrt[(1/2 - a/v^2)^2 + (2*p)/v^2];        n1[w_] := PDF[NormalDistribution[0, 1], w];       z[a1_] := a1/(p-a);       i[a4_] := i1 + a4*i2;       T0[a2_, a3_] := T1 + (a2)^t1*(a3)^t2;       dT0[a2_, a3_] := t1*(a2)^(t1-1)*(a3)^t2;       d[a2_, a1_, a3_, a5_] := (Log[T0[a2, a3] - Log[a5]] + (a - 1/2*(v)^2)*a3)*(v*Sqrt[a3])^(-1);       NMaximize[{((T0[a2, a3]-1)*z[a1]-a2-i[a4])*(x0/a1)^b,      a4*Exp[-p*a3]*n1[d[a2, a1, a3, a5]]*1/(v*Sqrt[a3])*dT0[a2, a3]==1      && a1 >= 0 && a2 >= 0 && a3 >= 0 && a4 >= 0 && a5 >= 1}, {a1, a2, a3, a4, a5}]      ]      while the graph is generated using, e.g.:               Plot[RS[0.03, 0.05, j, 0.1, 1.1, 1, 30, 0.1, 0.025][[2, 1, 2]], {j, 0.05, 0.25}]


title: Why I need Evaluate for the Plot of the probability density function of PolyaAeppliDistribution?

text: I encountered this when I was trying to answer this question. I just can't understand why the following code will only give a line at $y=0$:               Plot[PDF[PolyaAeppliDistribution[7, 1/4], x], {x, 0, 35}, Axes -> {False, True}]      ![enter image description here](http://i.stack.imgur.com/xwEJL.jpg) While with `Evaluate` I'll get the desired result:               Plot[Evaluate@PDF[PolyaAeppliDistribution[7, 1/4], x], {x, 0, 35}]      ![enter image description here](http://i.stack.imgur.com/a2r2N.jpg) `DiscretePlot`, which is a function with `Attributes` similar to `Plot`, doesn't suffer this:               DiscretePlot[PDF[PolyaAeppliDistribution[7, 1/4], x], {x, 0, 35}]      ![enter image description here](http://i.stack.imgur.com/C7Wvn.jpg) nor do many other distributions, for example `NormalDistribution`:               Plot[PDF[NormalDistribution[7, 2], x], {x, 0, 35}]      ![enter image description here](http://i.stack.imgur.com/65f1Q.jpg) I haven't do a complete test so I'm not sure if there's other distribution behaved like `PolyaAeppliDistribution`. Has it got any deep reasons? Or it's just a bug? I'm using _Mathematica 8_ , _Windows Vista Home Basic 32-bit_.


title: How can I write image to MySQL database?

text: I have a database, such as: ![Database schema](http://i.stack.imgur.com/qzliW.jpg) In _Mathematica_ , the final code is:               img1=Export["/home/user/Desktop/1.jpg",resultimg1];      I tried `SQLInsert[conn,"mathematica",{"image"},{img1}];` but the MySQL result is: ![Example with just image name inserted](http://i.stack.imgur.com/NS4LR.jpg) > How can I write the **image** to MySQL database?


title: Signed Graph from positive and negative correlations

text: I want to create a signed graph where the edges of my graph are either green (for a positive correlation) or red (for a negative correlation). I only managed to create a graph from a tresholded adjacency matrix so far (greater than x), but struggling with this and didn't find a function in mathematica. I'm also not sure if it's even possible :/ Is it also possible to make the edge lines thicker for a stronger correlation? Thanks in advance


title: Converting code in other languages to Mathematica code

text: Do you know of any work being done on the idea of bringing in code from languages like PERL, PHP, Python, etc.? That is import the code in some way and then convert it to _Mathematica_ code?


title: How to prevent auto spacing/alignment?

text: When using notebook, I find that sometimes when I type, it will automatically indent for me.![enter image description here](http://i.stack.imgur.com/YgBti.png) How can I block this function?