title: Inconsistent results in fits from NArgMin

text: EDIT: Just realized I had misspelled "inconsistent." I'm using version 7.0. I'm trying to fit a (noisy) data set to a large-order polynomial. (Just for context: there isn't a model for the data, and I need to find the minimum of the derivative, which is much easier with a polynomial that bypasses some of the noise.) The derivative of the data should always be positive, but noise in the data can cause it to appear to have a local minimum. This consistently happens at low x-values of the data (not a problem) and at higher x-values (the part I'm interested in). It's actually pretty difficult to find the best fit with a constraint like that on the derivative; I was lucky enough to find this previous question and started from there. Since I've had trouble reproducing this with a simpler set of data, I'm including the data that's causing the problem as well as my attempt. Sorry about that :\               data={{-7.60206, -5.90028}, {-7.20412, -6.32711}, {-7.05799, -6.24573}, \     {-6.90309, -8.23214}, {-6.727, -6.25497}, {-6.67264, -6.0359}, \     {-6.62434, -7.09815}, {-6.60206, -6.74033}, {-6.58087, -6.9319}, \     {-6.50515, -6.00988}, {-6.47173, -5.89132}, {-6.42597, -6.61755}, \     {-6.41173, -6.8024}, {-6.39794, -7.15367}, {-6.38458, -6.50378}, \     {-6.35902, -6.08738}, {-6.33489, -6.03554}, {-6.30103, -6.94662}, \     {-6.27984, -7.61019}, {-6.26962, -6.91566}, {-6.24988, -6.00816}, \     {-6.23099, -6.14881}, {-6.20412, -7.65494}, {-6.18709, -6.84911}, \     {-6.17881, -7.91219}, {-6.16273, -6.09495}, {-6.14722, -6.48424}, \     {-6.12494, -6.66752}, {-6.11776, -6.91584}, {-6.10375, -6.39662}, \     {-6.07058, -7.19377}, {-6.05799, -6.65843}, {-6, -6.80801}, \     {-5.98928, -7.18128}, {-5.95861, -6.81322}, {-5.9393, -7.01644}, \     {-5.89449, -6.82349}, {-5.87778, -6.55417}, {-5.86967, -6.74259}, \     {-5.83863, -6.76216}, {-5.82391, -7.12595}, {-5.81673, -7.83024}, \     {-5.80272, -6.71336}, {-5.75696, -6.77054}, {-5.73283, -7.41132}, \     {-5.72125, -6.87451}, {-5.69897, -6.64371}, {-5.66756, -6.78701}, \     {-5.65758, -6.83261}, {-5.64782, -7.04809}, {-5.62893, -8.12271}, \     {-5.61083, -6.81729}, {-5.59346, -7.58534}, {-5.58503, -7.65891}, \     {-5.56864, -6.98094}, {-5.5157, -6.928}, {-5.50169, -6.98523}, \     {-5.4437, -6.9454}, {-5.4318, -7.17851}, {-5.38722, -7.31544}, \     {-5.27572, -7.36563}, {-5.25964, -7.53078}, {-5.22185, -7.11725}, \     {-5.18046, -7.66833}, {-5.16749, -7.64004}, {-5.14267, -7.4718}, \     {-5.11919, -7.46749}, {-5.07572, -9.05899}, {-5.0655, -7.38326}, \     {-5.04576, -7.79535}, {-5.02687, -7.01003}, {-5, -7.47527}, \     {-4.95078, -7.14359}, {-4.9431, -7.44334}, {-4.90658, -7.12264}, \     {-4.85387, -7.25088}, {-4.80688, -7.77359}, {-4.78516, -8.05067}, \     {-4.76447, -8.07252}, {-4.72584, -7.33981}, {-4.70774, -6.99741}, \     {-4.69037, -7.45587}, {-4.63451, -7.42141}, {-4.62709, -7.89697}, \     {-4.61979, -7.52025}, {-4.61261, -8.00335}, {-4.5784, -7.78812}, \     {-4.56543, -7.40386}, {-4.49485, -7.813}, {-4.47366, -7.16346}, \     {-4.46344, -7.41719}, {-4.45346, -7.40907}, {-4.40671, -7.47877}, \     {-4.38934, -8.33093}, {-4.38091, -7.22819}, {-4.35655, -7.74591}, \     {-4.32606, -7.95015}, {-4.31876, -7.74146}, {-4.27737, -7.78947}, \     {-4.22768, -8.35667}, {-4.2161, -7.79398}, {-4.19382, -8.42667}, \     {-4.17263, -7.2905}, {-4.16241, -8.96208}, {-4.15243, -7.80177}, \     {-4.14267, -7.95211}, {-4.11464, -7.71493}, {-4.07988, -7.54309}, \     {-4.0716, -7.63749}, {-4.06349, -7.86216}, {-4.04769, -7.92244}, \     {-4.02503, -7.52806}, {-4.01773, -7.8399}, {-3.99568, -7.93923}, \     {-3.97469, -8.35667}, {-3.96257, -8.13847}, {-3.9393, -8.43652}, \     {-3.90309, -8.75796}, {-3.89279, -8.1729}, {-3.88273, -7.92428}, \     {-3.8729, -8.31709}, {-3.86012, -8.59314}, {-3.85078, -7.85531}, \     {-3.83268, -7.93671}, {-3.81248, -7.82018}, {-3.8041, -8.00778}, \     {-3.79588, -8.06567}, {-3.78781, -8.06229}, {-3.76955, -8.69581}, \     {-3.76195, -7.8496}, {-3.75449, -7.86858}, {-3.74715, -8.20325}, \     {-3.73993, -7.70706}, {-3.73049, -7.62317}, {-3.72354, -7.72065}, \     {-3.7167, -8.27666}, {-3.69465, -7.76037}, {-3.68825, -7.76928}, \     {-3.67572, -7.67484}, {-3.66154, -8.02366}, {-3.64975, -8.23589}, \     {-3.63827, -7.93107}, {-3.62525, -7.50342}, {-3.61439, -7.75411}, \     {-3.60206, -7.77489}, {-3.59176, -7.76971}, {-3.5817, -7.81586}, \     {-3.57025, -7.46451}, {-3.56067, -8.15378}, {-3.54975, -7.59961}, \     {-3.54061, -7.53351}, {-3.53165, -7.61588}, {-3.52143, -8.01452}, \     {-3.51286, -7.76544}, {-3.50307, -7.50226}, {-3.49485, -7.92735}, \     {-3.48678, -7.53301}, {-3.47756, -7.6037}, {-3.4698, -7.59014}, \     {-3.46092, -7.61198}, {-3.45346, -7.50342}, {-3.44612, -7.35343}, \     {-3.43771, -7.75246}, {-3.43063, -7.72065}, {-3.42251, -7.95802}, \     {-3.41567, -7.56719}, {-3.40894, -7.47331}, {-3.40121, -7.57152}, \     {-3.39469, -7.48833}, {-3.38722, -7.46707}, {-3.37469, -7.4033}, \     {-3.36151, -7.65035}, {-3.34872, -7.43076}, {-3.3363, -7.48253}, \     {-3.32422, -7.35195}, {-3.31336, -7.36444}, {-3.3019, -7.41038}, \     {-3.29073, -7.36041}, {-3.27984, -7.41529}, {-3.26922, -7.29265}, \     {-3.25964, -7.24932}, {-3.24949, -7.35146}, {-3.23958, -7.35113}, \     {-3.22988, -7.16049}, {-3.2204, -7.3206}, {-3.21183, -7.23806}, \     {-3.20273, -7.20416}, {-3.19382, -7.24997}, {-3.18509, -7.24803}, \     {-3.17653, -7.14634}, {-3.16877, -7.10937}, {-3.16052, -7.17391}, \     {-3.15243, -7.13803}, {-3.14448, -7.11725}, {-3.13668, -7.19217}, \     {-3.1296, -7.13175}, {-3.12205, -7.12332}, {-3.11464, -7.07218}, \     {-3.10735, -7.09241}, {-3.10018, -7.04678}, {-3.09366, -7.07227}, \     {-3.08672, -7.07253}, {-3.07314, -7.07348}, {-3.06048, -7.00128}, \     {-3.04769, -7.01659}, {-3.03527, -6.96567}, {-3.02365, -6.935}, \     {-3.01189, -6.95611}, {-3.00087, -6.95308}, {-2.9897, -6.93702}, \     {-2.97881, -6.91176}, {-2.96859, -6.90015}, {-2.95821, -6.9111}, \     {-2.94846, -6.89271}, {-2.93855, -6.8787}, {-2.92885, -6.86577}, \     {-2.91973, -6.864}, {-2.91045, -6.83028}, {-2.9017, -6.80614}, \     {-2.89279, -6.8052}, {-2.88406, -6.8232}, {-2.87582, -6.79925}, \     {-2.86742, -6.76766}, {-2.85949, -6.77332}, {-2.8514, -6.75764}, \     {-2.84345, -6.74061}, {-2.83594, -6.7553}, {-2.82827, -6.73816}, \     {-2.82102, -6.7275}, {-2.81361, -6.75098}, {-2.80632, -6.73848}, \     {-2.79942, -6.7172}, {-2.79237, -6.70536}, {-2.78569, -6.71977}, \     {-2.77211, -6.69684}, {-2.7592, -6.69571}, {-2.74666, -6.68624}, \     {-2.73447, -6.66456}, {-2.72262, -6.67177}, {-2.71086, -6.65361}, \     {-2.69962, -6.64591}, {-2.68867, -6.65048}, {-2.67799, -6.64835}, \     {-2.66756, -6.64439}, {-2.65718, -6.64516}, {-2.64724, -6.63901}, \     {-2.63752, -6.64361}, {-2.62801, -6.64287}, {-2.6187, -6.63583}, \     {-2.60942, -6.63402}, {-2.6005, -6.62981}, {-2.59176, -6.64484}, \     {-2.58319, -6.64474}, {-2.57479, -6.65147}, {-2.56639, -6.65002}, \     {-2.5583, -6.64274}, {-2.55037, -6.64187}, {-2.54257, -6.64871}, \     {-2.53491, -6.63834}, {-2.52724, -6.65454}, {-2.51985, -6.66038}, \     {-2.51258, -6.65696}, {-2.50543, -6.65914}, {-2.49839, -6.64055}, \     {-2.49134, -6.65408}, {-2.48452, -6.65424}, {-2.47121, -6.6424}, \     {-2.45817, -6.63535}, {-2.44563, -6.63281}, {-2.43344, -6.62368}, \     {-2.42148, -6.61031}, {-2.40994, -6.59431}, {-2.39859, -6.57061}, \     {-2.38764, -6.55078}, {-2.37696, -6.538}, {-2.36643, -6.51422}, \     {-2.35625, -6.49867}, {-2.34621, -6.47369}, {-2.33649, -6.46208}, \     {-2.32698, -6.43439}, {-2.31758, -6.41997}, {-2.30848, -6.40473}, \     {-2.29947, -6.393}, {-2.29073, -6.37805}, {-2.28216, -6.37162}, \     {-2.27368, -6.36121}, {-2.26544, -6.34662}, {-2.25727, -6.34753}, \     {-2.24934, -6.34287}, {-2.24154, -6.34032}, {-2.23381, -6.33989}, \     {-2.22629, -6.34378}, {-2.21882, -6.34209}, {-2.21155, -6.34217}, \     {-2.2044, -6.34847}, {-2.19729, -6.35258}, {-2.19037, -6.35258}, \     {-2.18349, -6.35968}, {-2.17018, -6.36461}, {-2.1572, -6.36892}, \     {-2.1446, -6.36796}, {-2.13236, -6.36432}, {-2.12045, -6.35925}, \     {-2.10891, -6.34518}, {-2.09762, -6.33549}, {-2.08661, -6.31951}, \     {-2.07588, -6.3087}, {-2.0654, -6.29828}, {-2.05522, -6.29348}, \     {-2.04523, -6.29345}, {-2.03546, -6.30076}, {-2.0259, -6.31038}, \     {-2.01655, -6.32847}, {-2.00745, -6.34783}, {-1.99848, -6.37117}, \     {-1.9897, -6.39458}, {-1.98109, -6.41923}, {-1.97265, -6.43722}, \     {-1.96441, -6.44987}, {-1.95628, -6.45579}, {-1.94831, -6.45369}, \     {-1.94047, -6.44678}, {-1.93278, -6.43521}, {-1.92526, -6.42661}, \     {-1.91783, -6.41699}, {-1.91052, -6.41109}, {-1.90333, -6.40588}, \     {-1.89626, -6.41371}, {-1.88934, -6.42107}, {-1.8825, -6.43708}, \     {-1.86912, -6.47919}, {-1.85617, -6.52883}, {-1.84357, -6.55976}, \     {-1.83133, -6.5558}, {-1.81944, -6.51556}, {-1.80785, -6.4633}, \     {-1.79659, -6.42203}, {-1.78558, -6.39845}, {-1.77485, -6.39715}, \     {-1.7644, -6.4092}, {-1.75417, -6.41564}, {-1.7442, -6.40869}, \     {-1.73443, -6.3793}, {-1.72487, -6.33557}, {-1.71555, -6.29011}, \     {-1.70639, -6.25807}, {-1.69745, -6.24437}, {-1.68867, -6.2509}, \     {-1.68006, -6.26612}, {-1.67164, -6.27975}, {-1.66336, -6.28322}, \     {-1.65525, -6.26844}, {-1.64728, -6.24355}, {-1.63944, -6.22114}, \     {-1.63177, -6.20663}, {-1.62421, -6.2108}, {-1.6168, -6.23096}, \     {-1.60949, -6.26405}, {-1.6023, -6.29625}, {-1.59525, -6.31671}, \     {-1.5883, -6.31662}, {-1.58147, -6.3016}, {-1.56809, -6.27854}, \     {-1.55513, -6.30344}, {-1.54254, -6.33983}, {-1.53031, -6.32322}, \     {-1.51841, -6.26627}, {-1.50682, -6.24411}, {-1.49554, -6.25615}, \     {-1.48455, -6.23942}, {-1.47383, -6.17853}, {-1.46337, -6.13769}, \     {-1.45314, -6.14292}, {-1.44315, -6.15919}, {-1.4334, -6.14313}, \     {-1.42385, -6.11713}, {-1.41452, -6.12631}, {-1.40536, -6.16569}, \     {-1.39641, -6.18248}, {-1.38764, -6.16451}, {-1.37904, -6.15518}, \     {-1.37061, -6.17622}, {-1.36233, -6.18461}, {-1.35421, -6.14501}, \     {-1.34625, -6.10036}, {-1.33842, -6.08757}, {-1.33074, -6.08959}, \     {-1.32318, -6.06436}, {-1.31576, -6.02264}, {-1.30846, -6.00601}, \     {-1.30128, -6.0189}, {-1.29422, -6.02749}, {-1.28727, -6.01383}, \     {-1.28043, -6.00676}, {-1.26707, -6.05246}, {-1.2541, -6.04137}, \     {-1.24151, -6.04864}, {-1.22928, -6.00765}, {-1.21738, -5.96689}, \     {-1.2058, -5.93204}, {-1.19451, -5.90199}, {-1.18352, -5.90146}, \     {-1.1728, -5.89875}, {-1.16233, -5.92488}, {-1.15211, -5.91532}, \     {-1.14212, -5.9226}, {-1.13237, -5.88736}, {-1.12282, -5.86103}, \     {-1.11348, -5.82132}, {-1.10434, -5.80047}, {-1.09538, -5.79469}, \     {-1.08661, -5.79257}, {-1.07801, -5.80953}, {-1.06958, -5.80259}, \     {-1.06131, -5.80503}, {-1.05318, -5.77427}, {-1.04522, -5.7585}, \     {-1.03739, -5.72601}, {-1.0297, -5.71595}, {-1.02215, -5.70825}, \     {-1.01473, -5.70799}, {-1.00743, -5.71207}, {-1.00025, -5.70483}, \     {-0.993188, -5.70018}, {-0.98624, -5.67431}, {-0.979398, -5.66444}, \     {-0.966038, -5.63829}, {-0.953072, -5.63347}, {-0.940482, -5.62353}, \     {-0.928247, -5.59392}, {-0.916347, -5.56682}, {-0.904768, -5.56074}, \     {-0.893486, -5.55977}, {-0.88249, -5.5387}, {-0.871766, -5.50732}, \     {-0.8613, -5.49268}, {-0.851083, -5.49433}, {-0.841098, -5.48539}, \     {-0.831338, -5.45912}, {-0.821792, -5.43721}, {-0.812451, -5.43104}, \     {-0.80331, -5.42785}, {-0.794355, -5.41191}, {-0.78558, -5.39096}, \     {-0.776979, -5.37989}, {-0.768546, -5.37566}, {-0.760275, -5.36394}, \     {-0.752157, -5.34505}, {-0.744187, -5.33322}, {-0.736362, -5.32963}, \     {-0.728674, -5.32043}, {-0.721123, -5.30286}, {-0.713699, -5.28876}, \     {-0.706399, -5.28529}, {-0.69922, -5.28199}, {-0.692158, -5.26763}, \     {-0.68521, -5.24964}, {-0.678371, -5.24109}, {-0.665006, -5.2306}, \     {-0.652042, -5.20638}, {-0.639452, -5.19457}, {-0.627217, -5.17444}, \     {-0.615319, -5.1607}, {-0.603736, -5.14226}, {-0.592456, -5.13065}, \     {-0.58146, -5.11305}, {-0.570736, -5.10147}, {-0.560271, -5.08776}, \     {-0.550051, -5.07206}, {-0.540068, -5.06321}, {-0.530308, -5.04697}, \     {-0.520762, -5.03815}, {-0.511422, -5.02446}, {-0.502279, -5.01468}, \     {-0.493325, -5.00185}, {-0.48455, -4.99366}, {-0.475949, -4.98007}, \     {-0.467517, -4.97234}, {-0.459244, -4.96171}, {-0.451127, -4.95081}, \     {-0.443157, -4.94383}, {-0.435332, -4.93212}, {-0.427645, -4.92523}, \     {-0.420092, -4.91513}, {-0.412669, -4.90733}, {-0.405369, -4.89753}, \     {-0.39819, -4.89191}, {-0.391129, -4.88128}, {-0.384179, -4.87593}, \     {-0.377341, -4.86739}, {-0.363976, -4.85303}, {-0.351011, -4.83878}, \     {-0.338422, -4.82565}, {-0.326188, -4.81316}, {-0.314289, -4.80114}, \     {-0.302706, -4.78971}, {-0.291425, -4.77868}, {-0.28043, -4.76819}, \     {-0.269706, -4.75792}, {-0.259241, -4.74798}, {-0.249021, -4.7385}, \     {-0.239037, -4.72924}, {-0.229278, -4.7201}, {-0.219732, -4.71146}, \     {-0.210392, -4.7033}, {-0.201249, -4.69572}, {-0.192294, -4.68787}, \     {-0.18352, -4.68039}, {-0.17492, -4.67327}, {-0.166487, -4.66616}, \     {-0.158214, -4.65948}, {-0.150096, -4.65317}, {-0.142127, -4.64682}, \     {-0.134302, -4.64059}, {-0.126615, -4.63473}, {-0.119062, -4.6292}, \     {-0.111638, -4.62373}, {-0.104339, -4.61836}, {-0.0971603, -4.61337}, \     {-0.0900986, -4.60855}, {-0.0831493, -4.60343}, {-0.07631, -4.59873}, \     {-0.0629462, -4.58964}, {-0.049981, -4.58088}, {-0.037392, -4.57269}, \     {-0.0251578, -4.56487}, {-0.0132583, -4.55743}, {-0.00167657, \     -4.55083}, {0.0096047, -4.54454}, {0.0205999, -4.53893}, {0.0313236, \     -4.53337}, {0.0417893, -4.52825}, {0.0520083, -4.52332}, {0.0619927, \     -4.51822}, {0.0717524, -4.51344}, {0.0812976, -4.50889}, {0.0906379, \     -4.50455}, {0.0997811, -4.50059}, {0.108736, -4.49674}, {0.11751, \     -4.49265}, {0.12611, -4.48908}, {0.134543, -4.48549}, {0.142816, \     -4.48249}, {0.150934, -4.47944}, {0.158903, -4.47637}, {0.166728, \     -4.47342}, {0.174415, -4.4706}, {0.181968, -4.46742}, {0.189392, \     -4.46434}, {0.196691, -4.46137}, {0.20387, -4.45885}, {0.210932, \     -4.45637}, {0.21788, -4.45369}, {0.22472, -4.45128}, {0.238084, \     -4.4462}, {0.251049, -4.44101}, {0.263638, -4.43577}, {0.275872, \     -4.43012}, {0.287772, -4.42478}, {0.299353, -4.41977}, {0.310634, \     -4.41556}, {0.32163, -4.41204}, {0.332354, -4.40875}, {0.342819, \     -4.40574}, {0.353038, -4.40279}, {0.363023, -4.40021}, {0.372782, \     -4.39779}, {0.382328, -4.39527}, {0.391668, -4.39256}, {0.400811, \     -4.39048}, {0.409766, -4.38866}, {0.41854, -4.38663}, {0.42714, \     -4.38516}, {0.435573, -4.3833}, {0.443846, -4.38112}, {0.451964, \     -4.37841}, {0.459933, -4.37602}, {0.467758, -4.37398}, {0.475445, \     -4.37215}, {0.482998, -4.37002}, {0.490422, -4.36768}, {0.497721, \     -4.36579}, {0.5049, -4.3635}, {0.511962, -4.36165}, {0.518911, \     -4.36083}, {0.52575, -4.36591}, {0.539114, -4.37695}, {0.552079, \     -4.38624}, {0.564668, -4.39179}, {0.576902, -4.39043}, {0.588802, \     -4.39048}, {0.600384, -4.39417}, {0.611665, -4.39192}, {0.62266, \     -4.38866}, {0.633384, -4.37718}, {0.643849, -4.36093}, {0.654068, \     -4.33669}, {0.664053, -4.32032}, {0.673812, -4.31347}, {0.683358, \     -4.31332}, {0.692698, -4.31251}, {0.701841, -4.31158}, {0.710796, \     -4.31023}, {0.71957, -4.3079}, {0.72817, -4.31828}, {0.736603, \     -4.33206}, {0.744876, -4.34439}, {0.752994, -4.35617}, {0.760963, \     -4.35984}, {0.768788, -4.36454}, {0.776475, -4.3641}, {0.784028, \     -4.35747}, {0.791452, -4.35255}, {0.798751, -4.34871}, {0.80593, \     -4.3443}, {0.812992, -4.33782}, {0.81994, -4.33342}, {0.82678, \     -4.33645}, {0.840144, -4.3371}, {0.853109, -4.33312}, {0.865698, \     -4.33385}, {0.877932, -4.31409}, {0.889832, -4.28469}, {0.901414, \     -4.27696}, {0.912695, -4.27538}, {0.92369, -4.27261}, {0.934414, \     -4.27074}, {0.944879, -4.26815}, {0.955098, -4.27633}, {0.965083, \     -4.28695}, {0.974842, -4.3028}, {0.984388, -4.30428}, {0.993728, \     -4.28852}, {1.00287, -4.28339}, {1.01183, -4.26882}, {1.0206, \     -4.26852}, {1.0292, -4.28874}, {1.03763, -4.30999}, {1.04591, \     -4.34026}, {1.05402, -4.34564}, {1.06199, -4.33417}, {1.06982, \     -4.31732}, {1.0775, -4.3048}, {1.08506, -4.28295}, {1.09248, \     -4.26599}, {1.09978, -4.28068}, {1.10696, -4.31298}, {1.11402, \     -4.33177}, {1.12097, -4.32824}, {1.12781, -4.30647}, {1.14117, \     -4.25651}, {1.15414, -4.22247}, {1.16673, -4.22796}, {1.17896, \     -4.29991}, {1.19086, -4.30709}, {1.20244, -4.30735}, {1.21372, \     -4.31431}, {1.22472, -4.3091}, {1.23544, -4.27057}, {1.24591, \     -4.21295}, {1.25613, -4.1817}, {1.26611, -4.18344}, {1.27587, \     -4.18317}, {1.28542, -4.18257}, {1.29476, -4.1835}, {1.3039, \     -4.18194}, {1.31286, -4.18449}, {1.32163, -4.18843}, {1.33023, \     -4.19232}, {1.33866, -4.19326}, {1.34694, -4.19159}, {1.35505, \     -4.18504}, {1.36302, -4.18344}, {1.37085, -4.18041}, {1.37853, \     -4.17377}, {1.38609, -4.21639}, {1.39351, -4.26059}, {1.40081, \     -4.28928}, {1.40799, -4.27665}, {1.41505, -4.22666}, {1.422, \     -4.1761}, {1.42884, -4.17782}, {1.4422, -4.16613}, {1.45517, \     -4.17583}, {1.46776, -4.1726}, {1.47999, -4.21981}, {1.49189, \     -4.29252}, {1.50347, -4.30803}, {1.51475, -4.34688}, {1.52575, \     -4.29175}, {1.53647, -4.27055}, {1.54694, -4.21275}, {1.55716, \     -4.17283}, {1.56714, -4.21776}, {1.5769, -4.1952}, {1.58645, \     -4.16187}, {1.59579, -4.19783}, {1.60493, -4.16365}, {1.61389, \     -4.17921}, {1.62266, -4.27348}, {1.63126, -4.31112}, {1.63969, \     -4.2974}, {1.64797, -4.25625}, {1.65608, -4.20345}, {1.66405, \     -4.20957}, {1.67188, -4.19068}, {1.67956, -4.11956}, {1.68712, \     -4.13562}, {1.69454, -4.21543}, {1.70184, -4.18477}, {1.70902, \     -4.25779}, {1.71608, -4.28487}, {1.72303, -4.27459}, {1.72987, \     -4.28326}, {1.74323, -4.25068}, {1.7562, -4.27135}, {1.76879, \     -4.28912}, {1.78102, -4.32662}, {1.79292, -4.31143}, {1.8045, \     -4.35274}, {1.81578, -4.29717}, {1.82678, -4.29271}, {1.8375, \     -4.31687}, {1.84797, -4.32874}, {1.85819, -4.25051}, {1.86817, \     -4.21378}, {1.87793, -4.24568}, {1.88748, -4.17369}, {1.89682, \     -4.18327}, {1.90596, -4.29785}, {1.91492, -4.26084}, {1.92369, \     -4.22121}, {1.93229, -4.22309}, {1.94072, -4.2172}, {1.949, \     -4.22707}, {1.95711, -4.32227}, {1.96508, -4.40666}, {1.97291, \     -4.27942}, {1.98059, -4.25027}, {1.98815, -4.31823}, {1.99557, \     -4.25654}, {2.00287, -4.28529}, {2.01005, -4.28781}, {2.01711, \     -4.24779}, {2.02406, -4.23673}, {2.0309, -4.13488}, {2.04426, \     -4.08296}, {2.05723, -4.2324}, {2.06982, -4.17255}, {2.08205, \     -4.19828}, {2.09395, -4.13272}, {2.10553, -4.19443}, {2.11681, \     -4.14937}, {2.12781, -4.22916}, {2.13853, -4.10431}, {2.149, \     -4.14669}, {2.15922, -4.33392}, {2.1692, -4.22209}, {2.17896, \     -4.11348}, {2.18851, -4.23143}, {2.19785, -4.31207}, {2.20699, \     -4.18715}, {2.21595, -4.21967}, {2.22472, -4.2331}, {2.23332, \     -4.10382}, {2.24175, -4.03334}, {2.25003, -4.12132}, {2.25814, \     -4.10954}, {2.26611, -4.10093}, {2.27394, -3.98143}, {2.28162, \     -3.96581}, {2.28918, -3.93108}, {2.2966, -3.86353}, {2.3039, \     -3.90121}, {2.31108, -4.14699}, {2.31814, -4.16986}, {2.32509, \     -4.06914}, {2.33193, -4.09747}, {2.34529, -4.13102}, {2.35826, \     -4.10327}, {2.37085, -4.03584}, {2.38308, -4.11951}, {2.39498, \     -3.98065}, {2.40656, -3.86725}, {2.41784, -3.87111}, {2.42884, \     -3.90806}, {2.43956, -4.10791}, {2.45003, -4.17971}, {2.46025, \     -4.00339}, {2.47023, -4.02952}, {2.47999, -4.09248}, {2.48954, \     -4.05987}, {2.49888, -3.82593}, {2.50802, -3.76067}, {2.51698, \     -3.86685}, {2.52575, -3.84597}, {2.53435, -3.8714}, {2.54278, \     -3.91248}, {2.55106, -3.86843}, {2.55917, -3.74494}, {2.57497, \     -3.88662}, {2.58265, -3.84542}, {2.59021, -3.8864}, {2.59763, \     -3.77177}, {2.60493, -3.76896}, {2.61211, -3.69489}, {2.61917, \     -3.80791}, {2.63296, -3.76332}, {2.64632, -3.71202}, {2.65929, \     -4.13497}, {2.68411, -3.7482}, {2.69601, -3.87555}, {2.70759, \     -3.90333}, {2.74059, -4.06462}, {2.75106, -3.90174}};      Here is my attempt to fit it with an order-4 polynomial:               Clear[a,b,c,d,e]     {a,b,c,d,e}=NArgMin[{Norm[Function[{x,y},\[FormalA]+\[FormalB] x+\[FormalC] x^2+ \     \[FormalD] x^3+\[FormalE] x^4-y]@@@data],Function[{x,y},\[FormalB]+2 \[FormalC] x \     +3 \[FormalD] x^2+4 \[FormalE] x^3>0]@@@data},{\[FormalA],\[FormalB],\[FormalC], \     \[FormalD],\[FormalE]}]      The coefficients this gives are               {a,b,c,d,e}={-5.01894, 0.720639, -0.0207154, -0.0210971, -0.00153312}      and the polynomial both approximately fits the data and has an always-positive derivative. Here is an attempt with an order-5 polynomial:               Clear[a,b,c,d,e,f]     {a,b,c,d,e,f}=NArgMin[{Norm[Function[{x,y},\[FormalA]+\[FormalB] x+\[FormalC] \      x^2+\[FormalD] x^3+\[FormalE] x^4+\[FormalF] x^5-y]@@@data],Function[{x,y},\[FormalB]+ \     2 \[FormalC] x+3 \[FormalD] x^2+4 \[FormalE] x^3+5 \[FormalF] x^4>0]@@@data},{\[FormalA], \     \[FormalB],\[FormalC],\[FormalD],\[FormalE],\[FormalF]}]      It's exactly the same as before except that there is a term `f x^5`. It gives the error message `NArgMin::nsol : There are no points that satisfy the constraints` {a number of terms equal to Length[data], each of which is the derivative constraint evaluated at the x-value for a particular point}. However there obviously is a solution that satisfies the constraints, since in the worst case setting `f=0` would duplicate the order-4 fit which I've already established works. Based on some experimenting with the fit _without_ constraining the derivative to always be positive, I expect that in order to satisfactorily fit the data I will need to use a polynomial of order about 20. That might present problems of its own, but I'll almost surely run into this particular one again unless I figure out how to fix it. Also, because fitting the order-4 polynomial takes about a minute, any suggestions on how to speed this up would also be appreciated. Thanks in advance for any help!


