Mesh at Ticks positions

In a `ListPlot3D[ ]` I want to have the `Mesh` at the same positions as the ticks. For some reason this isn't default if both are chosen `Automatic`. So my question is if there is some function to read (or reproduce) the automatically generated `Ticks` as a list e.g. `xTicksList` and `yTicksList` and than use this like               Mesh-> {xTicksList,yTicksList}      Alternative solutions are of course also welcome. But no solutions with explicite values, this isn't what I want, because finally I want to use this in a more general recipe. Edit: Easy call:               SetDirectory["./"]     data = Import["file.dat"];     ListPlot3D[data, ViewPoint -> {0, -2, 4}]      Data to work on:                    -1.300000000000       0.210526315789       0.980235619886          -1.163157894737       0.210526315789       0.979505821537          -1.026315789474       0.210526315789       1.097953636927          -0.889473684211       0.210526315789       1.102989687180          -0.752631578947       0.210526315789       1.098700823572          -0.615789473684       0.210526315789       1.125990693356          -0.478947368421       0.210526315789       1.211353461701          -0.342105263158       0.210526315789       1.815613507388          -0.205263157895       0.210526315789       1.045807948880          -0.068421052632       0.210526315789       0.000001971641           0.068421052632       0.210526315789       0.000001971641           0.205263157895       0.210526315789       1.045807948880           0.342105263158       0.210526315789       1.815613507388           0.478947368421       0.210526315789       1.211353461701           0.615789473684       0.210526315789       1.125990693356           0.752631578947       0.210526315789       1.098700823572           0.889473684211       0.210526315789       1.102989687180           1.026315789474       0.210526315789       1.097953636927           1.163157894737       0.210526315789       0.979505821537           1.300000000000       0.210526315789       0.980235619886          -1.300000000000       0.421052631579       0.980942994071          -1.163157894737       0.421052631579       0.981933173223          -1.026315789474       0.421052631579       1.103154056150          -0.889473684211       0.421052631579       1.107281088495          -0.752631578947       0.421052631579       1.106941920492          -0.615789473684       0.421052631579       1.146919259544          -0.478947368421       0.421052631579       1.309678535944          -0.342105263158       0.421052631579       0.584224780318          -0.205263157895       0.421052631579       0.700847812228          -0.068421052632       0.421052631579       0.000006770074           0.068421052632       0.421052631579       0.000006770074           0.205263157895       0.421052631579       0.700847812228           0.342105263158       0.421052631579       0.584224780318           0.478947368421       0.421052631579       1.309678535944           0.615789473684       0.421052631579       1.146919259544           0.752631578947       0.421052631579       1.106941920492           0.889473684211       0.421052631579       1.107281088495           1.026315789474       0.421052631579       1.103154056150           1.163157894737       0.421052631579       0.981933173223           1.300000000000       0.421052631579       0.980942994071          -1.300000000000       0.631578947368       0.982279600261          -1.163157894737       0.631578947368       0.986279051512          -1.026315789474       0.631578947368       1.111702792051          -0.889473684211       0.631578947368       1.114982129224          -0.752631578947       0.631578947368       1.122873224846          -0.615789473684       0.631578947368       1.194737734850          -0.478947368421       0.631578947368       1.930464394003          -0.342105263158       0.631578947368       0.560661235292          -0.205263157895       0.631578947368       0.615345975499          -0.068421052632       0.631578947368       0.964754106066           0.068421052632       0.631578947368       0.964754106066           0.205263157895       0.631578947368       0.615345975499           0.342105263158       0.631578947368       0.560661235292           0.478947368421       0.631578947368       1.930464394003           0.615789473684       0.631578947368       1.194737734850           0.752631578947       0.631578947368       1.122873224846           0.889473684211       0.631578947368       1.114982129224           1.026315789474       0.631578947368       1.111702792051           1.163157894737       0.631578947368       0.986279051512           1.300000000000       0.631578947368       0.982279600261          -1.300000000000       0.842105263158       0.984506863561          -1.163157894737       0.842105263158       0.993017144639          -1.026315789474       0.842105263158       1.123329136135          -0.889473684211       0.842105263158       1.127086080172          -0.752631578947       0.842105263158       1.151323601756          -0.615789473684       0.842105263158       1.316936571158          -0.478947368421       0.842105263158       0.533092973179          -0.342105263158       0.842105263158       0.546076002707          -0.205263157895       0.842105263158       0.576957097781          -0.068421052632       0.842105263158       0.684846595150           0.068421052632       0.842105263158       0.684846595150           0.205263157895       0.842105263158       0.576957097781           0.342105263158       0.842105263158       0.546076002707           0.478947368421       0.842105263158       0.533092973179           0.615789473684       0.842105263158       1.316936571158           0.752631578947       0.842105263158       1.151323601756           0.889473684211       0.842105263158       1.127086080172           1.026315789474       0.842105263158       1.123329136135           1.163157894737       0.842105263158       0.993017144639           1.300000000000       0.842105263158       0.984506863561          -1.300000000000       1.052631578947       0.988041894481          -1.163157894737       1.052631578947       1.002844293634          -1.026315789474       1.052631578947       1.137460222080          -0.889473684211       1.052631578947       1.145431494008          -0.752631578947       1.052631578947       1.204639094902          -0.615789473684       1.052631578947       2.034283267433          -0.478947368421       1.052631578947       0.527426104920          -0.342105263158       1.052631578947       0.536322515501          -0.205263157895       1.052631578947       0.555643903601          -0.068421052632       1.052631578947       1.542776620591           0.068421052632       1.052631578947       1.542776620591           0.205263157895       1.052631578947       0.555643903601           0.342105263158       1.052631578947       0.536322515501           0.478947368421       1.052631578947       0.527426104920           0.615789473684       1.052631578947       2.034283267433           0.752631578947       1.052631578947       1.204639094902           0.889473684211       1.052631578947       1.145431494008           1.026315789474       1.052631578947       1.137460222080           1.163157894737       1.052631578947       1.002844293634           1.300000000000       1.052631578947       0.988041894481          -1.300000000000       1.263157894737       0.993507698008          -1.163157894737       1.263157894737       1.016663871059          -1.026315789474       1.263157894737       1.153029591526          -0.889473684211       1.263157894737       1.173527252601          -0.752631578947       1.263157894737       1.324259264609          -0.615789473684       1.263157894737       0.520310839569          -0.478947368421       1.263157894737       0.523127565540          -0.342105263158       1.263157894737       0.529437718570          -0.205263157895       1.263157894737       0.542365083073          -0.068421052632       1.263157894737       1.251779214963           0.068421052632       1.263157894737       1.251779214963           0.205263157895       1.263157894737       0.542365083073           0.342105263158       1.263157894737       0.529437718570           0.478947368421       1.263157894737       0.523127565540           0.615789473684       1.263157894737       0.520310839569           0.752631578947       1.263157894737       1.324259264609           0.889473684211       1.263157894737       1.173527252601           1.026315789474       1.263157894737       1.153029591526           1.163157894737       1.263157894737       1.016663871059           1.300000000000       1.263157894737       0.993507698008          -1.300000000000       1.473684210526       1.001780955507          -1.163157894737       1.473684210526       1.035419641030          -1.026315789474       1.473684210526       1.168300600319          -0.889473684211       1.473684210526       1.218742366781          -0.752631578947       1.473684210526       1.820497914358          -0.615789473684       1.473684210526       0.517801652652          -0.478947368421       1.473684210526       0.519782526335          -0.342105263158       1.473684210526       0.524378305806          -0.205263157895       1.473684210526       1.497512379500          -0.068421052632       1.473684210526       1.158442502764           0.068421052632       1.473684210526       1.158442502764           0.205263157895       1.473684210526       1.497512379500           0.342105263158       1.473684210526       0.524378305806           0.478947368421       1.473684210526       0.519782526335           0.615789473684       1.473684210526       0.517801652652           0.752631578947       1.473684210526       1.820497914358           0.889473684211       1.473684210526       1.218742366781           1.026315789474       1.473684210526       1.168300600319           1.163157894737       1.473684210526       1.035419641030           1.300000000000       1.473684210526       1.001780955507          -1.300000000000       1.684210526316       1.013974303940          -1.163157894737       1.684210526316       1.059492763356          -1.026315789474       1.684210526316       1.180869891090          -0.889473684211       1.684210526316       1.299514133592          -0.752631578947       1.684210526316       0.516453133533          -0.615789473684       1.684210526316       0.515737848476          -0.478947368421       1.684210526316       0.517124685004          -0.342105263158       1.684210526316       0.520545139810          -0.205263157895       1.684210526316       1.214149849511          -0.068421052632       1.684210526316       1.111669990419           0.068421052632       1.684210526316       1.111669990419           0.205263157895       1.684210526316       1.214149849511           0.342105263158       1.684210526316       0.520545139810           0.478947368421       1.684210526316       0.517124685004           0.615789473684       1.684210526316       0.515737848476           0.752631578947       1.684210526316       0.516453133533           0.889473684211       1.684210526316       1.299514133592           1.026315789474       1.684210526316       1.180869891090           1.163157894737       1.684210526316       1.059492763356           1.300000000000       1.684210526316       1.013974303940          -1.300000000000       1.894736842105       1.031151313623          -1.163157894737       1.894736842105       1.087145840815          -1.026315789474       1.894736842105       1.188079272660          -0.889473684211       1.894736842105       1.480552497483          -0.752631578947       1.894736842105       0.514891129597          -0.615789473684       1.894736842105       0.514017825943          -0.478947368421       1.894736842105       0.514975893386          -0.342105263158       1.894736842105       1.653213278836          -0.205263157895       1.894736842105       1.132316352893          -0.068421052632       1.894736842105       1.083852929370           0.068421052632       1.894736842105       1.083852929370           0.205263157895       1.894736842105       1.132316352893           0.342105263158       1.894736842105       1.653213278836           0.478947368421       1.894736842105       0.514975893386           0.615789473684       1.894736842105       0.514017825943           0.752631578947       1.894736842105       0.514891129597           0.889473684211       1.894736842105       1.480552497483           1.026315789474       1.894736842105       1.188079272660           1.163157894737       1.894736842105       1.087145840815           1.300000000000       1.894736842105       1.031151313623          -1.300000000000       2.105263157895       1.053263797252          -1.163157894737       2.105263157895       1.112054099666          -1.026315789474       2.105263157895       1.187887756512          -0.889473684211       2.105263157895       2.414939312234          -0.752631578947       2.105263157895       0.513547775105          -0.615789473684       2.105263157895       0.512568414028          -0.478947368421       2.105263157895       0.513214034428          -0.342105263158       2.105263157895       1.234630789787          -0.205263157895       2.105263157895       1.093026423469          -0.068421052632       2.105263157895       1.065649778360           0.068421052632       2.105263157895       1.065649778360           0.205263157895       2.105263157895       1.093026423469           0.342105263158       2.105263157895       1.234630789787           0.478947368421       2.105263157895       0.513214034428           0.615789473684       2.105263157895       0.512568414028           0.752631578947       2.105263157895       0.513547775105           0.889473684211       2.105263157895       2.414939312234           1.026315789474       2.105263157895       1.187887756512           1.163157894737       2.105263157895       1.112054099666           1.300000000000       2.105263157895       1.053263797252          -1.300000000000       2.315789473684       1.076657703675          -1.163157894737       2.315789473684       1.123492475408          -1.026315789474       2.315789473684       1.179776702031          -0.889473684211       2.315789473684       0.517636004512          -0.752631578947       2.315789473684       0.512380796022          -0.615789473684       2.315789473684       0.511335258693          -0.478947368421       2.315789473684       0.519172187319          -0.342105263158       2.315789473684       1.138037117826          -0.205263157895       2.315789473684       1.070113678169          -0.068421052632       2.315789473684       1.052968436145           0.068421052632       2.315789473684       1.052968436145           0.205263157895       2.315789473684       1.070113678169           0.342105263158       2.315789473684       1.138037117826           0.478947368421       2.315789473684       0.519172187319           0.615789473684       2.315789473684       0.511335258693           0.752631578947       2.315789473684       0.512380796022           0.889473684211       2.315789473684       0.517636004512           1.026315789474       2.315789473684       1.179776702031           1.163157894737       2.315789473684       1.123492475408           1.300000000000       2.315789473684       1.076657703675          -1.300000000000       2.526315789474       1.091865153557          -1.163157894737       2.526315789474       1.114876898745          -1.026315789474       2.526315789474       1.164983245160          -0.889473684211       2.526315789474       0.516400089510          -0.752631578947       2.526315789474       0.511360095534          -0.615789473684       2.526315789474       0.510277474936          -0.478947368421       2.526315789474       1.335414688817          -0.342105263158       2.526315789474       1.094672456667          -0.205263157895       2.526315789474       1.055241265973          -0.068421052632       2.526315789474       1.043728713057           0.068421052632       2.526315789474       1.043728713057           0.205263157895       2.526315789474       1.055241265973           0.342105263158       2.526315789474       1.094672456667           0.478947368421       2.526315789474       1.335414688817           0.615789473684       2.526315789474       0.510277474936           0.752631578947       2.526315789474       0.511360095534           0.889473684211       2.526315789474       0.516400089510           1.026315789474       2.526315789474       1.164983245160           1.163157894737       2.526315789474       1.114876898745           1.300000000000       2.526315789474       1.091865153557          -1.300000000000       2.736842105263       1.089274605713          -1.163157894737       2.736842105263       1.091729061725          -1.026315789474       2.736842105263       1.145851846320          -0.889473684211       2.736842105263       0.515298422848          -0.752631578947       2.736842105263       0.510461989727          -0.615789473684       2.736842105263       0.509366151457          -0.478947368421       2.736842105263       1.174696797334          -0.342105263158       2.736842105263       1.070314416559          -0.205263157895       2.736842105263       1.044899739158          -0.068421052632       2.736842105263       1.036763511509           0.068421052632       2.736842105263       1.036763511509           0.205263157895       2.736842105263       1.044899739158           0.342105263158       2.736842105263       1.070314416559           0.478947368421       2.736842105263       1.174696797334           0.615789473684       2.736842105263       0.509366151457           0.752631578947       2.736842105263       0.510461989727           0.889473684211       2.736842105263       0.515298422848           1.026315789474       2.736842105263       1.145851846320           1.163157894737       2.736842105263       1.091729061725           1.300000000000       2.736842105263       1.089274605713          -1.300000000000       2.947368421053       1.070982617491          -1.163157894737       2.947368421053       1.064870984592          -1.026315789474       2.947368421053       1.124857239675          -0.889473684211       2.947368421053       0.514306616086          -0.752631578947       2.947368421053       0.509667542587          -0.615789473684       2.947368421053       2.571106436571          -0.478947368421       2.947368421053       1.113772367051          -0.342105263158       2.947368421053       1.054892518975          -0.205263157895       2.947368421053       1.037352203431          -0.068421052632       2.947368421053       1.031369828620           0.068421052632       2.947368421053       1.031369828620           0.205263157895       2.947368421053       1.037352203431           0.342105263158       2.947368421053       1.054892518975           0.478947368421       2.947368421053       1.113772367051           0.615789473684       2.947368421053       2.571106436571           0.752631578947       2.947368421053       0.509667542587           0.889473684211       2.947368421053       0.514306616086           1.026315789474       2.947368421053       1.124857239675           1.163157894737       2.947368421053       1.064870984592           1.300000000000       2.947368421053       1.070982617491          -1.300000000000       3.157894736842       1.047866508842          -1.163157894737       3.157894736842       1.041164829929          -1.026315789474       3.157894736842       1.103940126372          -0.889473684211       3.157894736842       0.513409767406          -0.752631578947       3.157894736842       0.508961575187          -0.615789473684       3.157894736842       1.326407622207          -0.478947368421       3.157894736842       1.082011967173          -0.342105263158       3.157894736842       1.044357195862          -0.205263157895       3.157894736842       1.031641411387          -0.068421052632       3.157894736842       1.027100715053           0.068421052632       3.157894736842       1.027100715053           0.205263157895       3.157894736842       1.031641411387           0.342105263158       3.157894736842       1.044357195862           0.478947368421       3.157894736842       1.082011967173           0.615789473684       3.157894736842       1.326407622207           0.752631578947       3.157894736842       0.508961575187           0.889473684211       3.157894736842       0.513409767406           1.026315789474       3.157894736842       1.103940126372           1.163157894737       3.157894736842       1.041164829929           1.300000000000       3.157894736842       1.047866508842          -1.300000000000       3.368421052632       1.027707541691          -1.163157894737       3.368421052632       1.022670717601          -1.026315789474       3.368421052632       1.084322269326          -0.889473684211       3.368421052632       0.512595867665          -0.752631578947       3.368421052632       0.508332439171          -0.615789473684       3.368421052632       1.179765630236          -0.478947368421       3.368421052632       1.062774142729          -0.342105263158       3.368421052632       1.036767743753          -0.205263157895       3.368421052632       1.027197425050          -0.068421052632       3.368421052632       1.023659622763           0.068421052632       3.368421052632       1.023659622763           0.205263157895       3.368421052632       1.027197425050           0.342105263158       3.368421052632       1.036767743753           0.478947368421       3.368421052632       1.062774142729           0.615789473684       3.368421052632       1.179765630236           0.752631578947       3.368421052632       0.508332439171           0.889473684211       3.368421052632       0.512595867665           1.026315789474       3.368421052632       1.084322269326           1.163157894737       3.368421052632       1.022670717601           1.300000000000       3.368421052632       1.027707541691          -1.300000000000       3.578947368421       1.012740556267          -1.163157894737       3.578947368421       1.009098441749          -1.026315789474       3.578947368421       1.066618101119          -0.889473684211       3.578947368421       0.511854868108          -0.752631578947       3.578947368421       0.507778141612          -0.615789473684       3.578947368421       1.119870247076          -0.478947368421       3.578947368421       1.050022506614          -0.342105263158       3.578947368421       1.031080838687          -0.205263157895       3.578947368421       1.023660489456          -0.068421052632       3.578947368421       1.020842841204           0.068421052632       3.578947368421       1.020842841204           0.205263157895       3.578947368421       1.023660489456           0.342105263158       3.578947368421       1.031080838687           0.478947368421       3.578947368421       1.050022506614           0.615789473684       3.578947368421       1.119870247076           0.752631578947       3.578947368421       0.507778141612           0.889473684211       3.578947368421       0.511854868108           1.026315789474       3.578947368421       1.066618101119           1.163157894737       3.578947368421       1.009098441749           1.300000000000       3.578947368421       1.012740556267          -1.300000000000       3.789473684211       1.002490308916          -1.163157894737       3.789473684211       0.999480129131          -1.026315789474       3.789473684211       1.051031597371          -0.889473684211       3.789473684211       0.511178259186          -0.752631578947       3.789473684211       2.115303346236          -0.615789473684       3.789473684211       1.087590009962          -0.478947368421       3.789473684211       1.041038314858          -0.342105263158       3.789473684211       1.026687653195          -0.205263157895       3.789473684211       1.020792862745          -0.068421052632       3.789473684211       1.018506330614           0.068421052632       3.789473684211       1.018506330614           0.205263157895       3.789473684211       1.020792862745           0.342105263158       3.789473684211       1.026687653195           0.478947368421       3.789473684211       1.041038314858           0.615789473684       3.789473684211       1.087590009962           0.752631578947       3.789473684211       2.115303346236           0.889473684211       3.789473684211       0.511178259186           1.026315789474       3.789473684211       1.051031597371           1.163157894737       3.789473684211       0.999480129131           1.300000000000       3.789473684211       1.002490308916          -1.300000000000       4.000000000000       0.995814193962          -1.163157894737       4.000000000000       0.992838080577          -1.026315789474       4.000000000000       1.037528228234          -0.889473684211       4.000000000000       0.510558796548          -0.752631578947       4.000000000000       1.344611311368          -0.615789473684       4.000000000000       1.067648040164          -0.478947368421       4.000000000000       1.034420877924          -0.342105263158       4.000000000000       1.023210238365          -0.205263157895       4.000000000000       1.018431506605          -0.068421052632       4.000000000000       1.016545718957           0.068421052632       4.000000000000       1.016545718957           0.205263157895       4.000000000000       1.018431506605           0.342105263158       4.000000000000       1.023210238365           0.478947368421       4.000000000000       1.034420877924           0.615789473684       4.000000000000       1.067648040164           0.752631578947       4.000000000000       1.344611311368           0.889473684211       4.000000000000       0.510558796548           1.026315789474       4.000000000000       1.037528228234           1.163157894737       4.000000000000       0.992838080577           1.300000000000       4.000000000000       0.995814193962