title: Why doesn't Mathematica evaluate this limit?

text: I am trying to evaluate a few limits in _Mathematica_ , and I can only get it to evaluate them in certain cases. I don't fully understand the evaluation order and when it substitutes numerical values in for variables. If anyone could explain to me how to do these I would appreciate it. Mn, g, and extent have numerical values that are determined before this. x0 and order are parameters that I input manually when plotting and using for matching, etc.               DeltaAnalytic[k_?NumericQ, g_?NumericQ, extent_?NumericQ] :=        ArcTan[((Sin[k*extent])^2)/(k*extent*Mn/g - Sin[k*extent]*Cos[k*extent])];          EffRangeExp[k0_, x0_?NumericQ, order_?NumericQ, coupling_?NumericQ, extent_?NumericQ] :=       Limit[Normal[Series[DeltaAnalytic[k, coupling, extent], {k, x, order}]], x -> x0] /.          k -> k0;      Now when I try to plot the above, `EffRangeExp`, or just get it to spit out a numeric value at some k with various parameters, it is clearly evaluating something in the wrong order. I just don't know how to fix this problem. Would it help to make the variables local in the above function?


title: Moments Ratio Plot using "ProbabilityDistribution"

text: I am trying to plot moments ratio plot with the following code:               f1[al_, be_, ga_, lam_] =        Skewness[ProbabilityDistribution[         al be x^(-be - 1) (1 + ga x^-be )^(-(al/ga) - 1) (1 + lam - 2 lam ((1 + ga x^-be )^(-(al/ga)))), {x, 0, ∞}]];     f2[al_, be_, ga_, lam_] = Kurtosis[ProbabilityDistribution[al be x^(-be - 1) (1 + ga x^-be )^(-(al/ga) -  1) (1 + lam - 2 lam ((1 + ga x^-be )^(-(al/ga)))), {x,           0, ∞}]];          b = ParametricPlot[{f1[10, be, 1.5, -0.5], f2[10, be, 1.5, -0.5]}, {be, 0.1, 5}];     a = RegionPlot[b2 - (b1)^2 - 1 < 0, {b1, -2, 3}, {b2, 0, 9}];     Show[a, b]      where `{al,be,ga} > 0` and `lam` is between `-1` and `1`. But _Mathematica_ is unable to compute skewness and kurtosis of the specified distribution (under this code). How can I compute `Skewness` and `Kurtosis` and further plot moments ratio plot of the specified distribution. In above code if I replace `ProbabilityDistribution` by `WeibullDistribution` I got moments ratio plot of _Weibull distribution_.


title: How to generate a series of bisection points of a given line segment?

text: I want to get the coordinates of the bisection points for a given line segment to a specified resolution. For example, when the line is given by {0,0} and {1,0}, the output coordinates should be {0.5,0} for the first iteration, and then {0.25,0} and {0.75,0} for the second iteration, and so on, until the distances between those points are less than some resolution, say 1/16. Is there a convenient way?


title: How copy a large cell into clipboard using `input text`?

text: This is a strange problem and everything I tried did not work. I have a very large single Manipulate cell (it is a demonstration stylesheet notebook, hence this cell have to be one), and I simply wanted to copy the content of this cell and paste it into another text file. It seems that, for some reason, Mathematica has a limit somewhere, since I am sure the windows 7 clipboard can handle this size itself. When I select the cell, and then do CTRL-c, and paste into a plain text file in my editor, the output that shows up is only about 850 lines (this is much less than the original cell, which is I think few thousands lines long). I tried two different editors with the same result. It always gets cut off at the same place. The copy has to be done as `input text` and not as `plain text`. The copy as `plain text` is able to copy the whole cell, but the formatting is all messed up and not possible to read. I need to copy it as `input text`, which what happens when selecting the cell and doing CTRL-C, then CTRL-V (on windows) I can save the whole notebook as .txt file, but again, the formatting is all lost, and it seems to save it using the `plain text` mode. I can offocurse break the cell into many smaller cells, and then copy one by one with the mouse, but this is very tedious way to do it and I think there should be a way to handle this directly. Here is the notebook and I hope someone can find a way. I have many such notebooks with large cells to do. I am using version 9.01 on windows 7 64 bit.


title: Using WhenEvent for derivative of discontinuous function