How can I export aligned equations to $\LaTeX$?

Using Palettes -> Writing Assistant -> Math Cells, you can enter aligned equations such as:               Cell[TextData[Cell[BoxData[      FormBox[GridBox[{         {GridBox[{            {             RowBox[{              RowBox[{"f", "(", "x", ")"}], "=",               RowBox[{"expr", " ", "1"}]}]},            {             RowBox[{"=",               RowBox[{"expr", " ", "2"}]}]},            {             RowBox[{"=",               RowBox[{"expr", " ", "3"}]}]}           },           GridBoxAlignment->{"Columns" -> {{"="}}}]}        },        GridBoxItemSize->{"Columns" -> {{             Scaled[0.96]}}}], TraditionalForm]]]], "Text"]      But saving as $\LaTeX$ yields equations that are unaligned and uncentered! ![sample](http://i.stack.imgur.com/KLqH6.png) I'm looking for a `SaveAsLatex` function that would correctly export _human readable_ code for the following things:   1. (marker) Aligned Equations   2. Hyperlinks (refs, labels, etc...)   3. ItemNumbered cells   4. Centered math cells   5. Numbered and captioned tables/figures Here is a sample notebook to test your code.


How to get 2D graphics into 3D without background?

Consider the following code:               g=Graphics[{EdgeForm[{Black, Thick}],                 {Green,Opacity[0.5],Rectangle[{0,0.5},{1,1}]},                 Red, Polygon[{{0, 0}, {1, 0}, {1/2, Sqrt[3]/2}}],                 White, Disk[{1/2, 1/(2Sqrt[3])}, 1/(2Sqrt[3])]},                Background->None];     Graphics3D[{{Texture[g],                  Polygon[{{0,0,0},{0,1,0},{1,1,0},{1,0,0}},                          VertexTextureCoordinates->{{0,0},{1,0},{1,1},{0,1}}]},                 {Texture[g],                  Polygon[{{0,0,1},{0,1,1},{1,1,1},{1,0,1}},                          VertexTextureCoordinates->{{0,0},{1,0},{1,1},{0,1}}]}},                Lighting->{{"Ambient", White}},                ViewPoint->{1,4,7}]      This gives the following graphics: ![Mathematica graphics](http://i.stack.imgur.com/EObbv.png) As you can easily see, the part outside of the figures is opaque white, despite of the `Background->None` option. Also `Background->RGBColor[1,1,1,0]` didn't help, nor did passing the Graphics through `Rasterize` with the option `Background->None` Here's roughly what I'd want to get (any inaccuracies are caused by my lacking GIMP-fu :-)): ![What I would want it to look like](http://i.stack.imgur.com/s8HwY.png) Looking for a solution I found this code but couldn't get it work for my case. Also, if I understand it correctly, it doesn't derive the transparency from the graphics but just replaces a certain colour with fully transparent, which wouldn't work with the semi-transparent green rectangle. Combining the 2D graphics with another one using `Show` does respect `Background->None` and `Opacity` on the green rectangle, so it's not a problem with the graphics itself. Therefore my question: Is it possible to embed 2D graphics into 3D while keeping the transparency of the 2D image, and if so, how?


Overlapping Red and Green ArrayPlots to show yellow intersections

Let's say I have two `ArrayPlot[]`s. One is in redscale and the other is in greenscale, such that the lowest value is white and the highest value is pure red or green. How do I overlap the two `ArrayPlot[]`s such that intersections are a combination of red and green to give a yellow intensity dependent on the "red" and "green" values? **Edit** I understand that maybe the question is not so clear. I got my idea from a common technique in biology where red fluorescent and green fluorescent signals are captured separately, then merged together.   Areas of red and green together become yellow, but regions of red only or green only are just those colors in the merged image. I am aiming to translate this to data arranged in arrays such that the final merged image will show areas of red and green "signals" as yellow and red/green alone is still red/green alone. Example:   ![enter image description here](http://i.stack.imgur.com/DqbaY.png)


Nonlinear recurrence relation

I entered the following recurrence relation into RSolve and it just gave the question back to me. $$a_{n+1} = \frac{(1+a_n +(a_{n−1})^3)} 3$$ Is there another way to get a formula for the nth term?


Display Matrix of values with position

I want to find the table of values of $x^2 + y^2$ in steps of 1, from $0$ to $5$ for $x$ and $y$, together with the position $(x,y)$: something like this:![enter image description here](http://i.stack.imgur.com/N0zcF.png) I can only display the $x^2 + y^2$ value but not the position..               Table[x^2 + y^2, {x, 0, 4, 1}, {y, 0, 4, 1}] // MatrixForm


Decimal output from a simple equation

Let               x= 0.0000000000000000036;          y = 1 - x      If i type this in Mathematica the answer of `y` is 1. I want the answer to be as it is 0.9999999999999999964


Getting Arg[z] to go from $0$ to $2\pi$

I'm defining branch cut functions, and I'm using $arg(z)$ as a building block. So I just spent an hour at the whiteboard assuming that $arg(z)$ goes from $0$ to $2\pi$, and then I implement the code, and everything goes horribly wrong. I just realized that the problem is that the the `Arg` function built into _Mathematica_ goes from $-\pi$ to $\pi$. Is there anyway I can redefine `Arg` so that my code will work?


Variant of the cutting-stock problem in Mathematica

I'm pretty new to _Mathematica_ and am trying to learn to solve problems in a functional way. The problem I was solving was to list the ways in which I could sum elements from a list (with repetitions), so the sum is less-than-or- equal to some value. The code below solves my problem just fine.               i = {7.25, 7.75, 15, 19, 22};     m = 22;     getSum[l_List, n_List] := Total[Thread[{l, n}] /. {x_, y_} -> x y];     t = Prepend[Map[Range[0, Floor[m/#]] &, i], List];     Outer @@ %;     Flatten[%, ArrayDepth[%] - 2];     Map[{#, getSum[i, #]} &, %];     DeleteCases[%, {_, x_} /; x > m || x == 0];     TableForm[Flatten /@ SortBy[%, Last], 0, TableHeadings -> {None, Append[i, "Total"]}]      However, the code checks a lot of unneccesary cases, which could be a problem if `m` is bigger or the list is longer. My question is simply: what would be the most _Mathematica_ -esque way to solve this problem with regard to both efficiency and code elegance.


Intersecting/Overlapping Image Elements Counts?

I have what I believe should be a relatively easy problem to solve that I have not been able to find an elegant solution for. I need to compare two binary 2D images and count if any of the elements from either image intersect/overlap with the other.   1. I would like to count how many blobs intersect with quadrilaterals. A blob may intersect with multiple quadrilaterals and each intersection would count, but multiple intersections within the same quadrilateral by the same blob, only count once.   2. I would like to count the number of quadrilaterals not intersecting with any blobs.   3. I would like to count the number of blobs not intersecting with any quadrilaterals. These are the images ![Quadrilaterals](http://i.stack.imgur.com/kR71u.png) ![Blobs](http://i.stack.imgur.com/ppyhb.png) I created bounding boxes based on blob images with the following:                   CreatePolygon[image_] :=          Module[{BinarizedImage, BoundaryBoxesCoords, Polygons, size},     size = ImageDimensions[image];     BinarizedImage = Binarize[image];     BoundaryBoxesCoords =      Last /@ ComponentMeasurements[     MorphologicalComponents[BinarizedImage], "MinimalBoundingBox"];     Polygons =      Graphics[{Red, Polygon /@ BoundaryBoxesCoords}, ImageSize -> size,      PlotRange -> {{0, First@size}, {0, Last@size}}]]      I tried doing a count of image items by overlapping the elements and counting objects consisting of amalgamated colors, but this doesn't help with conditions where blobs intersect the same quadrilateral multiple times. Using the inverse is also not helpful in solving the other two problems as I had hoped.               CreateHits[QuadImage_, BlobImage_] :=      Module[{CompositeImage, GrayThreshold, Hits},     CompositeImage =      ColorConvert[     ImageCompose[Binarize[BlobImage], {QuadImage, .5}],      "Grayscale"];     GrayThreshold = {.6, .8};     Hits =      First@Last@     ComponentMeasurements[       MorphologicalComponents[        Binarize[CompositeImage, GrayThreshold]], "Count"]]          CreateHits[Image1, Image2]      I don't think the ideal solution lies with the approach I've tried, however, which is a visual solution. What I'd like is to extract the coordinates for each blob and each quadrilateral area and just compare these object lists to determine overlaps. E.g., Blob 3 shares coordinates with Quadrilaterals 2 & 4\. I can't figure out, however, how to use the output of MorphologicalComponents to find this information to retrieve the coordinates for each object or to store each cluster as a separate item. This is bothersome because MorphologicalComponents has clearly identified those things. I could brute force the code and create separate images for each blob and/or quadrilateral and do the comparison computation that way, but besides being much more computationally expensive it is, as I said, not particularly elegant.


Workbench fails to run on OSX. Reports "Front end could not be launched."

I've just installed Workbench 2.0 and I am trying to use it with Mathematica 10. Following the examples in the help I created the sample Test project. When I hit run it does the following.   * Spawns a new Mathematica app.    * Opens a blank notebook.    * Workbench sits on 19% for about a minute.  After that I get the following error message. ![The Mathematica Notebook front end could not be launched.](http://i.stack.imgur.com/CGbK5.png) I have reinstalled Mathematica + Workbench from scratch but still the same. Also the blank notebook spawned is not in the `Directory[]` for the code. So that's a bit pointless. * * * As a workaround I have Mathematica launched and I've manually SetDirectory[] to my project, but it just seems a bit annoying I can't just work out of the workbench.


Matrix Determinant

I have an N by N (N>3) matrix generated from fortran. I would like to find determinant of that matrix using mathematica? I could do this for a 3 by 3 matrix. I can also import the fortran output file to mathematica but how to write down the data in the prescribed format : Det[{{a1, a2, a3}, {a4, a5, a6}, {a7, a8, a9}}] for large N? Writing the data one by one is a tedious job.Kindly help. fortran output of a 5 by 5 matrix:               row1(0.600336   -0.169615    0.054516   -0.003712   -0.038923)     row2(0.637602    0.363638   -0.069266    0.006823    0.035388)     row3(-0.032774    0.876752    0.226435   -0.020353   -0.017496)     row4(-0.024340   -0.144815    0.950590    0.182733   -0.007234)     row5(0.024211    0.030092   -0.161703    0.966905    0.173151)


Creating a 2D meshing algorithm in Mathematica

As what is proving to be a difficult, but entertaining task, I am attempting to adapt a 2D meshing algorithm created for MATLAB and port it to Mathematica. I understand meshing functions already exist in Mathematica so this is purely for fun/learning. The paper here describes in great detail the algorithm created for MATLAB, in terms of the non code specific logic and each step of the code. I intend to modify this question as/if suggestions are made to show its progress. To start off simple, I have a box that I'm creating a random selection of meshing points within. I modify these using Delaunay's Triangulation Algorithm and then create an initial triangular mesh. Next, imagining all these points are joined my 'magic springs', if the length, L, of a spring is less than a certain chosen scale length, L0, then it exerts a force on each joining point in the direction of increasing separation, proportional to L-L0. Thus you create a new set of points at a later artificial timestep due to the effect of these psuedoforces. Then if any points are outside of the original box, you drag 'em back in and repeat this process until some sort of equilibrium condition is met. This is the code I've done so far:               SeedRandom[2];     bboxL = 10;     bboxH = 10;     Nnodes = 100;     p0 = Table[0, {i, Nnodes}, {i, 2}];     Do[       p0[[i, 1]] = RandomReal[{0, bboxL}];       p0[[i, 2]] = RandomReal[{0, bboxH}];       , {i, Nnodes}];          timeStep = 0.2;          Needs["ComputationalGeometry`"];     dt = DelaunayTriangulation[p0];     toPairs[{m_, ns_List}] := Map[{m, #} &, ns];     edges = Flatten[Map[toPairs, dt], 1];     Graphics[GraphicsComplex[       p0, {Line[edges], Red, PointSize[Medium], Point[p0]}]]          L0 = 1;     displacement[{m_, ns_List}] :=        Total[Map[         If[Norm[p0[[#, All]] - p0[[m, All]]] <             bboxL*bboxH/Nnodes, -p0[[#, All]] + p0[[m, All]], {0, 0}] &,          ns]];          Do[       p0 = p0 + timeStep*Map[displacement, dt];       Do[        p0[[i, 1]] = Max[p0[[i, 1]], 0];        p0[[i, 2]] = Max[p0[[i, 2]], 0];        p0[[i, 1]] = Min[p0[[i, 1]], bboxL];        p0[[i, 2]] = Min[p0[[i, 2]], bboxH];        , {i, Nnodes}];       dt = DelaunayTriangulation[p0];       edges = Flatten[Map[toPairs, dt], 1];            , {i, 400}];          Graphics[GraphicsComplex[       p0, {Line[edges], Red, PointSize[Medium], Point[p0]}]]       You start off with this mesh: ![](http://i.stack.imgur.com/szgd0.png) Then after some iterations you get: ![](http://i.stack.imgur.com/xhuvg.png) What I'd like to do next is instead of meshing to a boring old square I'd like to be able to mesh to any geometry whether its given in a functional form or an array of points. Can anybody suggest how to proceed? Maybe just a simple circle would be a nice next step for practice? Everyone feel free to edit my post and join in the fun. Many thanks for any help :) Also many thanks go to MarkMcClure for helping me on getting to this stage!


Normal Plot (visual test for normality)

I wish to construct a Normal Plot to visually test for normality of data. My data is: > {188,199,171,200,219,172,235,194,234,206} And needs to be plotted to look something like this: ![enter image description here](http://i.stack.imgur.com/BOPxa.jpg) Whereby the data points are sorted from low to high and then plotted against the mid-point of their probability bins. So, in this case there are 10 data points so 10 bins with mid points of 5%, 15%, 25% etc. For this data, you would then see the lowest value (171) plotted at (171,5%), the next value (172) plotted at (172,15%) and so on. Any ideas where I can find the answers?


How to make InputTable

There is InputField in mma but how to make InputTable? In MathCAD it`s possible to insert Excel spreadsheet with input and output variables.Input variables I use for filling of header row and column and output variable for output. How to make the same functionality in mma? Thanks in advance


Difference between Directory[] and NotebookDirectory[] .. a trailing /?

The following was the code:               Directory[]     NotebookDirectory[]      The output was               "/media/Dataholder/final"          "/media/Dataholder/final/"      In the second case, there is a trailing **"/"** (I am on Mathematica 8 on Ubuntu) Just curious, why is there a difference ? Is is specific to my machine ? I found this when this was breaking the code, wherein I wanted to change the working directory to another one relative to the current directory, i.e. using               simFldr = Directory[] <> "anotherSubDirectory"      Though this sounds trivial, the patchwork needed to get to that directory will be non trivial since I have a code which must work **both on Windows and Unix**. Any _smart_ solution to set the directory to a subdirectory ?


How to apply RootLocusPlot corectly

I have to analyze the complex regions of variable c which is define obtained with `InverseLaplace` help in the form               Re[c] + Im[c] == -10 s^2 - (1/(2 Pi)     NIntegrate[1/Q[k, s], {k, -∞, ∞}])^-1;          Q[k_, s_] := 5 k^4 - 3 (-k 2 + s)^2;      I applied the `RootLocusPlot` on this polynomial, but I am not sure what I got. Is this complex plane of `c` variable? I need to see what will happen with `c` when `s` goes to $∞$ or $0$, but in my figure I can not understand that? Is there another command to plot diagram depends on complex solutions?               RootLocusPlot[       TransferFunctionModel[Unevaluated[{{-10 s^2 - 5 k^4 - 3 (-k 2 + s)^2}}],                              s, SamplingPeriod ->None, SystemsModelLabels -> None],        {k, 0, 0.8}]      ![enter image description here](http://i.stack.imgur.com/9Rd5J.png)


Making a calculation with high precision

I would like to make the following calculation:               1/Sqrt[1 - (150^2 10^(-4))/(9 10^16.)] - 1      _Mathematica_ 8 returns 0. The result is obviously not 0, but my calculation must be losing precision. How can I compute this value with sufficient precision?


Collatz Tool Box --- any speed ups possible?

I have created a tool box for experimenting with the Collatz conjecture. Info here: Wolfram MathWorld and here: Wikipedia The patterns I have found allow us to make the conjecture jump through some hoops. **Final Edit** `countOrbit` has been re-cast as a `Do Until` loop because the logic behaves similar to a one-directional linked list and I don't think it can be improved. **Note: the number of sub orbits $\leq$ (total steps) / 6** **Edit for the down-voters:** the current maximum that collatz projects have reached is around $10^{18}$. The example below has two numbers $10^{301030}$ and $10^{477119}$ that my functions can use quickly and accurately. That is many magnitudes greater that what is currently being done. So, why the down- votes? This is one example: m is the count of numbers in an ascending sequence. uniqueRank[1,m] returns the first number of the first unique sub orbit of that length. omegaSubOrbit[x,m] returns the last number of that sub orbit. We display the digit counts of these numbers. Then we count the complete orbit down to 1. This takes a bit over 12 minutes on my AMD 1100T. The left-hand number is the count of multiplies (we don't count divisions by two) and the right-hand count is the number of sub orbits used to get the counts.               m = 1000000; x = uniqueRank[1, m];     y = omegaSubOrbit[x, m];     {IntegerLength[x], IntegerLength[y]}     countOrbit[1, x]      > {301030, 477119}   >  {4805005, 1903828}   >  {13420758, 1903828} 7.8 minutes to count all multiplies and divides My question: Since I'm using `For` and `While` in a few places, is there a way to speed up those functions? Especially, the countOrbit function?               ascendingQ[x_] := 3 == Mod[x, 4]     uniqueQ[x_] := 0 != Mod[2 x - 1, 3]     subOrbit[x_] :=       Block[{y = x},      Flatten[Join[     Table[y \[DirectedEdge] (y = 1/2 (3 y + 1)), {n, 1,        IntegerExponent[x + 1, 2] - 1}], {y \[DirectedEdge] (3 y + 1)/        2^IntegerExponent[3 y + 1, 2]}]]]     createSubOrbitGraph[n_] :=      Block[{j, v = {}},       For[j = 1, j <= n, j++,        If[uniqueQ[2 j + 1], AppendTo[v, subOrbit[2 j + 1]]];        ];       Flatten[v]       ]     uniqueRank[n_, m_] := Block[{a = If[1 != n && OddQ[n], n - 1, n]},        (n + IntegerExponent[a, 2]) 2^m - 1]       nonUniqueRank[n_, m_] := (2 n - 1)   2^m - 1     createOrbit[w_, x_] := Block[{u = subOrbit[x]},       While[w < u[[-1, 2]],         u = Flatten[AppendTo[u, subOrbit[u[[-1, 2]]]]]];        u]     createOrbitGraph[n_] :=      Block[{j, u = {}},       For[j = 1, j <= n, j++,        If[uniqueQ[2 j + 1], u = Union[u, createOrbit[2 j + 1, 2 j + 1]]];        ];       Flatten[u]       ]     omegaSubOrbit[x_, m_] :=       Block[{z = (-1 + (3/2)^m (1 + x))}, 2^(1 - IntegerExponent[2 z, 2]) z]     omegaSubOrbit[x_] :=       Block[{m = IntegerExponent[x + 1, 2], z = (-1 + (3/2)^m (1 + x))},        2^(1 - IntegerExponent[2 z, 2]) z]     countOrbit[w_, x_] :=       Block[{h = x, t, c, d = 0, s = 0, l = 0, m, n, a},       While[True,        m = IntegerExponent[h + 1, 2];        t = -1 + (3/2)^m (1 + h);        n = IntegerExponent[t, 2];        l += m;        d += n;        s += 1;        h = t/2^n;        If[h <= w, Break[]];        ];       c = 2 l + d;       a = If[1 == w, "Full ", "Extended Sub "];       Print["---Counts ", a, "Orbit---",        "\nNumber of Sub Orbits: ", s,        "\nMultiplications by 3: ", l,        "\nDivisions by 2:       ", l,        "\nExtra Divisions by 2: ", d,        "\nTotal for Orbit:      ", c]       ]          Some brief documentation:   **ascendingQ[x]** Returns True if odd x is ascending, False if descending   **uniqueQ[x]** Returns True if odd x is not embedded in any longer sequence   **subOrbit[x]** Returns graph data in the form {Head[DirectedEdge]Tail}   **createSubOrbitGraph[n]** Returns graph data of sub orbits up through n   **uniqueRank[n, m]** Returns the first number of the n-th unique occurance of a sub orbit of size m   **nonUniqueRank[n, m]** Returns the first number of the n-th occurance of a sub orbit of size m, which may not be unique.   **createOrbit[w, x]** Returns graph data for w=1 complete orbit or w=x extended sub orbit   Note: for a graph, both are equivalent. w=x produces fewer duplicates.   **createOrbitGraph[n]** Returns graph data of extended sub orbits up through n   **omegaSubOrbit[x]** Returns the last odd number of a sub orbit. (The one that required multiple divides.)   **omegaSubOrbit[x, m]** Same as above, but uses m to speed up the first step   **countOrbit[w, x]** Returns the count of multiply and division steps and the count of sub orbits processed, for w=1 complete orbit or w=x extended sub orbit **Edit** Replaced countOrbit[w,x] with refined version that counts divisions and multiplication. Reduced the time from 15 minutes to 7.8 minutes for the above example.


What type of solver does Mathematica use in LinearSolve

I have a question regarding linear equation solvers. For a specific 9x9 diagonal matrix, every method I tried in C++ (Gaus, GCC, BICGTAB ) wouldn't work, although these methods would work fine for different matrices. In Mathematica `LinearSolve` gave a solution for this matrix. So my question is: What type of solver does Mathematica use in `LinearSolve`?


Is it possible to import data from Google Analytics?

Using _Mathematica_ , is it possible to pull data directly from Google Analytics? Unfortunately, GA exports messy `csv` files, and I was wondering if there was a direct way of receiving this data. A quick Google search has shown that at one point Patrick Collison had devised a way, though perhaps due to copyright or other legal infringements, that knowledge has disappeared off the web. I'm very new to using _Mathematica_ , so any tips would be greatly appreciated. EDIT: As suggested, here is an example of the messy `csv` files:               All Web Site Data     Browser & OS     20130421-20130521               Browser,Visits,Pages / Visit,Avg. Visit Duration,% New Visits,Bounce Rate     Safari,534,4.57,00:03:31,59.36%,44.38%     Safari (in-app),426,5.21,00:02:54,97.65%,34.04%     Chrome,347,5.16,00:05:54,63.11%,28.24%     Internet Explorer,214,6.02,00:08:21,68.69%,20.56%     Android Browser,170,4.84,00:03:49,68.82%,37.65%     Firefox,156,5.44,00:05:02,67.95%,30.77%     IE with Chrome Frame,11,4.36,00:04:07,18.18%,18.18%     Maxthon,3,3.33,00:00:51,66.67%,0.00%     Opera Mini,2,1.00,00:00:00,100.00%,100.00%     BlackBerry,1,1.00,00:00:00,100.00%,100.00%     ,"1,865",5.08,00:04:31,71.31%,34.37%          Day,Visits     4/21/13,41     4/22/13,44     4/23/13,16     4/24/13,92     4/25/13,293     4/26/13,142     4/27/13,25     4/28/13,40     4/29/13,40     4/30/13,67     5/1/13,129     5/2/13,114     5/3/13,32     5/4/13,11     5/5/13,27     5/6/13,136     5/7/13,68     5/8/13,59     5/9/13,123     5/10/13,49     5/11/13,20     5/12/13,40     5/13/13,35     5/14/13,28     5/15/13,36     5/16/13,42     5/17/13,32     5/18/13,31     5/19/13,10     5/20/13,22     5/21/13,21     ,"1,865"


financial data behind Wolfram|Alpha and Finance Platform

I need to price 23,000 securities from 1999 to 2007, and they are surprisingly hard to find on subscription-based services, like Bloomberg LP, ThomsonReuters or S&P CapitalIQ offerings. Probably because deleted/expired/retired securities are dropped from the databases. Is there a good source on what financial information is available to/via Wolfram products, e.g. how much of my needs would be covered?


Forecast Future Stock Prices - Brownian Motion - Again

excuse me, I think I have here a technical problem with Mathematica yesterday I posted the question with the title: Forecast Future Stock Prices - Brownian Motion I am still not very experienced but when I copied your code and entered it, it worked perfectly. Today I reopened the Wolfram Finance Platform Quickstart Notebook, and tried to work further in a new notebook. Again it didn’t work. And when I opened the notebook with the code you sent me, and refreshed it, also the one that worked perfectly didn’t work anymore. Could it be that Mathenatica cannot distinguish between the two notebook, although they weren’t open at the same time? Or what could be the problem? Thank you for your help. So the whole code is here:               BrownianMotion[period_, "steps_Integer:" 1000, "init_:" 0] :=       Accumulate[Prepend[RandomVariate[NormalDistribution[0, Sqrt[period⁄steps]], steps], init]]     ListLinePlot[BrownianMotion[1, 1000], AxesLabel \[RightArrow] {"Time", B_t},       PlotLabel \[RightArrow] Style["Stochastic Brownian Motion", Bold]]          BrownianMotionPaths[period_, "steps_Integer:" 1000, paths_Integer,        init_List] /; (Length[init] == paths) ≔Transpose[        Accumulate[Prepend[          RandomVariate[NormalDistribution[0, Sqrt[period/steps]], {steps, paths}], init]]]     brownianPath =       ListLinePlot[BrownianMotionPaths[1, 1000, 50, ConstantArray[0.5, 50]],        AxesLabel \[RightArrow] {"Time", B_t},        PlotLabel \[RightArrow] Style["Stochastic Brownian Motion", Bold]]     GOOGExpRet = Mean[FinancialData["GOOG", "Return", DatePlus[-365], "Value"]]     GOOGPrice = FinancialData["GOOG"]     GOOGVol = FinancialData["GOOG", "Volatility50Day"]          ListLinePlot[      GOOGPrice*(1 + GOOGExpRetConstantArray[1, 251] + BrownianMotion[1, 250]*GOOGVol),       AxesLabel \[RightArrow] {"Time", B_t},       PlotLabel \[RightArrow] Style["Simulated Google Price", Bold]]     ListLinePlot[      GOOGPrice*(1 + GOOGExpRetConstantArray[1, {50, 251}] +          BrownianMotionPaths[1, 250, 50, ConstantArray[0.5, 50]]*GOOGVol),       AxesLabel \[RightArrow] {"Time", "St"},       PlotLabel \[RightArrow] Style["Simulated Google Price", Bold],       ImageSize \[RightArrow] 400]     Mean[(GOOGPrice (1 + GOOGExpRetConstantArray[1, {50, 251}] +             BrownianMotionPaths[1, 250, 50] GOOGVol))[[All, -1]]];          GOOGBMPlot =       Block[{meanGOOGPrice =          Mean[(GOOGPrice (1 + GOOGExpRetConstantArray[1, {50, 251}] +                BrownianMotionPaths[1, 250, 50] GOOGVol))[[All, -1]]]}, "         " simulatedGOOGPaths =         ListLinePlot[         GOOGPrice (1 + GOOGExpRetConstantArray[1, {50, 251}] +             BrownianMotionPaths[1, 250, 50] GOOGVol), AxesLabel \[RightArrow] {"Time", S_t},          PlotLabel \[RightArrow] Style["Simulated Google Prices\n(Brownian Motion)", Bold],          BaseStyle \[RightArrow] style, PlotRange \[RightArrow] {{0, 260}, {0, 1200}},          PlotStyle \[RightArrow] Directive[{Thin, Lighter@Gray}],          Epilog \[RightArrow] {{m8red[1], Point[{250, meanGOOGPrice}]},            Text[Style["Mean\n$" <> ToString[PaddedForm[meanGOOGPrice, {5, 2}]], m8red[1], Bold,              FontFamily \[RightArrow] "Verdana"], {215, meanGOOGPrice}], {m8red[1],             Line[{{245, meanGOOGPrice}, {255, meanGOOGPrice}}]}}]]      Hope you guys can help me. And one more question: how can I copy the mathematica code into a word file without having it in the formulae format? Thanks


How can I give graph required data with GUI?

Consider that I have the simple graph of               Graph[{"Uppsala" -> "Marsta", "Marsta" -> "Uppsala", "UpplandsVasby" -> "Sollentuna", "Sollentuna" -> "UpplandsVasby",        "UpplandsVasby" -> "Marsta", "Marsta" -> "UpplandsVasby",        "Stockholm" -> "Boo", "Boo" -> "Stockholm",        "Stockholm" -> "Lidingo", "Lidingo" -> "Stockholm",        "Stockholm" -> "Sollentuna", "Sollentuna" -> "Stockholm",        "Stockholm" -> "Taby", "Taby" -> "Stockholm"},       VertexLabels -> "Name"]      I want to add required data of the Graph such as `EdgeWeight, EdgeCapacity` or other required data with GUI. Preferably in Excel interactive data sheet . Could you please somebody help me on that?


NDsolve with variable end-point

I want to plot the solution a coupled ODEs as a function of the end point only. Mathematica code:               tmax = 5;     rr = 1;     p = 0;     x[r_, t_, p_] = r Cos[(2 \[Pi])/tmax t + p];     z[r_, t_, p_] = r Sin[(2 \[Pi])/tmax t + p];     g[r_, t_,         p_] = ((1 + z[r, t, p]) D[x[r, t, p], t] - (I + x[r, t, p]) D[          z[r, t, p], t])/(2 ((1 + z[r, t, p]^2) + (I + x[r, t, p]^2)));     b[r_, t_] = Sqrt[(1 + I) + r^2] t;     sol1 = NDSolve[{c1'[t] == -g[rr, t, p] Exp[-2 I b[rr, t] ] c2[t],          c2'[t] == g[rr, t, p] Exp[2 I b[rr, t]] c1[t], c1[0] == 1,          c2[0] == 0}, {c1, c2}, {t, 0, tmax}];     sol2 = NDSolve[{c1'[t] == -g[rr, t, p] Exp[-2 I b[rr, t] ] c2[t],          c2'[t] == g[rr, t, p] Exp[2 I b[rr, t]] c1[t], c1[0] == 0,          c2[0] == 1}, {c1, c2}, {t, 0, tmax}];      Then want to repeat this procedure for different `tmax` and plot `LogPlot[Evaluate[{{Abs[c2[t]/c1[t]]} /. sol1, {Abs[c1[t]/c2[t]]} /. sol2}], {t, 0, tmax}, PlotRange -> Full]` Many thanks to the helpers EDIT: In block diagram this is what I want: Given coupled ODEs that are dependent on `tmax` both as the end-point and as a parameter, find the solution for each `tmax`, `c1_tmax[t] c2_tmax[t]` define the functions:               c1[tmax]=c1_tmax[tmax]          c2[tmax]=c2_tmax[tmax]      plot `c2[tmax]/c1[tmax]` for `{tmax,0,20}` Here's what I finally did (I hope it actually does it):               rr = 0.8;     p = 0;     x[r_, t_, p_] = r Cos[(2 \[Pi])/tmax t + p];     z[r_, t_, p_] = r Sin[(2 \[Pi])/tmax t + p];     g[r_, t_,         p_] = ((1 + z[r, t, p]) D[x[r, t, p], t] - (I + x[r, t, p]) D[          z[r, t, p], t])/(2 ((1 + z[r, t, p]^2) + (I + x[r, t, p]^2)));     b[r_, t_] = Sqrt[(1 + I) + r^2] t;     sol1 = ParametricNDSolve[{c1'[           t] == -g[rr, t, p] Exp[-2 I b[rr, t] ] c2[t],          c2'[t] == g[rr, t, p] Exp[2 I b[rr, t]] c1[t], c1[0] == 1,          c2[0] == 0}, {c1, c2}, {t, 0, tmax}, {tmax}];     sol2 = ParametricNDSolve[{c1'[           t] == -g[rr, t, p] Exp[-2 I b[rr, t] ] c2[t],          c2'[t] == g[rr, t, p] Exp[2 I b[rr, t]] c1[t], c1[0] == 0,          c2[0] == 1}, {c1, c2}, {t, 0, tmax}, {tmax}];     LogPlot[Evaluate[{{Abs[c2[tmax][tmax]/c1[tmax][tmax]]} /.          sol1, {Abs[c1[tmax][tmax]/c2[tmax][tmax]]} /. sol2}], {tmax, 0,        20}, PlotRange -> {{0, 20}, {10^-3, 10^3}}]


Issue with NDSOlve while solving vector differential equation

I am trying to get solution of a vector differential equation               x'[t]= aa*x[s]       where aa is my 9X9 matrix               aa= {       {0, 0, 0, s, 0, 0, 0, 0, 0},       {0, 0, 0, 0, s, 0, 0, 0, 0},       {0, 0, 0, 0, 0, s, 0, 0, 0},       {-s, 0, 0, 0, 0, 0, 0.3, 0, 0},       {0, -s, 0, 0, 0, 0, 0, 0.3, 0},       {0, 0, -s, 0, 0, 0, 0, 0, 0.3},       {0, 0, 0, -0.3, 0, 0, 0, 0, 0},       {0, 0, 0, 0, -0.3, 0, 0, 0, 0},       {0, 0, 0, 0, 0, -0.3, 0, 0, 0}      }      This code               function1 =       NDSolve[{x'[s] == aa*x[s],         x[0] ==  {{1, 0, 0, 0, 1, 0, 0, 0, 1}}}, {x[s]}, {s, 0, 10}]      is giving me this error: > **NDSolve::deqn: "Equation or list of equations expected instead of True in > the first argument {True,True}"** Please help out how to solve this vector DE.


Finding all roots of the system of two complex equations

I need to find all roots for the system of two complex equations. Obviously I can rewrite them as 4 real however problem remains. I have looked through routines connected with using ContourPlot however in my case they cannot be applied I think. System is:               P1 x +I (A+a Abs[x]^2) x + I S y^2 Conjugate[x] == I F     P2 y +I (B+b Abs[y]^2) y + I S x^2 Conjugate[y] == 0      x,y are unknown variables, P1 , P2 some complex constants A,B,a,b S,F - real constants. However problem remains, do you know an algorithm for finding all roots of 4 equations?


Creating a PolyhedronData[] structure for custom polyhedra

The `PolyhedronData[]` structure is wonderfully rich. I would like to create data for my own polyhedra, not any of the many that Mathematica provides. Is this possible? I wouldn't need every property, but I would like it to function the same way, e.g., `PolyhedronData["MyPolyhedron", "VertexCoordinates"]` would return a list of vertex coordinates, etc. I can hack up `MyPolyhedronData[]`, but I would prefer to use `PolyhedronData[]` if possible. Thanks for ideas!


ParallelTable Works in Regular Notebook but Gives Error When Packaged

Consider the following:               grid = Tuples[Range[0, 3.3083, 0.08468], 3];     k = Length[grid]; vdw = {0.15, 0.19, 0.19, 0.195, 0.195};     PeriodicDistance =        Compile[{{x, _Real, 1}, {y, _Real, 2}, {r, _Real}},         Sqrt@Total[((x - y) - 3.3083*Round[(x - y)/3.3083])^2] - r,         CompilationTarget :> "C", RuntimeOptions -> "Speed"];      Now the following function:               Cavs[dat_?MatrixQ] := Module[{pos},       Do[        With[{tr = Transpose[dat[[v ;; -1 ;; 5]]]},         pos[v] =           ParallelTable[           Min[PeriodicDistance[grid[[i]], tr, vdw[[v]]]], {i, k}]         ],        {v, 1, 5}];       pos[2]       ]      with input file               dat = ReadList["filename.ext", {Word, Word} ~ Join ~ Table[Number, {4}]][[All, 4 ;; 6]];          Cavs[dat]      gives ![Mathematica graphics](http://i.stack.imgur.com/s0GPJ.png) This answer is exactly the same answer I get when I replace `ParallelTable` with `Table`. Now, if I include this function in a _Mathematica_ package I get all sorts of `Part Specification` errors. Here's a sample: ![Mathematica graphics](http://i.stack.imgur.com/1975y.png) I know `ParallelTable` is the culprit because if I replace it with `Table` in the package it works fine. I just don't know why it works in a normal _Mathematica_ notebook session but fails when packaged. Any ideas?


Interprocedural optimization

Lets say I want to build a list of the first 1000000 primes. This is simple enough, I can just do: `AbsoluteTiming[plist = Table[Prime[i], {i, 1000000}];]` and it takes 4.8 seconds. I can also find out of the number of primes less than 15485863 (the million$^{th}$ prime) using : `AbsoluteTiming[PrimePi[15485863]]` which takes negligible time. My impression is that there is no way to get a precise `PrimePi[n]` result without actually finding all the primes less than `n`. This means that to create a list of the first 1000000 primes, it should take negligible time. I believe though that instead of reusing the intermediaries generated from previous `Prime[n]` calls, it instead starts from scratch every time, and this is why it takes so long to run. While I can write my own function to memoize this, I don't see how this could not be built in. Additionally, while in this case I can memoise the process, that is something that I cannot do in general. I assume that in many cases involving table there would be significant savings from saving partial terms from the previous iterations, so I assume that there is a way to do this. Is this a way to enable these optimizations, or is it just wishful thinking? **Update:** Few things: \- Regardless of how `Prime` or `PrimePi` is implemented, taking 4+ seconds to generate the first million primes is rather ridiculous (I have a simple little sieve in C# that can do just over 50 million primes in that time) and I think that it stands to reason that this is because it is doing the same work over and over an over again. Perhaps this is a better example:   `AbsoluteTiming[list1 = Table[Sum[i,i,10000000+q],{q,1,10000}];]`   This took 95 seconds on my computer. That is more than a little excessive. The only possible way that I can think of that it took that long was that for every iteration, it optimized it (hopefully just once, but less hopefully, every time) to $1/2 (1000000 + q) (1000001 + q)$ and then at every time evaluated it. If I instead do `AbsoluteTiming[ list1 = Table[1/2 (1000000 + q) (1000001 + q), {q, 1, 10000}];]` it takes just .06 seconds (much better). Is there a way to get it to always turn the first into the second? Additionally, I would tend to doubt that it realizes that the different in terms forms a linear equation and that it would be easier to do an two additions, than two divisions, three multiplications and a division.


Full documentation for AppearanceElements

As explained in this solution,               ListAnimate[Table[Plot[Sin[n x], {x, 0, 2}], {n, 3}]]//InputForm      will allow me to view the types of appearance element for the `ListAnimate` controller. But the same method does not work for simple controls or compound `Manipulate`-s, e.g.               Control[{{u, 3, "hello"}, 1, 5, 0.1}] // InputForm     Manipulate[u, {{u, 3, "hello"}, 1, 5, 0.1}] // InputForm      as both are already in `InputForm`. Is there a complete list of `AppearanceElement` types in the documentation (I doubt that) or elsewhere, or a trustworthy way of extracting this information? Added in response to Nasser's solution: it would also be good to allocate exactly which appearance elements are appropriate to each control; looking at `Animator` I've found a couple more which are in the relevant documentation, see below.               appearanceList =        Sort@{"AutorunPlayButton", "BookmarksButton",              "BookmarksPlayButton","ContentResizeArea", "DirectionButton",              "FasterSlowerButtons", "HideControlsButton",              "InteractiveTradingChartMenu",              "InteractiveTradingChartSnapshotButton",              "InteractiveTradingChartResetButton", "InputField",              "InlineInputField", "ManipulatePlayButton", "ManipulateMenu",              "PlayPauseButton", "PlayButton", "PauseButton", "ResetPlayButton",              "ProgressSlider", "ResetButton", "SnapshotButton",              "StepLeftButton", "StepRightButton", "UpdateButton"};     Length@appearanceList     DynamicModule[{sal, dx = 0.5, dy = 0.5, anim1, anim2, loc, swatch},       Column@{         Control[{sal, 1, 10, AppearanceElements -> appearanceList, Appearance -> "Open"}],          Control[{sal, 1, 10, AppearanceElements -> All, Appearance -> "Open"}],         Slider2D[Dynamic@{dx, dy}],(* no appearance elements *)         Animator[Dynamic[anim1], {0, 1, 0.1}, AppearanceElements -> appearanceList,           AnimationRunning -> False],         Animator[Dynamic[anim2], {0, 1, 0.1}, AppearanceElements -> All,            AnimationRunning -> False]        }]      ![image of output of above](http://i.stack.imgur.com/GKDca.jpg) This brings the total to 26, including `All` and `None`. By the way, it is odd that the `ResetPlayButton` looks exactly like the `PlayButton`, as far as I can see.


Is there a way to convert an image into a Graph?

I'm trying to convert an image with several overlapping dots into a `Graph`. The goal is to be able to derive the Kirchhoff matrix for the randomly created "network of resistors" a.k.a dots with the function `KirchhoffMatrix[]`. Any thoughts or ideas? Here's the image I'm trying to extract the graph from: ![enter image description here](http://i.stack.imgur.com/9HXZ5.png) Haha, sorry I suppose I have been pretty vague with this question. I am currently researching percolation simulations. The dots in the image represent metallic particles. The dots the overlap represent metallic particles connected via a resistor. We randomize the dots on the screen, group the ones that are touching with `MorphologicalComponents[] // Colorize` , and then we Isolate the 'BackBone Cluster' a.k.a the largest component with `DeleteSmallComponents[]`. We check to see if the cluster spans all the way from the top to the bottom and if it does, the sample percolated. We are then trying to find the conductance of the sample from the BackBone cluster. We have been using the Finite Element Method for this, which requires the `KirchhoffMatrix[]`. Your answer, Vitaliy Kaurov, looks like it will very thoroughly answer my question. I'm going to test things before I accept it but thank you for putting so much time into it!!


Change of coordinates for an InterpolatingFunction

This is a toy example of the question I have but I think it illustrates the point. I have a function `y[x]` which is an interpolating function. Let's define it through:               y=y1 /. NDSolve[{y1''[x]+y1'[x]+y1[x]==0,y1[0]==1,y1'[0]==0},y1, {x, 0, 5}][[1, 1]]      I need to pass this function into another differential equation as the initial condition for the new system (it's time dependent). However, the new differential equation has to be in polar coordinates so I need the above function converted into polar coordinates. Of course I could do this simply by writing:               Interpolation[{Sqrt[y[#]^2 + #^2], ArcTan[y[#]/#]} & /@ Range[0.001, 5, 0.1]]      Which will give me an interpolating function in the right coordinate system. However, with the above, I have had to chose the `x` values that I pass in by hand (ie. `Range[0.001,10,0.1]`). I would like to take as much data from the original `InterpolatingFunction` `y[x]` as I can. The grid within the interpolating function won't be even and there is, as far as I know, gradient data within the function as well. I would like to be able to translate the original `y[x]` `InterpolatingFunction` into a `θ[r]` `InterpolatingFunction` with as much fidelity as I can. I have seen that within `Head[y[x]][[4]]` there is data of the form `{Developer`PackedArrayForm,List_,List_}` but it's not clear what the syntax is. If anybody knows how to pass my `y[x]` into a `θ[r]` as accurately as possible, I would be very grateful. **Edit** Thanks to mmal's comment I see a way forward. In the first link there is an answer to a similar question. If we load:               Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]      Then we can define the following function:               Clear[reconstructInterpolatingFunction];     reconstructInterpolatingFunction[intf_InterpolatingFunction] :=      With[{data = intf[[4, 3]],      step = Subtract @@ Reverse[Take[intf[[4, 2]], 2]],      order = Developer`FromPackedArray@InterpolatingFunctionInterpolationOrder[intf],      grid = InterpolatingFunctionGrid[intf]},      Interpolation[MapThread[Prepend, {Partition[data, step], grid}],      InterpolationOrder -> order]];      Inspecting the term `MapThread[Prepend, {Partition[data, step], grid}]` for the `InterpolatingFunction` from `NDSolve` I find that the output is of the form:               {...,{{x},y[x],y'[x],y''[x]},...etc.}      Thus, this is what is needed to be transformed into polar coordinates and turned back into an `InterpolatingFunction`. This is a much simpler task than I originally had so many thanks to mmal. I shan't be able to finish answering this question tonight so if anyone fancies playing with the derivative terms, please do so.


Space-efficient null space of sparse array

I have a roughly 100,000 × 3,000 matrix (as a `SparseArray`) that I'd like to find the kernel (null space) of. It has about 500,000 nonzero entries, all -1 or 1. When I tried with `NullSpace`, it ate up 8 GB of RAM, complained about insufficient memory and shut down:               No more memory available.     Mathematica kernel has shut down.     Try quitting other applications and then retry.      Is there a better way to do this? Something a bit more efficient with memory (either a different Mathematica technique or a different language altogether)? I don't think there's any structure in the matrix to exploit, beyond what I've mentioned.


How to take the derivative w.r.t. an arbitrary function?

EDIT: The answer posted by @Jens works for built-in functions only. However I'm starting to wonder if this is related to my Mathematica install somehow. I have version 7. Here is an example in the Mathematica documentation center that implies that if I ask `InverseFunction[]` to find the inverse of a non- built-in pure function, it will be able to. However, as a test I tried to duplicate the result: The documentation center gives `In:= InverseFunction[(a # + b)/(c # + d) &]` `Out:= (-b+d#1)/(a-c#1) &`. Using the exact same input, I get `Out:= InverseFunction[(a # + b)/(c # + d) &]`, which is just the inputted command. :\ The documentation center is talking about version 9. Is there some fundamental difference in how versions 7 and 9 use `InverseFunction`? Is there any workaround? I've also tried to use other definitions other than `InverseFunction[]`, such as `Solve[]`...but in that case `Solve[]` uses inverse functions to find the solution (as evinced by the message I get: `InverseFunction::ifun: Inverse functions are being used. Values may be lost for multivalued inverses. >>` For example, following Jens's answer: `In:=InverseFunction[g][z]` and `In:=q /. Solve[g[q] == z, q][[1]]` both give the same answer, $g^{(-1)}[z]$. If you replace "`g`" with "`Log`" or the head of any other built-in function, they give the same answer; for example, `In:=InverseFunction[Log][z]` and `In:=q /. Solve[Log[q] == z, q][[1]]` give an answer of $e^z$, which is correct. But while the function using `Solve` can deal with non-built-in functions, e.g. `In:=q /. Solve[Log[q] == z, q][[1]]` `Out:=10^z`, which is of course the right answer. The problem is that when trying to implement this as a workaround based on Jens's solution, it hangs up on the same error for some reason, namely that it doesn't know what do to with non- built-in functions. Being relatively inexperienced at programming in Mathematica I'm not sure what other workarounds there may be. It also seems strange that the documentation center's example doesn't work for me, although as I say I think it's probably a version issue. Does anyone have any ideas? _ I want to be able to take the derivative of one function (of a given variable) w.r.t. a different function (of the same variable), i.e. $\frac{df[x]}{dg[x]}$. I know you can use the chain rule to appropriately recast this into the form $\frac{dh[y]}{dy}$, where $h[y]$ is $f[x]$ evaluated at $x=g^{-1}(y)$, with $g^{-1}$ the inverse function of $g$. There are a couple semi-related questions already posted, one of which is here, asking about how to take the derivative of the log of an arbitrary function. I already asked a question about VariationalD (which I initially thought did what I wanted) here. I was referenced to a third question here on the `Dt[]` command, but I can't figure out how to get what I want from there, either. In messing around with `D[]` and `Dt[]`, I have found that, weirdly, `D[]` will actually do this for some special cases. For example, `In:= D[Log[x],Log[x]]` `Out:= 1` and `In:= D[Log[x]^2,Log[x]]` `Out:= 2Log[x]`. However, commands such as `D[Log[x^2],Log[x]]` and `D[x,Log[x]]` return zero. `Dt[]`, meanwhile, heads in the right direction, for example: `In:= Dt[Log[x^2],Log[x]]` `Out:= 2 Dt[x,Log[x]]/x`. This is correct except that I don't know how to make it evaluate, even though I'm sure Mathematica can handle inverting a function to use the chain rule. I don't want to use the logarithm function, it's just an example. I want to be able to take the derivative of a fit (with a complicated functional form) to experimental data w.r.t. different (complicated) functions. So while in principle I could hash out the equivalent derivative w.r.t. $x$, I really don't want to :)


$RecursionLimit::reclim: Recursion depth of 256 exceeded. >> error in CDF deployment

When I am executing this code in notebook, there is no error but when I am deploying it in CDF, this error is coming. > $RecursionLimit::reclim: Recursion depth of 256 exceeded. >> The code is               With[{y1 = {1, 2, 2, 1, 7}, y2 = {0, 3.27, 4.188, 7.331, 4.694}},       Column[        { Spacer[70],           Text[Style["iPhone and iPad quarterly sales- units, million", Bold, 18]],           Column[            {Spacer[70],              Text[Style["Click on/off:", Bold, 14]],              q1 = True; q2 = True;             Row[               {Labeled[                  Button["     ", q1 = ! q1, Background -> Blue, Appearance->"Frameless"],                  "iPhone", {Right}                ],                 Spacer[19],                 Labeled[                  Button["     ",q2 =!q2,Background -> Orange, Appearance -> "Frameless"],                  "iPad", {Right}                ]               }              ],               Column[                {Dynamic@ BarChart[                            Table[{If[q1, y1[[i]], 0], If[q2, y2[[i]], 0]},{i, 1, 5,  1}],                             BarSpacing -> 0.8, ChartStyle -> {Blue, Orange},                             ImageSize -> {600, 280},                             GridLines -> {None, Automatic}                          ]                }              ]}]}]]      ![Mathematica graphics](http://i.stack.imgur.com/viW3J.png) I have tried using               $RecursionLimit = Infinity        But it has not worked. Please help.


Resolving reduced resolution issues in WSMLink

I have been attempting to evaluate Wolfram System Modeler (WSM) and it has not been going smoothly. It looks like some of the Modelica Models (combiTable1D for instance) supplied are not complete or not functional in WSM. I am working with Wolfram Support to get some clarification on that, but after days of trying I have been unable to get a simple output=input model working. What I am trying to do as a first step is to just get an audio file into simulation and to port this straight through to an output to verify that it got in with reasonable accuracy. To do this I start with a very simple model:               model AudioProcessing       Modelica.Blocks.Interfaces.RealInput u=5;       Modelica.Blocks.Interfaces.RealOutput y;     equation        connect(u,y)      end AudioProcessing;      Here I have set the input to the constant 5 just to see if I can run the simulations without error and indeed this works fine. In order to bring in the .WAV file I have tried many things, but the best results I get so far is to use `WSMLink` and the `WSMInputFunctions` option of `WSMSimulate` to provide and interpolated version of the .WAV to the simulation. For instance:               Needs["WSMLink`"]     rawAudio = Import["C:\\Users\\vandel\\Desktop\\Mathematica\\Guitar_Sample.wav"]     samplePeriod = N[1/First[rawAudio][[-1]]];     sampleData = First[rawAudio][[1, 1]];     audioTimeSeries = Table[{n*samplePeriod, sampleData[[n + 1]]}, {n, 0, Length[sampleData] - 1}];     audiofunction = Interpolation[audioTimeSeries];     Plot[audiofunction[t], {t, 0, 10}, PlotRange -> All]      This plot looks fine and I can generate reasonable audio using the interpolation function. Now I try to bring that into WSM as follows:               M = WSMSimulate[audioSignal, {0, 10}, WSMInputFunctions -> {"u" -> (audiofunction[#] &)}];      This runs fine but when I plot this as follows:               WSMPlot[M,"y", PlotRange -> All]      The resolution is so reduced that the sound can not be reproduced. The same takes place with the variable `u` and when I use the returned interploation table to build a new signal with higher time resolution such as:               {outputVector} = M[{"u"}];     testPlot = Table[outputVector[t], {t, 0, 10, .00001}];     ListPlot[testPlot, PlotRange -> All]      The plot from this looks just like the earlier plot. I have tried using different solver methods and high numbers of `InterpolationPoints` and `InterpolationOrder` to no avail. Any insight would be appreciated and if there is a better way to get a real world signal sample into the application I'd be happy to look at that as well.


Limiting form of a polynomial expression

When simplifying an expression by hand, a trick that is often used is to remove terms that are lower powers of the independent variable, for instance, as $x \rightarrow \infty$, $x^2 + x$ becomes simply $x^2$ I am trying to replicate this functionality in Mathematica. Limit seems like an obvious choice, but               Limit[x^2 + x, x -> ∞]      simply returns $∞$ (not terribly helpful). Another option is Series, but it seems that one has to pass the highest power in the expression to get the desired result, with               Normal@Series[x^2 + x, {x, ∞, -2}]      returning the expected $x^2$. However, this does not work in general for more complicated expressions, when the highest power may not be so obvious. Consider the following example: $\frac{x^2+x}{x+1}$ We expect that the limiting form of this expression as $x \rightarrow \infty$ should be $x$ (the top becomes $x^2$, the bottom becomes $x$, and this then simplifies to $x$). However, if you just use the highest power available, Series returns 0 (you have to actually use Normal@Series[x^2 + x, {x, ∞, **-1** }]). My question is, can anyone produce a generalized piece of code that can produce a limiting expression? It would be good if the procedure handled the other extreme as well, when the variable in question approaches 0 (in which case $x^2 + x$ would simplify to $x$). **Edit:** It seems that the main issue for the solutions presented so far is that the form of the expression is not consistent. These operations are relatively easy to perform by hand, but sometimes tedious, which is why it would be nice to have Mathematica do it for me! Here's a pathological example that I can reduce by hand and for which the accepted solution should be able to return the correct result: $\frac{\sqrt{x^3 + x}}{x^5 + x + 1} \frac{x^2}{x^{10} + x} + \frac{x^5 + x}{x}$ (The right answer is $x^4$)


Is it possible to `Protect` a dynamic programming process?

I wrote a function using dynamic programming to speed up the evaluation. For safety, I also want to protect this function. Take factorial for example:               fac[0] = 1;     fac[n_] := fac[n] = n*fac[n - 1];     Protect@fac;      `fac[3]` will return a `Set::write` error and give the right answer 6. Although `Quiet@fac[3]` or `Off[Set::write]` seems to work, the sacrifice is the speed, which can be verified by`?fac`: > Global`fac > > Attributes[fac]={Protected} > > fac[0]=1 > > fac[n_]:=fac[n]=n fac[n-1] i.e. after the evaluation of `fac[3]`, _Mathematica_ does not store the values: fac[1],fac[2],fac[3].(Of course it doesn't, since the fac is protected.) So what can be done to make `Protect` and dynamic programming process live with each other?


Series expansion for $\frac{1}{x+1}$ in terms of $\frac{1}{x-1}$

I would like to expand a function as $$\frac{1}{x+1} = \frac{1}{x-1+2} = \frac{1}{x-1} \frac{1}{ 1+\frac{2}{x-1}} = \frac{1}{x-1} \left[ 1- \frac{2}{x-1} + \left(\frac{2}{x-1}\right)^2 + \cdots \right]$$ I tried > Series[1/(x + 1), {x, Infinity + 1, 3}] apprently it does not work. Is there any robust way to realize this kind of expansion? Assume $|x|$ is sufficiently large.


How to get the time when a notebook is saved and closed

I want to get the time when a notebook is created and the time when the notebook is saved and closed, that is to say, the whole time when a notebook exist. What should I do? Thank you!


How to get an equivalent of WeightedData in Mathematica 8?

Is there an equivalent command of `WeightedData` (new in version 9) in Mathematica 8 or I have to define it by myself? I haven't found anything in the site or googleing it... If there is not such command do you have some suggestions for defining it?


Resonance Curve using NDSolve

I am trying to make a resonance curve like this one below, using NDSolve. ![enter image description here](http://i.stack.imgur.com/ely3v.jpg) I tried to use code as below. Basically I try to hold solution for a w (driving frequency value) using NumericQ and then find the max amplitude using FindMaxValue when t is big enough. But my code returns a lot of error code I don't understand. By the way, I am using NDSolve directly, so I can test the accurateness of NDSolve Method.               ClearAll;          f[w_?NumericQ] :=      Block[{sol},        sol = NDSolve[{x''[t] + x'[t] + x[t] == Cos[w*t], x[0] == 0, x'[0] == 0},          x[t], {t, 0, 100}];      (FindMaxValue[x[t], {t, 50}])[[1]]]          ListLinePlot[Table[f[w], {w, 0, 100, 1}], DataRange -> {0, 100}]


Express a complex function $f(z)$ as $u(x,y)+iv(x,y)$

How can I write a complex function $f(z)$ in the form $u(x,y)+iv(x,y)$ using Mathematica? Re and Im do not work, because they do it for complex numbers, not functions. For example, if I try               Re[2 I (z) + 6 Conjugate[(z)] + Sin[(z)]]      Mathematica returns:               -2 Im[z] + 6 Re[z] + Re[Sin[z]]


Calling several compiled functions inside another

Below, there is an example how I tried to call the compiled function "position" (which i got from this link position) inside another one.               position = Compile[{{mat, _Integer, 2}, {elm, _Integer, 0}}, Module[{result = Internal`Bag[Most[{0}]], i, j},      Table[If[mat[[i, j]] === elm,        Internal`StuffBag[result, Internal`Bag[{i, j}]]], {i,        Length[mat]}, {j, Length[First[mat]]}];     Table[      Internal`BagPart[pos, {1, 2}], {pos,        Internal`BagPart[result, All]}]], CompilationTarget -> "C", RuntimeOptions -> "Speed"];      Now, I try to call the position function inside another and I do this with the "With"-function.               Ex = With[{pos = position}, Compile[{{G0, _Real, 2}}, Module[{G = G0, P, n, p},      P = {2, 5, 1, 6};      n = Length[G];      p = pos[G, #] & /@ {P[[2]], P[[3]]};      ], CompilationTarget -> "C",      CompilationOptions -> {"InlineCompiledFunctions" -> True}]];      My question is, whether there is another way of calling a compiled function inside another, maybe without defining this variable "pos" at the beginning?


Substituting values in 3j symbols

I believe these three expressions should give the same answer of `-1/Sqrt[3]`, but the first gives `+1/Sqrt[3]` whereas the second and third give the correct value, using _Mathematica 8_. What am I doing wrong?               ThreeJSymbol[{a, 0}, {b, 0}, {c, 0}] /. {a -> 1, b -> 1, c -> 0}        ThreeJSymbol[{a, 0} /. a -> 1, {b, 0} /. b -> 1, {c, 0} /. c -> 0]       ThreeJSymbol[{1, 0}, {1, 0}, {0, 0}]


Real Size Image Printing

I am generating a complicated graphics with Mathematica, but with objects of given sizes (e.g. a line of length 1 inch, between two points). I want to make sure that when I export the graphics, e.g. as pdf, and then when I print it, the line length on paper will be one inch, without additional tweaking (assuming no scaling when printing).


How do I get a plot with a certain size?

I am currently creating a poster for a conference in Scribus. I have a given space on the poster for a plot that I want to create with Mathematica. I don't want to scale in in Scribus, as this would change the font size. Thus, the image should already have the expected size when I export it to PDF. However, the results I put into `ImageSize` don't match the dimensions of the PDF created. Is there a possibility to create a plot that is trimmed to the actual content (plot and labels) without a white border and matches a given size? Here is an example. I have a 100mm x 200mm slot in my poster, and I would like to fill it with the Plot below. AspectRatio etc. should be adjusted to the given dimensions. As I want to preserve my font size, it is not enough to export the correct AspectRatio, but I need the dimensions.               Plot[x^2, {x, 0, 2}, LabelStyle -> {FontFamily -> "Helvetica", 24},       ImageSize -> {2.835 100, 2.835 200}, AspectRatio -> Full,       RotateLabel -> True, Frame -> True,       FrameLabel -> {{"I [a.u.]", ""}, {"position (mm)", ""}}]      I checked with WolframAlpha that 2.835 is the factor pt->mm, as 72 is for pt->inch. However, if I export this plot to PDF, Acrobat tells me the dimensions are 69.8mm x 140.4mm. Additionally, I am dealing with a white border, that I cannot remove with `ImagePadding->0`, as that just leaves the coordinate system without the labels. This is bad because for example, my caption next to the image now starts above the image.


Using RSolve correctly

I am having problems persuading _Mathematica_ to solve even the simplest recurrence relations. As an example, how would you do the following?               RSolve[{q[i] == 1 + (i - 1)*q[i - 1], q[0] == 0}, q[i], {i}]      ~~**Addendum.** As a further frustration, isn't this exactly equivalent? _Mathematica_ can't solve it it seems. > RSolve[{q[i, k] == 1 + ((i - 1))*q[i - 1, k - 1], q[1, 1] == 1},   >  q[i, k], {i, k}] ~~


predator prey model with prey refuge

I want to plot the phase diagram of prey predator versus prey refuge to see how the prey refuge influences the population of prey and predator.And this is the system $x'=\alpha x(1-x/k)-\beta\frac{(1-m)xy}{1+a(1-m)x}$ $y'=-\gamma y+c\beta\frac{(1-m)xy}{1+a(1-m)x}$ The prey predator with Holling type II model is incorporating a prey refuge, $mx$ and $k$, $\alpha$, $\gamma$, $c$ and $\beta/\alpha$ are the carrying capacity, growth rate of prey, death rate of predator, conversion factor denoting the number of newly born predators for each captured prey and maximum number of prey that can be eaten by each predator in unit time respectively. I have the numerical value for $a=0.02$, $k=100$, $\alpha=10$, $\beta=0.6$, $\gamma=0.09$, $c=0.02$. Thanks so much!


Solve simple differential equation - Error?

I get the error "The function Te appears with no arguments." when running this code. I'm not sure why. Is it because of the $Abs[\Gamma]$ ?               C1 = 10^-10;     C2 = 0.1*C1;     R = 50;     Tb = 0.1;     Geb = 5*10^-15;     Z0 = 50;     L[Te_] := 10^-9 + 10^-9*(Te - 0.1);     Zlcr[Te_, w_] := (1/R + 1/(I*L[Te]*w) + I*C1*w)^-1;     Zload[Te_, w_] := -I*w*C2 + Zlcr[Te, w];     \[CapitalGamma][Te_, w_] := (Zload[Te, w] - Z0)/(Zload[Te, w] + Z0);     y[Te_, w_] := (Abs[\[CapitalGamma][Te, w]])^2;     p[Te_, w_] := Abs[\[CapitalGamma][Te, w]]     Co = 10^-28;     Vol = 10^-21;     Cv = Co/Vol;     eqn1[w_, Te_, Pprobe_, t_] :=        Cv*Te'[t] ==   (Cv -   y[Te, w])*5 y[Te, w]* Pprobe     eqn2 = eqn1[3*10^9, Te, 10^-15, t]     sol = DSolve[     {eqn2, Te[0] == 0 }, Te[t], t  ]


Combining ArrayPlot and Plot

I have two plots.   * plot1 is a colour graph generated using ArrayPlot.    * plot2 is a function plotted using Plot. I want to do two things.   1. Scale the axes of plot1 to be the same as plot2 (instead of just pixel counts).   2. Overlay plot2 onto plot1. As an example, say I have               plot1 = ArrayPlot[RandomReal[{0, 1}, {100, 100}], FrameTicks -> Automatic]      ![](http://i.stack.imgur.com/jyx0B.png)               plot2 = Plot[x^2, {x, 0, Pi}, PlotRange -> {0, 2 Pi}, PlotStyle -> {Thick,Red}]      ![](http://i.stack.imgur.com/JyQAA.png) How do I scale plot1 to read x-values from 0 to $\pi$ and y-values from 0 to $2\pi$ and then overlay plot2 on top of plot1? I'm open to suggestions on using different plotting functions if there's a more logical way of doing this.


Why is ListLogPlot skipping entire decades?

I'm having an issue with Mathematica wherein, when trying to use ListLogPlot, the scale of the y-axis skips entire decades. Instead of 1, 10, 100, 1000, it goes more like 10^2,10^4,10^6,10^8. I need it to, well, not do this. This is more or less my code, with different numbers introduced (although same order of magnitude)               data1 = {{{1, 1.432*10^8}, {2, 4.2*10^7}, {5., 1.68*10^7}, {7.,         5.21*10^6}, {10., 1.02*10^6}, {12., 5.37*10^5.}, {15., 1.76*10^5.}, {17.,         1.40*10^5.}, {20., 7.87*10^4}}}      Then               ListLogPlot[data1, Joined -> True, PlotMarkers -> {Automatic, Tiny},       PlotStyle -> Red, PlotRange -> {{0, 20}, {1, 1000000000}},       AspectRatio -> 1, Frame -> True]      And, at least for mine, it produces a graph wherein the ticks on the vertical log axis skip decades. There should also be a large white blank space towards the bottom of the graph. This is intentional, as I have several other sets of data I need to include using the Show function, and Show seems to default to the first graph set. So if I can get this graph to work, then it should be pretty easy to graph the others, and use the Show function. Any help is greatly appreciated.


How to plot data points in the form X, Y, E(X, Y) where X and Y coordinates are not ordered?

I have got a file with field values (RF simulation of a resonator) which consists of 3 columns: `X` and `Y` cartesian coordinates and the field value `E(X, Y)` with 9500 rows. The problem is that my external field simulation software is not able to print the required field on a regular mesh (polar or cartesian map) as shown below: > >       -15.00000      -26.00000   345000.00000 >        15.00000      -26.00000   361000.00000 >        12.20000      -27.40000   490000.00000 >       -12.20000      -27.40000   583000.00000 >        -9.27000      -28.50000  1050000.00000 >         9.27000      -28.50000  1140000.00000 >        16.50000      -28.60000   436000.00000 >       -16.50000      -28.60000   491000.00000 >         6.24000      -29.30000  1520000.00000 >        -6.24000      -29.30000  1730000.00000 >         3.14000      -29.80000  2110000.00000 >   My goal is to create from the data above an interpolated surface from which I could generate a nice field matrix with a certain resolution. My first idea was to use Gnuplot for this job so the scatter plot looks like this: ![enter image description here](http://i.stack.imgur.com/YMCVO.png) ..and then interpolation of the field points on a regular grid like this: ![enter image description here](http://i.stack.imgur.com/EzSmc.png) However, Gnuplot is great but it cannot write this interpolated field back into a file for further post processing. Now I am trying to apply the same procedure in Mathematica (ver 9) For this, I wrote the following simple commands:               stream = OpenRead["~/efields/em.dat"];          data = ReadList[stream, {Number, Number, Number}];          f = Interpolation[data];          ListPointPlot3D[{x, y, f[x, y]},        {x, Min[data[[All, 1]]], Max[data[[All, 1]]]},        {y, Min[data[[All, 2]]], Max[data[[All, 2]]]}]       Unfortunately this did not work and _Mathematica_ returned with 2 error messages: > Interpolation::udeg: Interpolation on unstructured grids is currently only > supported for InterpolationOrder->1 or InterpolationOrder->All. Order will > be reduced to 1. >>   >  ListPointPlot3D::nonopt: "Options expected (instead of {y,-480.,-26.}) > beyond position 1 in * Can anybody provide some support hints on this issue. Lets start with the basic:   1. How to plot the data correctly as scatter plot ?   2. How to create a surface from the randomly distributed field values ?


Import audio in uLaw format?

How do I import a uLaw-format audio file into _Mathematica_? Here's an example:   * hello-world.ulaw For reference, here's the same file in wav format:   * hello-world.wav As I understand it, the uLaw format contains raw µ-law audio data. In this respect, it should be very similar (or identical) to AU, which _Mathematica_ supports, except there is no header. I have tried:               Import["hello-world.ulaw", "AU"]      but _Mathematica_ returns:               Import::fmterr: Cannot import data as AU/SND format.      From the documentation, it looks like there is probably some combination of parameters and options that will work, but the `Import`/`Export` documentation doesn't go into much detail on how to actually use the various available options. (Or at least, not in a way that makes sense to me!)


Lookup in Inverse Symbolic Calculator+ from Mathematica

There is a useful feature in _WolframAlpha_ that allows to find a possible closed form for approximate numeric values. It can be used, for example, to guess the value of an integral that _Mathematica_ cannot evaluate symbolically.               Integrate[LogIntegral[x]^3/x^5, {x, 1, ∞}]     (* Integrate[LogIntegral[x]^3/x^5, {x, 1, ∞}] *)          N[%, 20]     (* -2.7107171698324070788 *)          Sign[%] WolframAlpha[ToString[Abs[%]], {{"PossibleClosedForm", 1}, "FormulaData"}] /. Hold[expr_ ≈ _] :> expr     (* -1/4 π^2 Log[3] *)      I noticed that sometimes _Inverse Symbolic Calculator+_ can find a closed form for numbers that cannot be recognized by _WolframAlpha_. Can anybody suggest _Mathematica_ code that queries _Inverse Symbolic Calculator+_ , parses a closed form returned by it and converts it into a _Mathematica_ expression?


GraphPlot labels overlapping

If I plot the following graph with an `EdgeRenderingFunction`, the position of both the labels are at dead center, and with a large graph I have the labels completely overlapping each other:               GraphPlot[{{1 -> 2, "a"}, {2 -> 1, "b"}},        DirectedEdges -> True, VertexCoordinateRules -> Automatic, VertexLabeling -> True,        EdgeRenderingFunction -> ({Blue, Arrow[#1, 0.1],          If[#3 =!= None, Text[Style[#3, Medium], Mean[#1], Background -> White], {}]} &)]      ![Mathematica graphics](http://i.stack.imgur.com/ueOBx.png) Is there a way to position the labels, say, at 60% down the edge instead of dead center, so that the labels don't have a chance to overlap? I've been toggling with `Mean[#1]` above but can't get this right positioning. Edit: improved formatting


Using external variable as a variable inside WhenEvent & NDSolve

I'm trying to use the new WhenEvent functionality of NDSolve in Mathematica 9, in order to perform an action when a variable in the system reaches a certain value. I would like this variable to come from an external variable, like so:               var = y; (* this could come from somewhere else *)     list = {};          (* keep track of values of x for which y[x] == 1 *)     NDSolve[{y''[x] == -y[x], y[0] == 1, y'[0] == 0,        WhenEvent[Round[var[x], 0.1] == 1, AppendTo[list, x]]},       y, {x, 0, 10}]      But this produces the errors > NDSolve::nbnum1: The function value Round[y[0.],0.1]==1 is not True or False > when the arguments are {0.,1.,0.,0.,-1.}. >> > > NDSolve::nbnum1: The function value Round[y[0.000143737],0.1]==1 is not True > or False when the arguments are > {0.000143737,1.,-0.000143737,-0.000143737,-1.}. >> > > NDSolve::nbnum1: The function value Round[y[0.000287473],0.1]==1 is not True > or False when the arguments are > {0.000287473,1.,-0.000287473,-0.000287473,-1.}. >> > > General::stop: Further output of NDSolve::nbnum1 will be suppressed during > this calculation. >> How can I use an "external" variable to specify which variable to watch in WhenEvent?


Can a function be made to accept a variable amount of inputs?

I have a function that takes two inputs and processes them for a single output. What I need is one that can take a varying number of inputs. and process them to a single output. Is this possible in Mathematica?                DatasetAverage[inputData_, inputData2_] := Block[{dataAvg, v, w},        v = Length[inputData];        w = Length[inputData2];        If [v != w,         Print["DatasetAverage: Data sample sizes do not match"]];        dataAvg = Table[Mean[{inputData[[i]], inputData2[[i]]}], {i, 1, Length[inputData2]}]      ]


Defining functions with changing number of variables

I am working with a bunch of functions of the form               fn[x1_,x2_,x3_,...,xn_] := x1x2+x2x3+...+xnx1      where $n$ changes. Is there a way to create these functions efficiently, without having to explicitly define each? I'm looking for a way of declaring, say, $n=5$ and getting back               f5[x1_,x2_,x3_,x4_,x5_]:=x1x2+x2x3+x3x4+x4x5+x5x1      Perhaps they could be defining iteratively? Since fn and fn-1 only differ by a few monomials. I appreciate any helpo that I can get! Thanks!


Function with different set of arguments

> **Possible Duplicate:**   >  How to create functions of arbitrary number of variables? i want to use a Function `f[]` with different set of arguments. example: `f[{x,y,z}]` as well as `f[{x1,y1,z1},{x2,y2,z2},...,{xn,yn,zn}]`. How do i write its definition to accept Both type of calls.


How write this Function with many arguments?

F[x1_,x2_,...,x99_]:=expr How to write this Function in mathematica whithout complete write it?


How to define a Mathematica Function with varying number of input and output arguments

In Matlab, such issue is handled by               varargout, // a cell structure to store all output arguments     varargin, // a cell structure to store all input arguments     nargout, // number of output arguments     nargin // number of input arguments      Is there any equivalent implementation in Mathematica, and how? A simple working example would be much appreciated!