text: I have a discontinuous function ($u(t)$, a square wave) and I would like `WhenEvent` to trigger when the signal goes high/low, i.e. when the value of $u(t)$ changes. I was hoping to use the derivative of $u(t)$ to determine this.               squareWave[t_, period_, duty_] := UnitBox[Mod[t/period, 1.]/(2. duty)]          system =  {x'[t] == u[t], WhenEvent[Mod[t, 0.5 τ],          u[t] -> squareWave[t, 2 τ, 0.2]], x[0] == 0, u[0] == 1,          WhenEvent[D[u[t]] > 0, Print[t]]};     params = {τ -> 1};     sol = NDSolve[system /. params, {x, u}, {t, 0, 10},         DiscreteVariables -> u];     Plot[Evaluate[{x[t], u[t], u'[t]} /. sol], {t, 0, 10},         PlotLegends -> {"x(t)", "u(t)", "u'[t]"}]      Unfortunately this does not seem to work? The output is: ![Output](http://i.stack.imgur.com/3Rjxl.png)


title: Axis Labels Disappear With Manipulate

text: I have a `ListPlot3D` with custom axis labels that I am scrolling with `Manipulate`. My issue is that the axis labels scroll away as the plot is scrolled. The commands below reproduce the problem that I am having. Thanks, Edmund               tickLabels = {{1, ""}, {2, ""}, {3, ""}, {4, ""}, {5, "lv1"}, {6,      ""}, {7, ""}, {8, ""}, {9, ""}, {10, "lv2"}, {11, ""}, {12,      ""}, {13, ""}, {14, ""}, {15, "lv3"}, {16, ""}, {17, ""}, {18,      ""}, {19, ""}, {20, "lv4"}, {21, ""}, {22, ""}, {23, ""}, {24,      ""}, {25, "lv5"}, {26, ""}, {27, ""}, {28, ""}, {29, ""}, {30,      "lv6"}, {31, ""}, {32, ""}, {33, ""}, {34, ""}, {35, "lv7"}, {36,      ""}, {37, ""}, {38, ""}, {39, ""}, {40, "lv8"}, {41, ""}, {42,      ""}, {43, ""}, {44, ""}, {45, "lv9"}, {46, ""}, {47, ""}, {48,      ""}, {49, ""}, {50, "lv10"}};          Manipulate[      ListPlot3D[       Table[i + j RandomReal[{1, 5}], {i, 50}, {j, 15}][[window - 9 ;; window]],       AxesLabel -> {"x", "y", "value"},        Ticks -> {Automatic, tickLabels[[window - 9 ;; window]], Automatic}],        {window, 10, 50, 1}]


title: How to build a list of functions

text: Having said that I'm no expert, I have some problems in generating a list of functions inside a loop. The functions in the list should depend on the elements of a _parameters_ list, that are read in sequence. The stripped down examples here below should show what I mean. First I tried this (rather naively)               parameters = {a, 3, 6, E, 2}; p = 1;     While[p <= 5, funclist[[p]][x_] := parameters[[p]] x^p; p++]      Naturally it doesn't work. After some other trials I arrived at this possible solution               parameters = {a, 3, 6, E, 2}; p = 1;     While[p <= 5, With[{p = p}, funclist[p, x_] := parameters[[p]] x^p]; p++]      But in this case the output is not actually a list but rather a sort of indexed function that cannot be manipulated as a list could be. What I'd like to get is a list of functions that, for example can be used in the following ways:               in: funclist     out: {a x, 3 x^2...}      and also               in: funclist[[2]][4]     out: 48      or also               Plot[funclist[[2]],{x,-1,5}]      Is it possible?


title: How to use DegreeGraphDistribution with directed graphs?

text: `DegreeGraphDistribution` supports directed graphs because it has a `DirectedEdges` option. How can I specify the in-degree sequence and the out-degree sequence separately when generating random _directed_ graphs? For example,               RandomGraph@DegreeGraphDistribution[{2, 2, 1, 1}, DirectedEdges -> True]      gives a graph where the vertices have the following {in, out} degree combinations: `{{2,2}, {2,2}, {1,1}, {1,1}}`. This syntax worked, but the in and out-degree sequences are identical for each vertex. How can I specify them separately? * * * I'd like to note that as a workaround it is possible to use igraph's `degree.sequence.game` function through the IGraphR package. However, now I am looking to do this in pure Mathematica though. If you do end up using igraph, be sure to read the documentation in detail, and be aware of the quirks of each method that is available (does it guarantee uniform sampling? does it produce simple graphs? does it support directed graphs? there are several options).


title: Construct a simple mesh or tetrahedral mesh from 3D image surface

text: I have a 3D Y-Shape hollow tube, not so good surface.                Import["http://dl.dropbox.com/u/68983831/tube02.vtk", "Graphics3D"]      ![enter image description here](http://i.stack.imgur.com/A2k9g.png) I tried to use following vertex data plot and generate mesh.               pts = Import["tube02.vtk", "VertexData"];     Graphics3D[Point@pts]      ![enter image description here](http://i.stack.imgur.com/5LztT.png) Question: How to plot a smooth surface from vertex data and then generate tetrahedral or simple mesh? I was trying to use following thread to solve my problem: How to calculate volume of convex hull and volume of a 3D object and My donut has holes in it!.


title: Combination of a Contourplot and a Graphics Object

text: I want to combine the following to graphs.               cartPoints = Table[With[{x = RandomReal[]}, {1/(2*Pi), ArcCos[x]}], {10}];     Graphics[Arrow[{{0, 0}, #}] & /@ CoordinateTransform["Polar" -> "Cartesian", cartPoints],      Frame -> True, FrameTicks -> None, AspectRatio -> 1,      PlotRange -> {{0, 1/(2*Pi)}, {0, 1/(2*Pi)}},      FrameLabel -> {{"z", ""}, {"y", ""}},      LabelStyle -> { FontFamily -> "Arial", FontSize -> 14},      BaseStyle -> {FontFamily -> "Arial", FontSize -> 14}]          ContourPlot[Cos[x^2 + y^2], {x, -Sqrt[Pi]/2, Sqrt[Pi]/2}, {y, -Sqrt[Pi]/2,      Sqrt[Pi]/2}, FrameLabel -> {{"x", ""}, {"y", ""}},      LabelStyle -> { FontFamily -> "Arial", FontSize -> 14},      BaseStyle -> {FontFamily -> "Arial", FontSize -> 14}]      How can I arrange both graphs in 3D? The Countourplot should be the bottom of the resultung graph and the arrows should point in z direction


title: Keeping vertexcoordinates after adding a new vertex

text: I want to add a new vertex to a graph, with fixed VertexCoordinates but when I use VertexAdd, the new graph does not have the VertexCoordinates of the previous one.               g = Graph[{1 -> 2}, VertexCoordinates -> {{0, 0.5}, {0.5, 0}},        PlotRange -> 1]      This is the initial graph               g = VertexAdd[g, 3]      Adding a new vertex makes a new graph with automatic coordinates. I tried to see if there is a way to define the coordinates when adding a new vertex but I could not find anything. Also I was looking if there is something like:               SetProperty[g, VectorCoordinates -> {list of coordinates}]      To set coordinates for all vertices in a graph, but I could not find anything.


title: How to combine elements of two matrices?

text: Given two matrices m1 and m2, e.g.:               m1 = {{a1, b1}, {c1, d1}}     m2 = {{a2, b2}, {c2, d2}}      How can one obtain the following?               {{f[a1, a2], f[b1, b2]}, {f[c1, c2], f[d1 ,d2]}}      I found this solution               MapThread[f, {m1, m2}, 2]      Is there a simpler way?


title: Question with ParametricNDSolveValue

text: When solving the following system:               g[a_,b_] := c /. FindRoot[a + b == c, {c, 0}]          pf =        ParametricNDSolveValue[{y''[x] == g[a,b] y[x] Cos[x + y[x]],          y[0] == a, y'[0] == 1}, Integrate[y[s]^2, {s, 0., b}], {x, 0, b}, {a, b}];      _Mathematica_ gives me two error messages, which say: > FindRoot::nlnum: The function value {0. +a+b}is not a list of numbers with > dimensions {1} at {c} = {0.}. >> > > ReplaceAll::reps: {FindRoot[a+b==c,{c,0}]} is neither a list of replacement > rules nor a valid dispatch table, and so cannot be used for replacing. >> How can I fix this issue?


title: Using the same frame ticks for two different histograms

text: Consider the following:               SetOptions[Histogram, BarOrigin -> Left,        Frame -> {{True, None}, {True, None}}, FrameTicks -> Automatic];          data1 = {Table[1, {i, 5}], Table[5, {i, 50}], Table[3, {i, 25}],         Table[4, {i, 20}]};     data2 = {Table[1, {i, 3}], Table[5, {i, 20}], Table[3, {i, 25}]};     data3 = {Table[1, {i, 3}], Table[5, {i, 20}], Table[4, {i, 15}]};          histo1 = Histogram[data1]     histo2a = Show[Histogram[data1, ChartElements -> None],Histogram[data2]]     histo3a = Show[Histogram[data1, ChartElements -> None],Histogram[data3]]          histo2b = Show[Histogram[data1], Histogram[data2, ChartStyle -> Red]]         histo3b = Show[Histogram[data1], Histogram[data3, ChartStyle -> Red]]      I would like to use the same frame/coordinate system for `histo2a` and `histo3a` as in `histo1`. `histo3b` shows how it should be (only without the grey part) and `histo2a` how it should not be. `histo2b`in addition shows the disadvantage of the `Show[]`-approach (one bar exceeds the frame). Due to the latter, I was trying to extract the FrameTicks-values from `histo1` and to use them for `Histogram[data2]` and `Histogram[data3] but neither`Options[histo1,FrameTicks]`,`AbsoluteOptions[histo1,FrameTicks]`nor`HistogramList[data1]` return help. Now I would like to use exactly the same frame ticks, which were calculated based on `data1` for `histo2`. Neither `Options[histo1,FrameTicks]`, `AbsoluteOptions[histo1,FrameTicks]` or `HistogramList[data1]` help. Has anyone an idea?


title: Generating a non-convex polyhedron from a list of vertex coordinates

text: I want to include a figure in a paper I am writing on Combinatorial Geometry which features a non-convex polyhedron given by the following vertices, EDIT: I was unaware that Mathematica could convert coordinates from spherical to Cartesian, so I will post the correct spherical coordinates as follows:               {{0, 0, 0}, {1, 0, 0}, {1, Pi/3, 0}, {1, Pi/3, ArcCos[1/3]},      {1, Pi/3, 2 ArcCos[1/3]}, {1, Pi/3, 3 ArcCos[1/3]},      {1, Pi/3, 4 ArcCos[1/3]}, {1, (2 Pi)/3, (ArcCos[1/3])/2},      {1, (2 Pi)/3, (3 ArcCos[1/3])/2}, {1, (2 Pi)/3, (5 ArcCos[1/3])/2},      {1, (2 Pi)/3, (7 ArcCos[1/3])/2}, {1, (2 Pi)/3, (9 ArcCos[1/3])/2}, {1, Pi, 0}}      Does anyone know how I can generate such a figure using Mathematica? I assume I will need to also somehow define which vertices are connected by an edge with a list, but I am unsure how I would do that as well. I have tried using the "Computational Geometry Package", and have been reading through the tutorial for about an hour, but I have no idea what a "vertex adjacency list" is or how I could make this work in 3-dimensions; the package tutorial seems to only comment on triangulations in the plane, etc. Any help is greatly appreciated! EDIT: I will attempt to describe this non-convex polyhedron and include pictures and a figure. ![Real image](http://i.stack.imgur.com/8d9hA.jpg) ![figure](http://i.stack.imgur.com/m4L7M.png) I will quote from my paper: > The inspiration for constructing a simplicial 3-complex $\mathcal{K}$ for > which 12 tetrahedra touch at a vertex comes from the configuration of 4 > tetrahedra sharing an edge; see Figure 3. Let $v_{0}=(0,0,0)$ be the origin > and connect the two vertices $v_{1}=(1,0,0)$ and $v_{12} = (-1,0,0)$ to > $v_{0}$ by an edge. Label these edges as $e(v_{0}v_{1})$ and > $e(v_{0}v_{12})$ and notice that their union forms a straight line of length > 2 in $\mathbb{E}^3$. Around each of these edges we arrange four tetrahedra > as in Figure 3, and we rotate the cluster of four tetrahedra sharing edge > $e(v_{0}v_{12})$ by $\pi/6$ in order to ensure that an extra four tetrahedra > will fit in between the two clusters of 4 tetrahedra (explained in more > detail later). Considering the vertices of these tetrahedra, we obtain a > point set $P$ (with $|P|=12$) where the minimum distance which can occur any > of the points is of unit length. Figure 3: in the context of my paper, this figure shows that at most 4 tetrahedra can share an edge with conditions I impose. If you imagine one of the tetrahedra removed so that there is a bigger space, these are the "clusters of 4 tetrahedra" I described above. ![figure 3](http://i.stack.imgur.com/GKAcn.png) * * * (The bonus question was solved, thank you Mr. Wizard.) BONUS: If anyone knows how to check with Mathematica if all of the points are at least a distance of 1 away from each other that would be very helpful.


title: Crash with subsetting TemporalData

text: The first line gets a single sample path for an M/M/1 queue for time between 0 and 100. No problem, I can plot it, etc.               td = RandomFunction[QueueingProcess[9, 10], {0, 100}, 1];      Next, I want to look at the sample path of the process between time 10 and 50, so I do               subset = td["Part", 1, {10, 50}];      and MMA crashes on me. Ver 9.0.1.0 on windows 7 64 bit. Any suggestions?


title: How to create animated snowfall?

text: Well, the title is self-explanatory. What sorts of snowfall can we generate using _Mathematica_? There are two options I suggest to consider: 1) Continuous GIF animations with smallest possible number of frames. 2) `Dynamic`-based animations.


title: Transparency rendering problems in Mathematica 10 (Mac)

text: For some weird reason, they apparently changed the styling of contours in ContourPlot for 10.0. Here is a comparison of the results for V9 and V10 (first 9, then 10):               ContourPlot[Sin[x y], {x, 0, 3}, {y, 0, 3},          ContourShading -> None,  ContourStyle -> {{Red, Thickness[0.008]}}]      ![Mathematica 9 output](http://i.stack.imgur.com/UUxhg.png) Version 9 ![Mathematica 10 output](http://i.stack.imgur.com/QxZ3N.png) Version 10 Firstly, can I override the coloring? I would like to keep the solid colors that were in V9. And secondly, where do those dark spots come from? Is this a bug? Edit: yes, this does look like a bug. The dark spots are only visible in the Mac version. Interestingly enough, for about half a second after the output appears, what I see on the screen is similar to what `Export` produces (shown below). The only difference is that the lines are thinner in the exported .png (another bug?). After those 0.5 seconds, another level of transparency kicks in and I see what is shown in the top picture below.               ContourPlot[Sin[x y], {x, 0, 3}, {y, 0, 3},          Contours -> {.9}, ContourShading -> None,          ContourStyle -> {{Red, Thickness[0.17]}}]      ![enter image description here](http://i.stack.imgur.com/3pz2e.png) <\- What I see. ![enter image description here](http://i.stack.imgur.com/9HQzI.png) <\- What `Export` produces.


title: How to incorporate a matrix in a For loop?

text: I would like the equivalent of:               For[x = 0, x less than Infinity, x++]             For[y = 0, y less than Infinity, y++]                 m = Table[(x, x-2 y, x-2 y, 0, 0, 0), (x-2 y, x, x-2 y, 0, 0, 0),                      (x-2 y, x-2 y, x, 0, 0, 0), (0, 0, 0, 2 y, 0, 0),(0, 0, 0, 0, 2 y, 0),                      (0, 0, 0, 0, 0, 2 y)]      I then would like to include an "if-else" statement where I print only the largest possible matrix. (i.e. If `m` is less than `m`, continue running through loop until it finds the largest `m`, then print it). I have another matrix, `l`, where I need to minimize the distance between `l` and `m`, hence requiring the largest possible matrix for `m`. Could you help me with this?


title: Using different random values at each recursion step

text: I have the following code:               ϕ[0] := π/4     ϕ[n_] := Exp[-n] ϕ[n - 1] + Sqrt[1 - Exp[-2 n]] M     M = RandomVariate[NormalDistribution[0, 1]]      For this recursion relation, is the normal deviate taking a random variable during each recursion or is it just taking one for the whole recursion process? Thanks,


title: Numerically integrating a list-valued function

text: I want to `NIntegrate` a `List` valued function `foo[x]` which is only defined for numerical arguments `x`. Here is a simple toy example:               foo[x_?NumericQ] := {x^2, x^3};     NIntegrate[foo[x], {x, 0, 1}]      It gives the following error > >     NIntegrate::inum: Integrand foo[x] is not numerical at {x} = > {0.00795732}. >> >     NIntegrate::inum: Integrand foo[x] is not numerical at {x} = > {0.00795732}. >>. >   Note that the symbolic definition `fooS` works fine:               fooS[x_] := {x^2, x^3};     NIntegrate[fooS[x], {x, 0, 1}]     (*{0.333333, 0.25}*)      What causes the error? It seems to be crucial that the function `foo` is `List` valued. When I `NIntegrate` each component separatly, the error does not occur:               foo1[x_?NumericQ] := foo[x][[1]];     foo2[x_?NumericQ] := foo[x][[2]];     {NIntegrate[foo1[x], {x, 0, 1}], NIntegrate[foo2[x], {x, 0, 1}]}     (*{0.333333, 0.25}*)      and even               NIntegrate[{#1, #2} & @@ {foo1[x], foo2[x]}, {x, 0, 1}]     (*{0.333333, 0.25}*)


title: How to find the domain and range of a function with Mathematica?

text: I'm studying calculus and in some exercises I am asked to find the domain and range of a function. Does _Mathematica_ have already a built-in function for this? I can imagine some ways of doing so, but at the moment I want to know if there's a built-in function or some easy way of doing it.


title: How to compute MIN$(A(x), B(x))$

text: I have two polynomials: $\;A(x) = \sum a_i\;x^i$, $\quad B(x) = \sum b_i\;x^i$.   Given $A(x)$, $B(x)$, I want to compute $\;C(x) = $MIN$(A(x), B(x)) = c_i\;x^i$ where $c_i = $MIN$(a_i, b_i)$. How can I do it automatically in _Mathematica_?


title: Creating custom functions with multiple arguments

text: I am hoping that this isn't a stupid question so feel free to vote it for closure. Google failed somehow. I want to define a custom function (more complicated than the usual `f[x_] := someExpression`) that performs several tasks (taking elements of a set, performing computations, etc.) before giving an output. I don't want to run the whole bunch of codes repeatedly. Is there a way of defining such a function? What I have in mind is, say a program in R, which goes like               function_name <- function(arg1, arg2, ..., argn){         routine 1         routine 2         routine 3         ...         Output to be returned     }      EDIT: In view of the comment that this question is somewhat vague, I am posting part of the code below:               Final = {{1}};     For[hn = 0, hn < 7, hn++;      rp = {0}; fn = hn;      For[fk = 0, fk < fn, fk++;        Clear[r, v, w, p, q, z, x, n, k, t, res, pt];        v[z_] := Sum[q^d, {d, 0, z - 1}];        n = fn; k = fk; t = {}; For[i = 0, i < (n - k), i++;          For[j = -1, j < k, j++; t = Join[t, {j}];]];        t = KSubsets[t, (n - k)];        For[i = 0, i < Length[t], i++;          t[[i]] = Sort[t[[i]]]];        t = Union[t];      The code is quite long (sloppy programming). I just want the whole thing to be given a name so that I can just type that name of that function and vary the arguments.


title: About minimizing calculations when using ComposeList

text: I have a lot of functions to use in a iterative way, and I need some of the calculation results. For example:                func = Function[{s}, s Sin[#] &] /@ Range[100];      ComposeList[func, x][[1 ;; ;; 10]]       Apparently, this code calculates much more than necessary. Especially, a lot of time is needed for the calculation when the length of `func` list is very long and when the `Function` is very complicated (e.g. `Length@func = 1024` and the function is `Fourier`); **Is there any elegant way to reduce the calculation?** _**Edit_** Perhaps I should say more about the fact that this code calculates than necessary. For example,                 func = Function[{s}, s Sin[#] &] /@ Range[10];        result=ComposeList[func, x][[1 ;; ;; 5]]      (* {x, 5 Sin[4 Sin[3 Sin[2 Sin[Sin[x]]]]], 10 Sin[9 Sin[ 8 Sin[7 Sin[6 Sin[5 Sin[4 Sin[3 Sin[2 Sin[Sin[x]]]]]]]]]]} *) Now we can see that result[[2]] (i.e., 5Sin[4 Sin[3 Sin[2 Sin[Sin[x]]]]]) is also appeared inside result[[3]] (i.e., 10Sin[...5Sin[4 Sin[3 Sin[2 Sin[Sin[x]]]]]], so the evaluation for 5Sin[4 Sin[3 Sin[2 Sin[Sin[x]]]]] is repeated twice here. The repetition will be very large with an increase of Length[func], which will be much more time-consuming than it is required. This is my point here (Up to now, Rojo has gotten the point and solved it ).


title: Assumptions with D

text: I want to give assumptions for the `D` function. Say I want to calculate $\frac{d|x|}{dx}$ for $x>0$, which is 1. I write `D[Abs[x], x, Assumptions -> x > 0]` which gives `D::optx: Unknown option Assumptions in D[Abs[x],x,Assumptions->x>0]. >>` Why doesn't D take assumptions?


title: Clickable Bounded Diagram

text: Suppose I make a `BoundedDiagram` via the following code               Needs["ComputationalGeometry`"];     data2D = RandomReal[{0, 10}, {10, 2}];     b1 = {{0, 0}, {11, 0}, {11, 11}, {0, 11}};     convexhull = ConvexHull[data2D];     delval = DelaunayTriangulation[data2D];     {vorvert, vorval} = VoronoiDiagram[data2D];     {dvert1, dval1} = BoundedDiagram[b1, data2D, delval, convexhull];     DiagramPlot[data2D, dvert1, dval1]      How would I go about making each region clickable, i.e. open some link that I associated with the data? \-- Edit: I should note, all I really want is a to be able to click on regions of a Voronoi-Like diagram, it doesn't have to be done via BoundedDiagram, this is just my first attempt at doing that ... (and is basically straight from the documentation.)


title: Calculating the volume under a surface with Riemann sum

text: I have a set of xyz data points. X and Y are coordinates of a regular grid of 10x10 units, Z is the independent variable. I am trying to calculate the volume under the set of points, using Riemann sum. I have used two approaches that I expected to produce the same result, and on the contrary, produce very different results. In the first approach I make a sum of the volumes of the prism formed by every point. In the second approach I make an interpolation function with an interpolation order of 0, and then integrate it. Here is a MWE of the code I'm using:               Data = {{{230, 310}, 0.4434}, {{230, 320}, 0.5078}, {{230, 330},      0.6000}, {{230, 340}, 0.6430}, {{230, 350}, 0.6724}, {{230, 360},      0.7204}, {{230, 370}, 0.7593}, {{230, 380}, 0.7987}, {{230, 390},      0.8908}, {{230, 400}, 1.0175}, {{230, 410}, 1.1136}, {{230, 420},      1.2342}, {{230, 430}, 1.3375}, {{230, 440}, 1.4055}, {{230, 450},      1.3979}, {{240, 310}, 0.4593}, {{240, 320}, 0.3963}, {{240, 330},      0.3985}, {{240, 340}, 0.3877}, {{240, 350}, 0.4262}, {{240, 360},      0.4763}, {{240, 370}, 0.5465}, {{240, 380}, 0.6163}, {{240, 390},      0.7376}, {{240, 400}, 0.8567}, {{240, 410}, 0.9769}, {{240, 420},      1.1350}, {{240, 430}, 1.2960}, {{240, 440}, 1.4032}, {{240, 450},      1.4310}, {{250, 310}, 0.5866}, {{250, 320}, 0.4513}, {{250, 330},      0.3789}, {{250, 340}, 0.3360}, {{250, 350}, 0.3273}, {{250, 360},      0.3526}, {{250, 370}, 0.4068}, {{250, 380}, 0.4520}, {{250, 390},      0.5269}, {{250, 400}, 0.6071}, {{250, 410}, 0.6807}, {{250, 420},      0.7808}, {{250, 430}, 0.8794}, {{250, 440}, 0.9572}, {{250, 450},      0.9682}};          Total[Data[[All, 2]]*100]          Integrate[Interpolation[Data, InterpolationOrder -> 0][x, y], {x, 230, 250}, {y, 310, 450}]      The first approach yields a volume of 3377.73, and the second one of 1918.94. Can someone explain the reason for this difference? Or which one is more appropriate for the purpose of estimating a volume? Any help will be very much appreciated.


title: How can I dynamically get a file whenever it is saved in Workbench?

text: I want to get a file once and only once at the start of a coding session. Then, whenever I save the file in the Wolfram Workbench, have it be gotten automatically. How can I construct such a utility?


title: Why doesn't Abs simplify further?

text: Why does this:               Simplify[Abs[x + I], Element[x, Reals]]      give me               Abs[x + i]      Is there a way to force Mathematica to give me the following answer? $\sqrt{x^2+1}$


title: X label in GraphicsColumn is cut off

text: I'm trying to use GraphicsColumn to plot two curves with very different ranges. for example,               GraphicsColumn[{Plot[Sin[x], {x, 0, 10}, PlotRange -> All,         AspectRatio -> 0.3, Frame -> True, Axes -> False,         ImageMargins -> 20],        Plot[Cos[x], {x, 0, 10}, PlotRange -> All, AspectRatio -> 0.3,         Frame -> True, Axes -> False, ImageMargins -> 20]},       Epilog -> {Text["Frequency", {Center, Bottom}],         Rotate[Text["Power", {0.5, Center}], 90 Degree]}]      But the x label is not displayed properly, i.e., it is cut by the edge of the graph. ![enter image description here](http://i.stack.imgur.com/yAVbL.jpg) How to improve it?


title: Integration strategies for oscillatory multidimensional function

text: I am seeking to integrate a highly oscillatory, multidimensional function. I am currently using NIntegrate's QuasiMonteCarlo approach. However, this is time-consuming and, given my current resources, not very accurate. How can I obtain more reliable estimates of the beasty integral given below? As the function itself will be integrated at a later stage, I am also interested in speeding up the function evaluation. The integral to be solved:               fun[r_?NumericQ, d_?NumericQ, c_, opts:OptionsPattern[]]:=        NIntegrate[           Cos[(c (d^2+r^2-2 d r Cos[ta] - 3 ((-r+d Cos[ta]) Cos[tb]+d Cos[a] Sin[ta] Sin[tb])^2)) / Abs[d^2+r^2-2 d r Cos[ta]]^(5/2)]            Cos[(c (d^2+r^2+2 d r Cos[ta] - 3 ((r+d Cos[ta]) Cos[tb]+d Cos[a] Sin[ta] Sin[tb])^2)) / Abs[d^2+r^2+2 d r Cos[ta]]^(5/2)]           * Sin[ta]*Sin[tb]/(2*Pi),        {ta,0,Pi},        {tb,0,Pi/2},        {a,0,Pi},        Evaluate@FilterRules[{opts},Options[NIntegrate]]     ]      Typically, $d$ = 2, $r$ is in the range from 0 to Infinity (with the small values and $r$=$d$ posing problems), and $c$ is in the range from 100 to 3000. A typical function call is:               AbsoluteTiming[fun[3, 2, 400, Method -> "QuasiMonteCarlo", PrecisionGoal -> 6,      MaxPoints -> 40000000]]     (* -> {102.3215798,-0.00442278} *)      This issues a NIntegrate::maxp warning and indicates an error estimate of 0.00011. Using the default strategy I obtain:               AbsoluteTiming[      fun[3, 2, 400, MaxRecursion -> 20, Method -> {GlobalAdaptive, MaxErrorIncreases -> 10000}]]     (* -> {9.3912165,-0.00439357} *)      and a NIntegrate::eincr warning. Estimated error: 0.0369. How to proceed from here? Thank you for your help.


title: Figuring out how AbsoluteOptions works with Graphs

text: I am puzzled by how `AbsoluteOptions` works with `Graph` objects. I would have expected that one could use it to obtain all the options used to draw a graph. There are several ways in which it behaves contrary to my expectations. First, let' s make a simple graph, g, and set some custom options:               g = RandomGraph[{6, 11}, VertexStyle -> {1 -> Red, 2 -> Green},          VertexSize -> {1 -> Large, 2 -> Large}, VertexLabels -> "Name",          ImagePadding -> 15, EdgeLabels -> "Name", Axes -> True]      ![g](http://i.stack.imgur.com/cfx2X.png) **1 - Why won' t all the options work again?** One expects that the options used for `g` could be obtained through `AbsoluteOptions[g]` and redeployed. However, this does not work. Either the code below locks up completely or the Out cell has a tooltip: "$Failed is not a Graphics primitive or directive".               allOptions = AbsoluteOptions[g];     g2 = Graph[EdgeList[g], allOptions]      **2 - Some options work as expected, others do not. Why?** Let's take a subset of the options of `g`; namely, `{VertexCoordinates, EdgeLabels, Axes, VertexLabels, VertexSize, AlignmentPoint, ImagePadding}`. Now let's compare g and the partial replication, g3, side by side:               someOptions =        Sort@AbsoluteOptions[         g, {VertexCoordinates, EdgeLabels, Axes, VertexLabels, VertexSize,          AlignmentPoint, ImagePadding}]     g;     g3 = Graph[EdgeList[g], someOptions]     someOptions3 =           Sort@AbsoluteOptions[          g3, {VertexCoordinates, EdgeLabels, Axes, VertexLabels, VertexSize,          AlignmentPoint, ImagePadding}]          (* Out someOptions3*)     {AlignmentPoint -> Center, Axes -> {True, True},         EdgeLabels -> {"Name"}, ImagePadding -> 15.,         VertexCoordinates -> {{0.518253, 0.817802}, {1.61587,         0.866512}, {2.05896, 0.336143}, {1.03973, 1.21024}, {1.04431, 0.}, {0., 0.377097}},           VertexLabels -> {"Name"},      VertexSize -> {1 -> Large, 2 -> Large}}      ![g and g3](http://i.stack.imgur.com/xfqQd.png) The vertex sizes are the same in each case, as expected. Also, the `VertexStyle` is different. That's fine: g3 has the default vertex style. But why are the vertices in different locations? After all, we passed the `VertexCoordinates` option to g3. And the vertex coordinates returned by `AbsoluteOptions[g3...` do not correspond to the coordinates used for the vertices. **3 - What are failed options?** If we inspect the options used by g, we will notice that two of them failed, even though `g` was drawn with no apparent issues.               AbsoluteOptions[g, {VertexShapeFunction, EdgeShapeFunction}]          (* Out *)     {VertexShapeFunction -> $Failed, EdgeShapeFunction -> $Failed}      If you look at the graph, g, you see that the default vertex shapes and edge shapes were correctly rendered? So, whence the fail? **4 - Why is it insufficient to remove failed options?** If we remove the failed options and try to implement all the other options, MMA does one of two things: (1) It returns the unparsed `Graph` command or (2) it produces only a small portion of the graph, g. Any help would be appreciated. I'm not trying to correct a particular program but rather understand the strengths and limitations of `AbsoluteOptions.`


title: Sharpening extrema using DensityPlot

text: I have a data set where I really care mainly about visualizing the highest and lowest areas. DensityPlot suits my needs well, but ideally the maxima and minima would pop more from the rest of the data. I know that DensityPlot scales the data from your function to between zero and one before coloring it accordingly. I'd like to use a scaling that has more meat in the middle than theirs. So I was thinking I could take their scaling, and use it as an input to for example                (x-0.5)^3/8,       which has the properties `f[0]=0` and `f[1]=1`, but is better distributed for my purpose. Then I'd pass these values to the colorizer. Can't really figure out how to do this though. Any thoughts?


title: Tips on giving a lecture course using Mathematica

text: I've had a look at this question on giving presentations with Mathematica which is very useful on the technical side of setting up slideshows. However, my question is more about the integration of Mathematica with good teaching style. I shall shortly be giving an undergraduate lecture course on Mathematical Methods to engineers and others from non pure maths disciplines (it'll be from integration onwards) and am planning on using Mathematica as a teaching tool. One has to be careful with not letting technology take the place of good teaching but I would like to be able to use Mathematica effectively for showing the structure of a problem and the parametric dependencies of functions etc. - the perfect place for plenty of `Manipulate` usage. I hope to give at least 90% of my lectures in Mathematica and the rest on a blackboard - this is a wild estimate but it's what I'm aiming for. I would be grateful if anyone has undertaken such an exercise to give me possible pitfalls and pointers as to the best methods they've found to make Mathematica bring the maths to life, rather than confuse the students with a mass of fast-paced buttons, dynamic displays and notation. P.S I saw also this question on lecture courses with Mathematica, however again, these are examples and not descriptions of what went well and what didn't.


title: How to Show the "TemperatureMap" using Manipulate?

text: How to show the "TemperatureMap" in Manipulate?. ONLY the image, without text "ColorData..."               Manipulate[ Column[{Style["This is a Test... " -> DateString[] -> "  -  " -> i^2,18, Bold], Style["How to show ONLY the image of TemperatureMap in the last row?", 18,Darker@Red, Bold], ColorData["TemperatureMap"]}], {i, 1, 5}]      ![Temperature in Manipulate](http://i.stack.imgur.com/YBEfj.jpg)


title: Easy button or hot key to switch between `Working` and `SlideShow` Screen Environments to avoid trip to menu

text: When I edit a slide show it easy to copy whole slides in `Working` Screen Environment but nice to preview slides in `SlideShow` Screen Environment. ![enter image description here](http://i.stack.imgur.com/xo8ZD.png) _Mathematica_ has convenient interactive buttons to go to Full Screen mode and change slides. ![enter image description here](http://i.stack.imgur.com/5lyQy.png) **Is it possible to set up an easy button or hot key to switch between`Working` and `SlideShow` Screen Environments to avoid trips to menu? Maybe using `DockedCells` ? Any similar ideas ?**


title: Graphical solution of a a two-variable system containing an equation and an inequality

text: I'm currently studying atmospheric-gravity waves and their dispersion relations. I want to have look at values of $(x,y)$ that solve the following system : \begin{equation}\label{}(1) \left\\{ \begin{array}{rcr} (x+\frac{1}{2}y^{2})\exp(u^2)-y[u+\exp(u^2)]+u\exp(u^2)& = &0\\\ 2u(x+\frac{1}{2}y^{2})\exp(u^2)-y[1+u\exp(u^2)]+u^2& < &0\\\ \end{array} \right. \end{equation} where $x\in [0,1]$, $y\in[0,1]$ and $u\in[0,1]$. My goal is to plot the region $(x,y)$ where this system has a solution. How can I plot S in the $(x,y)$-plane.? The code for the first funtion :               f1[u_, x_, y_] := ((y^2)/2 + x)*Exp[u^2] - y*(u + Exp[u^2]) + u*Exp[u^2]     f2[u_, x_, y_] := 2*u*((y^2)/2 + x)*Exp[u^2] - y*(1 + u*Exp[u^2]) +  u^2      The problem is how to used : ContourPlot or RegionFunction to construct the surface S.


title: NMinimize stops with no more memory?

text: I am using NMinimize function for simulation based optimization. So my objective function is a simulation that runs for every combination of variable values evaluated by NMinimize function. However, the problem I have is the Nminimize function ceases after the first run (I am printing the time stamp for every iteration) and eventually after a long time gives me out of memory error. I even tried with different methods such as "RandomSearch" and "SimulatedAnnealing" with custom method parameter values, but in vain. Can some one pinpoint where I am going wrong? edit: My code is long, but as requested is given below:               f[a1_, a2_, a3_] := Module[{b1 = a1, b2 = a2, b3 = a3, L = 3, Flen = 1, Rlen = 1,SimTime = 60, Kj = 150,w = 20,Theta = 5, dt = 6,delta = 1,DemandDuration = 10,RMstart = 1,RMLocation = 3, TT = 0},           Print[DateString[]]; Vf = Theta w; dx = Vf dt/3600; capacity = w*Vf*Kj/(Vf + w);n = Round[Flen/dx];m = Round[SimTime/dt];p = Round[Rlen/dx];Rdensity = Table[0*i, {i, p}, {i, m}, {i, n}];Rflow = Table[0*i, {i, p}, {i, m}, {i, n}];Fdensity = Table[0*i, {i, n}, {i, m}];Fflow = Table[0*i, {i, n}, {i, m}];demand[n_, k_] := Min[k*Vf, n*capacity];supply[n_, k_] := Min[(n*Kj - k)*w, n*capacity];flo[demand_, supply_] := Min[demand, supply];den[k_, qin_, qout_] := k + (qin - qout)/Vf;     merge[n_, Fu_, Fd_, Rd_] := Min[1, supply[n, Fd]/(demand[n, Fu] + 0.01)]*demand[1, Rd]/delta;Nsupply[n_, k_, qsum_] := Min[(n*Kj - k)*Vf - qsum, n*capacity];     RM[x_, t_] := N[b1 x^2 + b2 x + b3];alpha[a_] := 1500*a/Flen;beta[a_] := 0.1*a/Flen;          For[k = 1, k <= n, k++,      For[i = 1, i <= p, i++, Rdensity[[i, 1, k]] = 0;];     For[j = 1, j <= DemandDuration, j++, Rdensity[[p, j, k]] = alpha[n*dx]*delta/Vf;     TT = TT + Rdensity[[p, j, k]]];];          For[j = 1, j <= 4, j++,      For[k = 1, k <= n, k++,      If[k == 1,        Rflow[[1, j, k]] =         merge[L, Fdensity[[k, j]], Fdensity[[k, j]],          Rdensity[[1, j, k]]],        Rflow[[1, j, k]] =         merge[L, Fdensity[[k, j]], Fdensity[[k - 1, j]],          Rdensity[[1, j, k]]]];      If[k == 1,        Fflow[[k, j]] =         flo[demand[L, Fdensity[[k, j]]], supply[L, Fdensity[[k, j]]]],        Fflow[[k, j]] =         flo[demand[L, Fdensity[[k, j]]],          supply[L, Fdensity[[k - 1, j]]] - Rflow[[1, j, k - 1]]*dx]];      If[k > 1 && j < m,        Fdensity[[k - 1, j + 1]] =         den[Fdensity[[k - 1,           j]], (Rflow[[1, j, k - 1]] - beta[(n)*dx]*Fflow[[k, j]])*dx +           Fflow[[k, j]], Fflow[[k - 1, j]]];       TT = TT + Fdensity[[k - 1, j + 1]];];      If[k == n && j < m,        Fdensity[[k, j + 1]] =         den[Fdensity[[k, j]], Rflow[[1, j, k]]*dx, Fflow[[k, j]]];       TT = TT + Fdensity[[k, j + 1]];];      For[i = 2, i <= p, i++,        If[i == RMLocation && j >= RMstart,         Rflow[[i, j, k]] =          Min[RM[k dx, j dt],           flo[demand[1, Rdensity[[i, j, k]]],            supply[1, Rdensity[[i - 1, j, k]]]]],         Rflow[[i, j, k]] =          flo[demand[1, Rdensity[[i, j, k]]],           supply[1, Rdensity[[i - 1, j, k]]]]];       If[j < m,         Rdensity[[i - 1, j + 1, k]] =          den[Rdensity[[i - 1, j, k]], Rflow[[i, j, k]],           Rflow[[i - 1, j, k]]];        TT = TT + Rdensity[[i - 1, j + 1, k]];]];];];     For[j = 5, j <= m, j++,      For[k = 1, k <= n, k++,      If[k == 1,       Rflow[[1, j, k]] =        merge[L, Fdensity[[k, j]], Fdensity[[k, j]],         Rdensity[[1, j, k]]],       Rflow[[1, j, k]] =        merge[L, Fdensity[[k, j]], Fdensity[[k - 1, j]],         Rdensity[[1, j, k]]]];     FQsum = 0;     For[r = 1, r <= Theta - 1, r++, FQsum = FQsum + Fflow[[k, j - r]]];     If[k == 1,       Fflow[[k, j]] =        flo[demand[L, Fdensity[[k, j]]], supply[L, Fdensity[[k, j]]]],       Fflow[[k, j]] =        flo[demand[L, Fdensity[[k, j]]],         Nsupply[L, Fdensity[[k - 1, j - Theta + 1]], FQsum] -          Rflow[[1, j, k - 1]]*dx]];     If[k > 1 && j < m,       Fdensity[[k - 1, j + 1]] =        den[Fdensity[[k - 1,          j]], (Rflow[[1, j, k - 1]] - beta[(n)*dx]*Fflow[[k, j]])*dx +          Fflow[[k, j]], Fflow[[k - 1, j]]];      TT = TT + Fdensity[[k - 1, j + 1]];];     If[k == n && j < m,       Fdensity[[k, j + 1]] =        den[Fdensity[[k, j]], Rflow[[1, j, k]]*dx, Fflow[[k, j]]];      TT = TT + Fdensity[[k, j + 1]];];     For[i = 2, i <= p, i++, RQsum = 0;      For[r = 1, r <= Theta - 1, r++,        RQsum = RQsum + Rflow[[i, j - r, k]]];      If[i == RMLocation && j >= RMstart,        Rflow[[i, j, k]] =         Min[RM[k dx, j dt],          flo[demand[1, Rdensity[[i, j, k]]],           Nsupply[1, Rdensity[[i - 1, j - Theta + 1, k]], RQsum]]],        Rflow[[i, j, k]] =         flo[demand[1, Rdensity[[i, j, k]]],          Nsupply[1, Rdensity[[i - 1, j - Theta + 1, k]], RQsum]]];      If[j < m,        Rdensity[[i - 1, j + 1, k]] =         den[Rdensity[[i - 1, j, k]], Rflow[[i, j, k]],          Rflow[[i - 1, j, k]]];       TT = TT + Rdensity[[i - 1, j + 1, k]];]];];];          TT]          NMinimize[{f[x, y, z], {x, y,z} \[Element] Integers}, {{x , 27, 30}, {y, 797, 800}, {z, 2497, 2500}}];      Ps. Also any suggestions to improve the performance of this code will be greatly appreciated!!


title: Calling functions which take their arguments interactively

text: Lets say I have a file named `test.m` containing some functions.               test[arg1_, arg2_] := (       Print[arg1];       Print[arg2];     )     test3[arg1_, arg2_] := (       Print[arg1];       Print[arg2];     )      What would be a good way to generate a list of butons that would allow you to invoke the functions easily? For example. ![enter image description here](http://i.stack.imgur.com/3l0yK.png) The tricky part here (and is mainly why I am asking this question) is calling the functions, which will have several different argument types? I had thought about using an `InputField` with a `MessageDialog`, but I would bet there is better way to incorporate _Mathematica_ 's features.               ClearAll[loadFile];     loadFile[path_String?FileExistsQ] := DeleteCases[ToExpression[         FromCharacterCode[BinaryReadList[path]]         , InputForm, HoldComplete], Null];     x = ReleaseHold[        loadFile["test.m"] /.         HoldPattern[sym_[args__] := eval_] :>          Button[sym, eval]        ];     x[[0]] = List;     x


title: How to get list of duplicates when using DeleteDuplicates?

text: This might be easy, but can't find a way to use `DeleteDuplicates` to get also list of the actual duplicates. Example:               lstA = {1, 2, 4, 4, 6, 7, 8, 8};     r = DeleteDuplicates[lstA]     (* {1, 2, 4, 6, 7, 8} *)      I also wanted to get list of the actual duplicates, which are `{4,8}` in this example. It would have been nice if `DeleteDuplicates` would also return those, but there is no option there for that. I do not know what many Mathematica functions do not return back more useful information when called. Many seem to return one piece of information only, and one has to call another function to get another piece of information. For example, here `DeleteDuplicates` could had an API like this               {r,d}=DeleteDuplicates[lst]      and `r` will contain the list after duplicates are moved, but `d` would contain the actual list of duplicates. To make it even more useful, it can be               {r,d,p}=DeleteDuplicates[lst]      Where `p` will be the positions of the duplicates in the original list. Matlab seems to do it this way. Many functions there can return more than one piece of information at a time. This might be due to WL being functional programming language, and designed for cascading function calls, where each function only does one thing at a time. I am not sure now. DeleteDuplicates.html


title: How to efficiently process pasted content from PDF

text: I had selected a matrix in a PDF file, ![Mathematica graphics](http://i.stack.imgur.com/rg5tt.png) and paste it onto my MMA notebook. Below is the exact copy-pasted content:               0.9034 "NAN" 0.7163 0.8588     0.3031 0.5827 0.2699 0.8063     0.0418 0.8426 "NAN" 0.8634     "NAN" 0.8913 0.0662 0.8432      I want to display this content in the matrix form as shown in the original PDF. Thankfully there was no distortion when the content was transferred; however, the white spaces now became implied multiple signs in MMA. ![Mathematica graphics](http://i.stack.imgur.com/3I5dx.png) * * * **My solution** **1)** Convert content to string by simply wrapping it in `""` **2)** I then ran into the problem of the `"NAN"`'s becoming apart from the overall string due to its being wrapped by a pair of `""` previously. I couldn't find a quick way to assimilate them back into the larger string but to manually modify them (by adding a pair of `\`'s such that `"NAN"` became `\"NAN\"`: ref) ![Mathematica graphics](http://i.stack.imgur.com/LMHz5.png) ![Mathematica graphics](http://i.stack.imgur.com/1xn1T.png) ![Mathematica graphics](http://i.stack.imgur.com/VE1aQ.png) **3)** Use `StringSplit` twice, first to split the string at each line break `"\n"` to create 4 "lines"/sublists, and then map it the second time to each line at the `","` to create separate elements for each line.               StringSplit[#, {" "}] & /@ StringSplit[%, "\n"]     (* {{"0.9034", "\"NAN\"", "0.7163", "0.8588"}, {"0.3031", "0.5827",        "0.2699", "0.8063"}, {"0.0418", "0.8426", "\"NAN\"",        "0.8634"}, {"\"NAN\"", "0.8913", "0.0662", "0.8432"}} *)      **4)** Replace each `"\"NAN\""` with a simple `"NAN"`               % /. "\"NAN\"" :> "NAN"     (* {{"0.9034", "NAN", "0.7163", "0.8588"}, {"0.3031", "0.5827", "0.2699",        "0.8063"}, {"0.0418", "0.8426", "NAN", "0.8634"}, {"NAN", "0.8913",        "0.0662", "0.8432"}} *)      **_Sidestep_** : I tried to do this step more generally (since the string enclosed by `\"` might be more varied in future cases), by doing this:               % /. "\""~~x___~~"\"" :> x      This did not work, probably because `ReplaceAll` couldn't handle more complex string replacements (e.g. involving blanks). As a result, I tried `StringReplace`, and it worked as expected:               Map[StringReplace[#, "\"" ~~ x___ ~~ "\"" :> x] &, %, {2}]     (* {{"0.9034", "NAN", "0.7163", "0.8588"}, {"0.3031", "0.5827", "0.2699",        "0.8063"}, {"0.0418", "0.8426", "NAN", "0.8634"}, {"NAN", "0.8913",        "0.0662", "0.8432"}} *)      **One-step summary**               Map[StringReplace[#, "\"" ~~ x___ ~~ "\"" :> x] &,        StringSplit[#, {" "}] & /@ StringSplit["0.9034 \"NAN\" 0.7163 0.8588         0.3031 0.5827 0.2699 0.8063         0.0418 0.8426 \"NAN\" 0.8634         \"NAN\" 0.8913 0.0662 0.8432", "\n"], {2}] // MatrixForm      ![Mathematica graphics](http://i.stack.imgur.com/btfQe.png) * * * **My question is:** Could anyone help me think of a more elegant/efficient way to get the same result? The greatest bottleneck, I think, is the manual adding of `\`'s, so I'd love to hear how you can do that programmatically.


title: Is there a built-in procedure for simultaneous diagonalization of a set of commuting matrices?

text: Given a set $\\{A_1,...,A_m\\}$ of $m$ commuting $N\times N$ diagonalizable matrices, it is known that there exists a basis of eigenvectors $\Lambda$ that simultaneously diagonalizes all the $A_i$. Is there an automated way to compute $\Lambda$ in Mathematica? For a pair of matrices $\\{A_1,A_2\\}$ it can be done "by hand" using `Eigenvectors` to first compute the eigenvectors $\Lambda_1$ of $A_1$, finding similarity transforms $P_k$ that act on the degenerate subspaces of $\Lambda_1$ to make them also eigenvector of $A_2$, and then combining the transformed degenerate subspaces together to form $\Lambda$, but I don't know how to generalize this to more than 2 matrices.


title: Plotting implicitly-defined space curves

text: It is known that space curves can either be defined parametrically, $$\begin{align*}x&=f(t)\\\y&=g(t)\\\z&=h(t)\end{align*}$$ or as the intersection of two surfaces, $$\begin{align*}F(x,y,z)&=0\\\G(x,y,z)&=0\end{align*}$$ Curves represented parametrically can of course be plotted in _Mathematica_ using `ParametricPlot3D[]`. Though implicitly-defined plane curves can be plotted with `ContourPlot[]`, and implicitly-defined surfaces can be plotted with `ContourPlot3D[]`, no facilities exist for plotting space curves like the intersection of the torus $(x^2+y^2+z^2+8)^2=36(x^2+y^2)$ and the cylinder $y^2+(z-2)^2=4$: ![torus-cylinder intersection](http://i.stack.imgur.com/ODFj1.png) Sometimes, one might be lucky and manage to find a parametrization for the intersection of two algebraic surfaces, but these situations are few and far between, especially if the two surfaces are of sufficiently high degree. The situation is worse if at least one of the surfaces is transcendental. > How might one write a routine that plots space curves defined as the > intersection of two implicitly-defined surfaces? It would be preferable if the routine returns only `Line[]` objects representing the space curve. A routine that handles only algebraic surfaces would be an acceptable answer, but it would be nice if your routine can handle transcendental surfaces as well. A bonus feature for the routine might be the ability to determine if the two surfaces given do _not_ have a space curve intersection, or intersect only at a single point, or other such degeneracies.


title: Plotting a curve in 3D

text: Say I have two polynomials in $\mathbb{R}[X,Y,Z]$, whose intersection of zero loci correspond to a curve in the 3D space. What is the best way to plot the curve? ## Example: $$ f = X^2+Y^2-Z^2, \qquad g = 2X^3+Y^3-Z $$ I want to plot the curve given by $$ \begin{cases} &X^2+Y^2=Z^2 \\\\\\\ &2X^3+Y^3=Z \end{cases} $$


title: How can I commit files to Github by Mathematica?

text: # How can I publish Notebooks to Github via using Mathematica? * * * I'm on windows 8.1 x64, _Mathematica_ 9. How can I upload the current notebook to Github? My function expected is: `Notebook2Github[EvaluationNotebook[]]` Now I've installed Github on Windows, and have one test page The **annoying** thing is that each time I added/modified a new file in the destination folder(`E:\Users\HyperGroups\Documents\GitHub\hypergroups.github.com`), I should open GitHub, and add something into the `uncommitted changes` fields and click the `sync` button(shown in the picture) ![enter image description here](http://i.stack.imgur.com/10jQA.png) How can I avoid doing that and complete all such things by the function `Notebook2Github`. * * * ### My tries in Git Shell I can use the following commands in the GitShell. `git add [new file]` /`git commit` and `git push` and the new file will be updated to GitHub.


title: Deleting parts of a large list

text: At present I am running an analysis on economic data. Within the data I was able to identify countries which went through recession. I then calculated for example the average decline rate of GDP during recession. All my results are in the following list:               CompleteQuarterlyStatData      In this list I had to keep also all the countries which did not go through a recession. So if I ask for the decline rate of Australia during recession I get the following answer:               In[1328]:= CompleteQuarterlyStatData[[1]][[1]][[1]]          Out[1328]= {{"Australia", "AUS", "other countries", "GDP","quarterly data"}, {}}      Whereas position 1 (`CompleteQuarterlyStatData[[i]]`) indicates the key figure (in the above example "decline rate during recession"), position 2 (`CompleteQuarterlyStatData[[i]][[j]]`) the economic indicator (in the above example "GDP") and position 3 (`CompleteQuarterlyStatData[[i]][[j]][[k]]`) the country (in the above example "Australia"). (by the way: In total I have nine key figures (so `i` ranges from 1 to 9), 24 economic indicators (`j` ranges from 1 to 24) and 32 countries (`k` ranges from 1 to 32)) As Australia obviously did not got through a recession I want to get rid of all key figures for Australian GDP, which works with the following code:               If[      NumberQ[CompleteQuarterlyStatData[[1]][[1]][[2]][[2]]] == False,       Table[       Delete[CompleteQuarterlyStatData, i],       {i,        Map[        Part[#, 1 ;; 3] &,         Position[CompleteQuarterlyStatData,CompleteQuarterlyStatData[[1]][[1]][[2]][[1]]]]       }      ]     ];      (Note: Position 2 of `CompleteQuarterlyStatData[[1]][[1]][[2]]` is `{}` and `CompleteQuarterlyStatData[[1]][[1]][[2]]` `{"Australia", "AUS", "other countries", "GDP","quarterly data"}`. (see Out[1328])) So what all countries, which did not go through a recession or a longterm decline, have in common is, that `CompleteQuarterlyStatData[[1]][[EcoIndicator]][[Country]][[2]]` is always of the value `{}`. (Note: `CompleteQuarterlyStatData[[1]]` refers to the key figure "decline rate during recession".) To get rid of all countries which did not suffer from a longterm decline in a given economic indicator I could wrap `Table` around my if-procedure to go through all economic indicators and countries:               Table[     Table[        If[      NumberQ[CompleteQuarterlyStatData[[1]][[EcoIndicator]][[Country]][[2]]] == False,       Table[       Delete[CompleteQuarterlyStatData, i],       {i,        Map[        Part[#, 1 ;; 3] &,         Position[CompleteQuarterlyStatData,CompleteQuarterlyStatData[[1]][[EcoIndicator]][[Country]][[1]]]]       }      ]     ]     ,{Country,Length[CompleteQuarterlyStatData[[1]][[EcoIndicator]]]}]     ,{EcoIndicator,Length[CompleteQuarterlyStatData[[1]]]}];      But that does not work. Does anyone has a suggestion? In fact it would be nice to have something like `Delete[CompleteQuarterlyStatData,ArrayXXX]` whereas `ArrayXXX` represents the position of all countries (which did not go through a longterm decline) within `CompleteQuarterlyStatData`. * * * For better understanding I created an example:               list = {       {        {{{"Australia","GDP"},{}}, {{"Korea","GDP"},-2.45}, {{"USA","GDP"},-2.34}},        {{{"Australia","GDP"},2.34}, {{"Korea","GDP"},1.23}, {{"USA","GDP"},1.45}}       },       {        {{{"Greece", "Imports"},3.25}, {{"Turkey","Imports"}, {}}, {{"USA","Imports"},-2.64}},        {{{"Greece", "Imports"},-1.23}, {{"Turkey","Imports"},3.56}, {{"USA","Imports"},-1.56}}       }     };      The output of `list[[1]][[1]][[1]]` or `list[[2]][[1]][[2]]` matches the pattern `{_,{}}`. In that case I would like not only to delete those parts of list witch matches the pattern `{_,{}}` but also all other key figures which were calculated for the individual country and economic indicator. The result should then be:               {       {        {{{"Korea","GDP"},-2.45}, {{"USA","GDP"},-2.34}},        {{{"Korea","GDP"},1.23}, {{"USA","GDP"},1.45}}       },       {        {{{"Greece", "Imports"},3.25}, {{"USA","Imports"},-2.64}},        {{{"Greece", "Imports"},-1.23}, {{"USA","Imports"},-1.56}}       }     };      The reason: Australia did not go through a longterm decline in GDP, neither did Turkey in imports (if so, all other key figures concerning Australia & GDP or Turkey & imports would be irrelevant for further calculation).


title: How to implement Kemeny-Young method? (rank aggregation problem)

text: **Prehistory** I am trying to make some statistical analysis of some experimental data, arises from measurements made on an ordinal scale. I faced with the problem of _rank aggregation_ : to get from many "individuals" orderings (on the same set of objects) one "collective" ordering. The most "natural" approach to this problem is _Kemeny-Young method_ (better look primary source). Surprisingly I found out that there is no program application for this method!!! (There is one C++ code, but it does not allow weak orderings, i.e., does not allow cases when several objects share same position at ordering). Previously I asked some points (one, two) for constructing needed code, but now I have decide to tell all at once — because the problem is more complicated than I thought at first, and I can miss some points since I am null in _Mathematica_ and programming. **Description** Let $R_1, R_2, R_3, ..., R_N$ denote "individuals" weak orderings of $N$ given objects $a, b, c, ...$. Let consider $R$ as set of ordered pairs of objects. Then $(a, b)\in R$ has the usual interpretation: "$a$ is _ordered at least as good as b_ at $R$". In case $(b, a)$ is also in $R$ we say that " _both are ordered equally good_ ". Where in case $(b,a)$ is not in $R$ we say that "$a$ is _ordered above_ $b$" or "$b$ is _ordered below_ $a$". (After introducing metric we will see that it is possible to neglect — since they don't make further difference — such pairs as $(a, a), (b, b), (c, c)...$.) > To demonstrate orderings notation, here are all possible orderings for > $N=3$: > > $\ R_1=\\{(a, b), (a, c), (b, c)\\}$ > > $\ R_2=\\{(a, c), (a, b), (c, b)\\}$ > > $\ R_3=\\{(a, b), (a, c), (b, c), (c, b)\\}$ > > $\ R_4=\\{(b, a), (b, c), (a, c)\\}$ > > $\ R_5=\\{(b, c), (b, a), (c, a)\\}$ > > $\ R_6=\\{(b, a), (b, c), (a, c), (c, a)\\}$ > > $\ R_7=\\{(c, a), (c, b), (a, b)\\}$ > > $\ R_8=\\{(c, b), (c, a), (b, a)\\}$ > > $\ R_9=\\{(c, a), (c, b), (a, b), (b, a)\\}$ > > $R_{10}=\\{(a, b), (b, a), (a, c), (b, c)\\}$ > > $R_{11}=\\{(a, c), (c, a), (a, b), (c, b)\\}$ > > $R_{12}=\\{(b, c), (c, b), (b, a), (c, a)\\}$ > > $R_{13}=\\{(a, b), (b, a), (a, c), (c, a), (b, c), (c, b)\\}$ For such notation we may introduce metric $\delta$ (so-called _Kemeny distance_ ) between any two orderings $R_1$ and $R_2$ by next way: $$\delta(R_1,R_2)=|R_1\setminus R_2|+|R_2\setminus R_1|$$ where $\setminus$ means set-theoretic difference; and $||$ means cardinality of set (i.e., number of elements, because sets are finite). The required "collective" ordering $Ω$ (so-called _Kemeny mean_ ) is such ordering of given objects, that minimizes the sum of the squares of Kemeny distances to all "individuals" orderings, i.e.: $$Ω=\min \sum_{i=1}^{N } \delta(R_i,Ω)^2$$ In fact, $Ω$ may be not unique, there may be several $Ω_1, Ω_2, ...$ for which the appropriate sums of the squares of Kemeny distances are equal and minimal. So in general case $Ω$ is set of such $Ω_i$. **How to attack** So we have several of $R_i$ as input and the goal is to output $Ω$. It looks, like there should be brute-force with one-by-one generating of possible ordering, calculating the sum of the squares of Kemeny distances to all input orderings and verifiaction for minimum. Even for small $N$ number of possible orderings is huge (for my data case $N=10$, there are over $10^8$ possible orderings), so we should keep less data.


title: Generating an Ulam spiral

text: An Ulam Spiral is quite an interesting construction, revealing unexpected features in the distribution of primes. Here is a related topic with one answer by Pinguin Dirk, who has provided one approach. I've created a faster implementation, but I believe it can surely be speeded up:               ClearAll[spiral]     spiral[n_?OddQ] := Nest[        With[{d = Length@#, l = #[[-1, -1]]},          Composition[            Insert[#, l + 3 d + 2 + Range[d + 2], -1] &,            Insert[#\[Transpose], l + 2 d + 1 + Range[d + 1], 1]\[Transpose] &,            Insert[#, l + d + Range[d + 1, 1, -1], 1] &,            Insert[#\[Transpose], l + Range[d, 1, -1], -1]\[Transpose] &            ][#]] &,        {{1}},        (n - 1)/2];          spiral[5] // MatrixForm     spiral[201] // PrimeQ // Boole // ArrayPlot      > ![enter image description here](http://i.stack.imgur.com/9p8h8.png) > > ![enter image description here](http://i.stack.imgur.com/v65AV.png) This is good enough for my purposes, and I don't have time to focus on this now, However, it might be interesting for future visitors, so **the question** is how to make it faster by improving/rewriting. * * * **Note:** There may be confusion concerning whether I need a matrix populated with primes or one populated only with 0 and 1, 1 indicating the prime positions. Let's assume it doesn't matter. Maybe someone has a neat idea for the first representation that does not look good in the second one, so I'm leaving it open.


title: Creating a realtime MIDI Out

text: I have a live stream of notes and note velocities using `SoundNote` and `SoundVolume`. My problem is that I have no idea how to export the MIDI data in real time to an external synthesizer. Would I just use something like this, for example?               Dynamic[Export["file.mid", Sound[SoundNote[0]]] ]      I haven't tried this yet because even if I did have a dynamic MIDI file, how would I get the third party software, like GarageBand or Logic to recognize the MIDI input stream? Another way to phrase this question would be: how do I make _Mathematica_ into a live-playing software synth and not just produce a static MIDI composition?


title: Why is AllTrue much slower than VectorQ?

text: This seems to be a theme with V10, a new function dedicated to a specific task doesn't live up to expectation performance-wise. Mr. Wizard has already uncovered 2 such functions here and here. So how about `AllTrue` versus `VectorQ`? From the docs ![Mathematica graphics](http://i.stack.imgur.com/vQ9tw.png) ![Mathematica graphics](http://i.stack.imgur.com/iOfva.png) We're interested in the second usage of `VectorQ` here, which is the same as the purpose of `AllTrue`. A quick test shows that `VectorQ` annihilates `AllTrue` when it comes to performance e.g.               Needs["GeneralUtilities`"]          AccurateTiming[AllTrue[Range[10^6], IntegerQ]]      > 0.20069455 While for `VectorQ`:               AccurateTiming[VectorQ[Range[10^6], IntegerQ]]      > 0.00214923153 That is a two order of magnitude performance increase over `AllTrue`. Using `BenchMarkPlot` from the useful `GeneralUtilities` package we observe the following:               BenchmarkPlot[      {VectorQ[#, IntegerQ] &, AllTrue[#, IntegerQ] &},      Range[#] &,      PowerRange[10, 10^8],      "IncludeFits" -> True, PlotRange -> Full      ]      ![Mathematica graphics](http://i.stack.imgur.com/PEjLa.png) So, why is `AllTrue` slow compared to `VectorQ`?


title: How to make a function work on symbols in a specific context

text: Let us say we have two sets of symbols $(x, y, z)$ with the same names that live in two different contexts:               {context1`x,context1`y,context1`z} = {1, 10, 100}          {context2`x,context2`y,context2`z} = {2, 20, 200}      How can we define a function which takes as an argument a context name, adds $x$ and $y$ that live in the specified context and assigns the result to $z$ in the same context? **Example:**               f["context1`"]      would result in > >     {context1`x, context1`y, context1`z} = {1 ,10, 11} >   >     {context2`x, context2`y, context2`z} = {2, 20, 200} >


title: ParallelTable and Table do not give same result

text: I have a question regarding the use of `Parallelize`. In the help one can read that “`Parallelize[Table[expr,iter, …]]` (which is equivalent to `ParallelTable[expr,iter,…])` will give the same results as `Table`, except for side effects during the computation.” Ok, here I have an easy code where I use an `If`-conditional inside my Table:               arrayA=Table[RandomReal[{-1,1}],{i,1,1000}];     arrayToBeFilled=ConstantArray[0,1000];     Parallelize[Table[If[arrayA[[i]]<=0,arrayToBeFilled[[i]]=arrayA[[i]]+5,     arrayToBeFilled[[i]]=arrayA[[i]]-5],{i,1,1000}],Method->Automatic];//Timing      I do not get any useful result except my unaltered initialized array, but if I use the same code without `Parallelize`, it works fine (and even faster)! Since my real code (in principal the same as above but with more calculations) takes some time for evaluation, I hoped that I could increase the speed by using `Parallelize`. But it seems that either I am doing/understanding something wrong or that something is wrong with `Parallelize` by itself. Can somebody tell me what the case is? I also would be happy if somebody could tell me a better way how I could increase the speed of such code as in my example.


title: Updating List with Do works but not with ParallelDo

text: I am trying to find 5 minimas for some function. I can obtain the results if I implement a simple Do function. I tried to speed it up by using ParallelDo and then my code returns spurious results. Here is an example: **With Do Loop**               mytable = {{0, 0, 0, 0, 0, 0, 10^7}, {0, 0, 0, 0, 0, 0, 10^6}, {0, 0, 0, 0, 0, 0,          10^10}, {0, 0, 0, 0, 0, 0, 10^8}, {0, 0, 0, 0, 0, 0,10^9}};     ele[a_, b_, c_, d_, e_, f_] := (c/(a + b)) Exp[(d/e)^(-1/f)];          Do[mytable = SortBy[mytable, Last]; If[ele[a, b, c, d, e, f] < Last[Last[mytable]],         mytable[[-1, All]] = {a, b, c, d, e, f, ele[a, b, c, d, e, f]}],          {a,1, 2, 0.5}, {b, 2, 2.5, 0.05}, {c, 0.1, 1.1, 0.5}, {d, 1, 2, 0.5},         {e, 1, 2, 0.5}, {f, 1, 2, 0.5}]          SortBy[mytable, Last]      I get the desired output: > {{2., 2.5, 0.1, 2., 1., 1., 0.0366383}, {2., 2.45, 0.1, 2., 1., > 1.,0.0370499}, {2., 2.4, 0.1, 2., 1., 1., 0.0374709}, {2., 2.35, 0.1,2., 1., > 1., 0.0379016}, {2., 2.3, 0.1, 2., 1., 1., 0.0383424}} But when I simply change Do to **ParallelDo** , it gives me the original mytable values without any change. > {{0, 0, 0, 0, 0, 0, 1000000}, {0, 0, 0, 0, 0, 0, 10000000}, {0, 0, 0, 0, 0, > 0, 100000000}, {0, 0, 0, 0, 0, 0, 1000000000}, {0, 0, 0, 0, 0, 0, > 10000000000}} Can anyone tell me if this is due to independence problem or is there a better way to Parallelize my code?


title: Can I make a function which depends on several arguments which are not independent?

text: Here's a simple example Suppose have the permanent relation that z is proportional to xy^2, for real numbers s.               z = s x y^2      Now, we are interested in functions of x,y,z, say:               f[x_,y_,z_] = Sin[x z]-(1-y z Cos[z])^(-1)      Let's say for reasons of interpretation of the system, we do not want to simply replace z by sxy^2 and make a new function always                g[x_,y_,s_] = Sin[s x^2 y^2] - (1-s x y^3 Cos[s x y^2])^(-1)        This same thing could have been obtained from the first function by just calling:                f[x, y, s x y^2]        Instead, what I would like to be able to do, is retain the full f[x_,y_,z_], unless I have specifically asked for numerical values of x and y. What I would like is to get               f[x, y, z] = Sin[x z]-(1-y z Cos[z])^(-1)        and               f[2,1,(*something*)] =         to do something a little different. If the first two arguments are numerical, I would like the function to treat the third argument as the proportionality constant s, instead of as z itself. I suppose I could accomplish this with some kind of If statement? If those arguments are NumberQ false, take the 3rd argument to be z, and if they are both NumberQ True, take the third argument to be s, as in z=s x y^2? I suppose this question really reduces to can I make a conditional function which differs depending on the argument type?


title: Runge-Kutta 2nd Order ODE Solver

text: Suppose I have a 2nd order ODE of the form `y''(t) = 1/y` with `y(0) = 0` and `y'(0) = 10`, and want to solve it using a Runge-Kutta solver. I've read that we need to convert the 2nd order ODE into two 1st order ODEs, but I'm having trouble doing that at the moment and am hoping someone here might be able to help. This is my code thus far:               Remove["Global`*"]     (*dy/dt=*)f[t_, y_] := 1/y;     (*d^2y/dt^2=*)g[t_, y_, yd_] :=???;     t[0] = 0;     y[0] = 0;     yd[0] = 10;     tmax = 1000;     h = 0.01;          Do[      {t[n] = t[0] + h n,            k1 = h f[t[n], y[n], yd[n]];       l1 = h g[t[n], y[n], yd[n]];            k2 = h f[t[n] + h/2, y[n] +  k1/2, yd[n] + l1/2];       l2 = h g[t[n] + h/2, y[n] +  k1/2, yd[n] + l1/2];            k3 = h f[t[n] + h/2, y[n] + k2/2, yd[n] + l2/2];       l3 = h g[t[n] + h/2, y[n] + k2/2, yd[n] + l2/2];            k4 = h f[t[n] + h, y[n] + k3, yd[n] + l3];       l4 = h g[t[n] + h, y[n] + k3, yd[n] + l3];            y[n + 1] = y[n] + 1/6 (k1 + 2 k2 + 2 k3 + k4);       yd[n + 1] = yd[n] + 1/6 (l1 + 2 l2 + 2 l3 + l4);            }, {n, 0, tmax}]      As you can see by the question marks for the function `g[t_,y_,yd_]`, I don't know how I can set it in such a way that `y''(t) = 1/y`. Do I feed the results of `y[n+1]` into `g` when running the algorithm? Any help would be appreciated.


title: Speeding Up Replacing of Labels in Large Matrix?

text: I am Mathematica novice and am trying to find a fast way to replace labels in some rather large matrices (512x512 or 1024x1024) that have resulted from segmenting images with WatershedComponents or MorphologicalComponents. At present I have written the function below that takes a "label matrix" (matrix that results from segmentation) and a list of "keeper" labels (labels that I want to remain in place in the returned matrix) and returns a new matrix with only those labels remaining in place that are in the listOfKeepersIn. All other labels are replaced in the returned matrix with a single "background" label, here designated as 100. I suspect there are many more efficient ways to achieve this than what I have written here, so I welcome your suggestions. I have tried to convert this to a Compiled Function using Compile but haven't had any success (get an error message about "tensors of different ranks"). I also tried to use ParallelTable instead of Table but didn't notice much improvement. Thanks in advance for any help you can provide. -GR               ComponentKeeperFunction[matrixIn_, listOfKeepersIn_] :=          Block[{matrixToReturn},          matrixToReturn =           Table[           Which[                MemberQ[listOfKeepersIn, matrixIn[[r, c]]] == True,              (* If label value is on the keeper list then just keep that         label in its place, (i.e. make the value in the table the same as             matrixIn[[r,c]])*)              matrixIn[[r, c]],                    MemberQ[listOfKeepersIn, matrixIn[[r, c]]] == False,              (* If label value is not on the keeper list then replace that label with a                    designated background label  *)                      100  (*here I designate the background label as having a value of 100 *)           ] (* close Which *),               {r, 1, Dimensions[matrixIn][[1]]}, {c, 1, Dimensions[matrixIn][[2]]}           ] (*close Table *);            Return[matrixToReturn]           ](*close Block*)


title: Simulated Annealing Parameters and Results

text: I am using `SimulatedAnnealing` method for a simulation based optimization problem and was wondering if someone can enlighten me on the following features:   1. Is there some guidelines on optimal size of `"SearchPoints"` based on the size of the solution space knowing that the objective function is non-linear?   2. It is intuitive that the number of iterations will depend on the objective function, but I have noticed that the number of iterations seem to be a multiple of number of variables. is this true? Sample code is provided in Simulated Annealing Convergence   3. I think it is difficult to prove global optimization results, but was wondering if any one has ideas on alternative ways to do that.


title: How can I calculate the correlation dimension and/or the Lyapunov exponent of a time series using Mathematica

text: I have a pretty long time series (4000 data points). How can I calculate the Correlation dimension and/or Lyapunov exponent for such data? Please also advise on how to import the data as well.


title: How to run all command with same name into a notebook

text: I have a very big notebook with a command repeated a lot of times but with different parameters each time and I want to run all these commands at the same time without having to run separately all of them. Is there a way? **EDIT: more info** Between different calls of the 'command' there are other things (mainly plots) and I want to preserve the order of the notebook. Using the `Evaluate Notebook` form the menu `Evaluation` can be an option but when I am in a hurry this is bad because it evaluates also all the things in between while I am mainly interested in the output of my commands.


title: Use of Ito's lemma in ItoProcess

text: In the documentation for the `ItoProcess` it says: > Converting an `ItoProcess` to standard form automatically makes use of Ito's > lemma. It is unclear to me how this is done, also the example given for the standard form doesn't help. How can I, for example, apply Ito's lemma on the following stochastic differential equation (SDE) $dS=S(σdB+μdt)$, with $B$ being Brownian motion. Applying Itō's lemma with $f(S)=log(S)$ gives $$\begin{align} d\log(S) & = f^\prime(S)\,dS + \frac{1}{2}f^{\prime\prime} (S)S^2\sigma^2 \,dt \\\ & = \frac{1}{S} \left( \sigma S\,dB + \mu S\,dt\right) - \frac{1}{2}\sigma^2\,dt \\\ &= \sigma\,dB +\left (\mu-\tfrac{\sigma^2}{2} \right )\,dt. \end{align}$$ It follows that $$\log (S_t) = \log (S_0) + \sigma B_t + \left (\mu-\tfrac{\sigma^2}{2} \right )t,$$ exponentiating gives the expression for $S$, $$S_t=S_0\exp\left(\sigma B_t+ \left (\mu-\tfrac{\sigma^2}{2} \right )t\right).$$ How can I achieve that in Mathematica?


title: Expanding a Function in Series works, SeriesCoefficient Doesn't Work

text: Take the following definitions:               rho = Cos[(2 Pi)/7] + I Sin[(2 Pi)/7]          F[y, q] =       y^3*Product[(1 -            Conjugate[lambda] y^-2) Product[(1 -              Conjugate[lambda] y^-2*q^n) (1 - lambda*y^2*q^n), {n, 1,            Infinity}], {lambda, {rho, rho^2, rho^4}}]          G[y, q] =       y^2*Product[(1 -            Conjugate[mu] y^-1) Product[(1 - Conjugate[mu] y^-1*q^n) (1 -              mu*y*q^n), {n, 1, Infinity}], {mu, {1, rho^3, rho^5, rho^6}}]          Psi[y, q] = (F[y, q]/G[y, q]) * Product[(1 - q^n)^2, {n, 1, Infinity}]      For some reason, I can compute `Series[Psi[y, q], {y, 0, 3}]` quite quickly, but the command `SeriesCoefficient[Psi[y, q], {y, 0, i}]` will not finish for $i=1,2,3$. Why could this be? I've noticed the output of `Series[]` isn't exactly a power series in y, but rather has some powers of y buried into the functions `QPochHammer[]` but I don't know how to get them out. Any help is greatly appreciated. Thanks, Andy.


title: How to measure segment length and branch angle

text: I am trying to measure segment length and branch angle or bifurcation angle between each pair of segments. My image after thinning looks like this: ![enter image description here](http://i.stack.imgur.com/me0gY.jpg)                i = Import@"http://dl.dropbox.com/u/68983831/thinned.png";      dat = ImageData[i];       i1 = Image[dat[[34 ;; 242, 28 ;; 213]]]      g = MorphologicalGraph[i1, EdgeWeight -> Automatic]      thus output looks like: ![enter image description here](http://i.stack.imgur.com/tqIPZ.jpg)