Non-linear trend reduction with missing data

How can I reduce a non-linear trend of some data series if there are parts of "no data", represented by the value 99999? For example:               data={{124.55,368.632}, {124.6,281.976}, {124.65,200.952}, {124.7,91.384}, {124.75,-60.424},     {124.8,-282.504}, {124.85,-541.448}, {124.9,-378.76}, {124.95,99999}, {125,99999},     {125.05,99999}, {125.1,99999}, {125.15,99999}, {125.2,99999}, {125.25,99999}, {125.3,99999},     {125.35,265.46}, {125.4,376.75}, {125.45,462.54},...,{178.95,284.46}}      Normally, I am successful in reducing the non-linear trend of the data via               lm = LinearModelFit[data, {a, a^2, a^3, a^4, a^5},a];     Do[aha = Last[Take[data, {m, m}]]; y = Last[aha];        x = First[aha]; new[m] = y - lm[x], {m, idim}];      but have no idea how to do the trend-reduction between those data gaps (i.e., outside of the regions with data = 99999). The position of those regions is not constant. After the reduction is performed, the position of the "no data"-values should be the same as before. Due to answer 1, unfortunately there is no periodically or cyclically behaviour in the data at all. Here, for example, is another, but complete data set:                {{100.00,       0.303999        },        {100.05,       0.303999        },        {100.09,       0.176000        },        {100.15,       0.303999        },        {100.20,       0.176000        },        {100.25,       0.303999        },        {100.30,       0.431999        },        {100.34,       0.431999        },        {100.40,       0.559999        },        {100.45,       0.687999        },        {100.50,       0.687999        },        {100.55,       0.943999        },        {100.59,        1.07200        },        {100.65,        1.20000        },        {100.70,        1.32800        },        {100.75,        1.32800        },        {100.80,        1.20000        },        {100.84,        1.20000        },        {100.90,        1.20000        },        {100.95,        1.07200        },        {101.00,        1.07200        },        {101.05,        1.07200        },        {101.09,        1.07200        },        {101.15,        1.07200        },        {101.20,        1.07200        },        {101.25,        1.07200        },        {101.30,       0.943999        },        {101.34,       0.943999        },        {101.40,       0.943999        },        {101.45,       0.687999        },        {101.50,       0.431999        },        {101.55,       0.303999        },        {101.59,       4.800009E-002   },        {101.65,      -8.000003E-002   },        {101.70,      -0.207999        },        {101.75,      -0.464000        },        {101.80,      -0.719999        },        {101.84,      -0.847999        },        {101.90,      -0.847999        },        {101.95,      -0.975999        },        {102.00,       -1.10400        },        {102.05,       -1.23200        },        {102.09,       -1.36000        },        {102.15,       -1.36000        },        {102.20,       -1.36000        },        {102.25,       -1.36000        },        {102.30,       -1.36000        },        {102.34,       -1.23200        },        {102.40,       -1.10400        },        {102.45,       -1.10400        },        {102.50,      -0.975999        },        {102.55,      -0.847999        },        {102.59,      -0.719999        },        {102.65,      -0.591999        },        {102.70,      -0.464000        },        {102.75,      -0.207999        },        {102.80,       4.800009E-002   },        {102.84,       4.800009E-002   },        {102.90,       0.431999        },        {102.95,       0.687999        },        {103.00,       0.943999        },        {103.05,        1.20000        },        {103.09,        1.32800        },        {103.15,        1.32800        },        {103.20,        1.58400        },        {103.25,        1.71200        },        {103.30,        1.84000        },        {103.34,        1.96800        },        {103.40,        2.09600        },        {103.45,        2.22400        },        {103.50,        2.22400        },        {103.55,        2.35199        },        {103.59,        2.35199        },        {103.65,        2.48000        },        {103.70,        2.48000        },        {103.75,        2.60800        },        {103.80,        2.86399        },        {103.84,        2.86399        },        {103.90,        2.86399        },        {103.95,        2.86399        },        {104.00,        2.99200        },        {104.05,        2.86399        },        {104.09,        2.73600        },        {104.15,        2.60800        },        {104.20,        2.60800        },        {104.25,        2.73600        },        {104.30,        2.48000        },        {104.34,        2.48000        },        {104.40,        2.48000        },        {104.45,        2.35199        },        {104.50,        2.22400        },        {104.55,        2.09600        },        {104.59,        1.96800        },        {104.65,        1.84000        },        {104.70,        1.84000        },        {104.75,        1.71200        },        {104.80,        1.58400        },        {104.84,        1.71200        },        {104.90,        1.45600        },        {104.95,        1.45600        },        {105.00,        1.32800        },        {105.05,        1.32800        },        {105.09,        1.07200        },        {105.15,        1.07200        },        {105.20,       0.943999        },        {105.25,       0.943999        },        {105.30,       0.943999        },        {105.34,       0.815999        },        {105.40,       0.559999        },        {105.45,       4.800009E-002   },        {105.50,      -0.336000        },        {105.55,      -0.975999        },        {105.59,       -1.36000        },        {105.65,       -2.00000        },        {105.70,       -2.51200        },        {105.75,       -2.89599        },        {105.80,       -3.02400        },        {105.84,       -3.02400        },        {105.90,       -2.89599        },        {105.95,       -2.12800        },        {106.00,       -1.23200        },        {106.05,      -0.464000        },        {106.09,      -8.000003E-002   },        {106.15,       0.303999        },        {106.20,       0.559999        },        {106.25,       0.687999        },        {106.30,       0.943999        },        {106.34,        1.07200        },        {106.40,        1.32800        },        {106.45,        1.45600        },        {106.50,        1.58400        },        {106.55,        1.58400        },        {106.59,        1.58400        },        {106.65,        1.58400        },        {106.70,        1.58400        },        {106.75,        1.45600        },        {106.80,        1.32800        },        {106.84,        1.45600        },        {106.90,        1.32800        },        {106.95,        1.32800        },        {107.00,        1.32800        },        {107.05,        1.20000        },        {107.09,        1.07200        },        {107.15,       0.943999        },        {107.20,       0.943999        },        {107.25,       0.815999        },        {107.30,       0.815999        },        {107.34,       0.687999        },        {107.40,       0.559999        },        {107.45,       0.559999        },        {107.50,       0.559999        },        {107.55,       0.431999        },        {107.59,       0.431999        },        {107.65,       0.559999        },        {107.70,       0.431999        },        {107.75,       0.687999        },        {107.80,       0.815999        },        {107.84,        1.07200        },        {107.90,        1.07200        },        {107.95,        1.32800        },        {108.00,        1.45600        },        {108.05,        99999.0        },        {108.09,        99999.0        },        {108.15,        99999.0        },        {108.20,        99999.0        },        {108.25,        99999.0        },        {108.30,        99999.0        },        {108.34,        99999.0        },        {108.40,        99999.0        },        {108.45,        99999.0        },        {108.50,        99999.0        },        {108.55,        99999.0        },        {108.59,        99999.0        },        {108.65,        99999.0        },        {108.70,        99999.0        },        {108.75,        99999.0        },        {108.80,        99999.0        },        {108.84,        99999.0        },        {108.90,        99999.0        },        {108.95,        99999.0        },        {109.00,        99999.0        },        {109.05,        99999.0        },        {109.09,        99999.0        },        {109.15,        99999.0        },        {109.20,        99999.0        },        {109.25,        99999.0        },        {109.30,        99999.0        },        {109.34,        99999.0        },        {109.40,        99999.0        },        {109.45,        99999.0        },        {109.50,        99999.0        },        {109.55,        99999.0        },        {109.59,        99999.0        },        {109.65,        99999.0        },        {109.70,        99999.0        },        {109.75,        99999.0        },        {109.80,        99999.0        },        {109.84,        99999.0        },        {109.90,        99999.0        },        {109.95,        99999.0        },        {110.00,        99999.0        },        {110.05,        99999.0        },        {110.09,        99999.0        },        {110.15,        99999.0        },        {110.20,        99999.0        },        {110.25,        99999.0        },        {110.30,        99999.0        },        {110.34,        99999.0        },        {110.40,        99999.0        },        {110.45,        99999.0        },        {110.50,        99999.0        },        {110.55,        99999.0        },        {110.59,        99999.0        },        {110.65,        99999.0        },        {110.70,        99999.0        },        {110.75,        99999.0        },        {110.80,        99999.0        },        {110.84,        99999.0        },        {110.90,        99999.0        },        {110.95,        99999.0        },        {111.00,        99999.0        },        {111.05,        99999.0        },        {111.09,        99999.0        },        {111.15,        99999.0        },        {111.20,        99999.0        },        {111.25,        99999.0        },        {111.30,        99999.0        },        {111.34,        99999.0        },        {111.40,        99999.0        },        {111.45,        99999.0        },        {111.50,        99999.0        },        {111.55,        99999.0        },        {111.59,        99999.0        },        {111.65,        99999.0        },        {111.70,        99999.0        },        {111.75,        99999.0        },        {111.80,        99999.0        },        {111.84,        99999.0        },        {111.90,        99999.0        },        {111.95,        99999.0        },        {112.00,       4.800009E-002   },        {112.05,      -8.000003E-002   },        {112.09,      -8.000003E-002   },        {112.15,      -8.000003E-002   },        {112.20,      -8.000003E-002   },        {112.25,      -8.000003E-002   },        {112.30,      -0.336000        },        {112.34,      -0.464000        },        {112.40,      -0.336000        },        {112.45,      -0.336000        },        {112.50,      -0.336000        },        {112.55,      -0.336000        },        {112.59,      -0.336000        },        {112.65,      -0.336000        },        {112.70,      -8.000003E-002   },        {112.75,       4.800009E-002   },        {112.80,       0.176000        },        {112.84,       0.303999        },        {112.90,       0.559999        },        {112.95,       0.687999        },        {113.00,       0.943999        },        {113.05,        1.07200        },        {113.09,        1.20000        },        {113.15,        1.45600        },        {113.20,        1.71200        },        {113.25,        1.96800        },        {113.30,        2.35199        },        {113.34,        2.86399        },        {113.40,        3.12000        },        {113.45,        3.37599        },        {113.50,        3.63200        },        {113.55,        3.88799        },        {113.59,        3.88799        },        {113.65,        3.88799        },        {113.70,        4.01600        },        {113.75,        3.88799        },        {113.80,        4.01600        },        {113.84,        3.88799        },        {113.90,        3.75999        },        {113.95,        3.50400        },        {114.00,        2.99200        },        {114.05,        2.48000        },        {114.09,        1.96800        },        {114.15,        1.58400        },        {114.20,       0.943999        },        {114.25,       0.431999        },        {114.30,      -0.336000        },        {114.34,      -0.847999        },        {114.40,       -1.23200        },        {114.45,       -1.61600        },        {114.50,       -2.00000        },        {114.55,       -2.25599        },        {114.59,       -2.38399        },        {114.65,       -2.51200        },        {114.70,       -2.64000        },        {114.75,       -2.89599        },        {114.80,       -3.02400        },        {114.84,       -2.89599        },        {114.90,       -2.76799        },        {114.95,       -2.64000        },        {115.00,       -2.38399        },        {115.05,       -2.25599        },        {115.09,       -2.00000        },        {115.15,       -1.74400        },        {115.20,       -1.48800        },        {115.25,       -1.23200        },        {115.30,      -0.975999        },        {115.34,      -0.719999        },        {115.40,      -0.464000        },        {115.45,      -0.207999        },        {115.50,      -0.207999        },        {115.55,       4.800009E-002   },        {115.59,       4.800009E-002   },        {115.65,       4.800009E-002   },        {115.70,       4.800009E-002   },        {115.75,      -8.000003E-002   },        {115.80,       4.800009E-002   },        {115.84,      -8.000003E-002   },        {115.90,      -0.207999        },        {115.95,      -0.464000        },        {116.00,      -0.719999        },        {116.05,      -0.847999        },        {116.09,      -0.975999        },        {116.15,       -1.10400        },        {116.20,       -1.36000        },        {116.25,       -1.23200        },        {116.30,       -1.23200        },        {116.34,       -1.23200        },        {116.40,       -1.10400        },        {116.45,       -1.10400        },        {116.50,       -1.23200        },        {116.55,       -1.10400        },        {116.59,       -1.10400        },        {116.65,       -1.23200        },        {116.70,       -1.23200        },        {116.75,       -1.36000        },        {116.80,       -1.10400        },        {116.84,      -0.847999        },        {116.90,      -0.847999        },        {116.95,       -1.10400        },        {117.00,       -1.23200        },        {117.05,       -1.36000        },        {117.09,       -1.36000        },        {117.15,       -1.23200        },        {117.20,       -1.10400        },        {117.25,       -1.10400        },        {117.30,      -0.975999        },        {117.34,      -0.847999        },        {117.40,      -0.591999        },        {117.45,      -0.719999        },        {117.50,      -0.719999        },        {117.55,      -0.591999        },        {117.59,      -0.719999        },        {117.65,      -0.719999        },        {117.70,      -0.719999        },        {117.75,      -0.719999        },        {117.80,      -0.591999        },        {117.84,      -0.591999        },        {117.90,      -0.591999        },        {117.95,      -0.464000        },        {118.00,      -0.464000        },        {118.05,      -0.207999        },        {118.09,      -8.000003E-002   },        {118.15,       4.800009E-002   },        {118.20,      -8.000003E-002   },        {118.25,      -8.000003E-002   },        {118.30,      -8.000003E-002   },        {118.34,      -8.000003E-002   },        {118.40,      -8.000003E-002   },        {118.45,      -8.000003E-002   },        {118.50,      -8.000003E-002   },        {118.55,       4.800009E-002   },        {118.59,       4.800009E-002   },        {118.65,       4.800009E-002   },        {118.70,       4.800009E-002   },        {118.75,       4.800009E-002   },        {118.80,       4.800009E-002   },        {118.84,       0.176000        },        {118.90,       0.176000        },        {118.95,       0.176000        },        {119.00,       0.176000        },        {119.05,      -8.000003E-002   },        {119.09,      -0.207999        },        {119.15,      -0.207999        },        {119.20,      -0.207999        },        {119.25,      -8.000003E-002   },        {119.30,      -8.000003E-002   },        {119.34,       4.800009E-002   },        {119.40,       0.303999        },        {119.45,       0.559999        },        {119.50,       0.815999        },        {119.55,        1.07200        },        {119.59,        1.32800        },        {119.65,        1.58400        },        {119.70,        1.58400        },        {119.75,        1.84000        },        {119.80,        2.09600        },        {119.84,        2.35199        },        {119.90,        2.48000        },        {119.95,        2.73600        },        {120.00,        2.99200        },        {120.05,        3.24800        },        {120.09,        3.24800        },        {120.15,        3.24800        },        {120.20,        3.12000        },        {120.25,        2.99200        },        {120.30,        2.73600        },        {120.34,        2.60800        },        {120.40,        2.60800        },        {120.45,        2.73600        },        {120.50,        2.73600        },        {120.55,        2.99200        },        {120.59,        3.12000        },        {120.65,        3.24800        },        {120.70,        3.24800        },        {120.75,        3.24800        },        {120.80,        3.12000        },        {120.84,        3.12000        },        {120.90,        2.86399        },        {120.95,        2.86399        },        {121.00,        2.73600        },        {121.05,        2.60800        },        {121.09,        2.48000        },        {121.15,        2.60800        },        {121.20,        2.60800        },        {121.25,        2.60800        },        {121.30,        2.86399        },        {121.34,        2.86399        },        {121.40,        2.99200        },        {121.45,        2.86399        },        {121.50,        2.99200        },        {121.55,        2.99200        },        {121.59,        2.86399        },        {121.65,        2.86399        },        {121.70,        2.86399        },        {121.75,        2.86399        },        {121.80,        2.99200        },        {121.84,        3.12000        },        {121.90,        3.37599        },        {121.95,        3.50400        },        {122.00,        3.63200        },        {122.05,        3.50400        },        {122.09,        3.50400        },        {122.15,        3.50400        },        {122.20,        3.50400        },        {122.25,        3.50400        },        {122.30,        3.50400        },        {122.34,        3.37599        },        {122.40,        3.24800        },        {122.45,        3.24800        },        {122.50,        3.12000        },        {122.55,        3.12000        },        {122.59,        3.24800        },        {122.65,        3.37599        },        {122.70,        3.37599        },        {122.75,        3.50400        },        {122.80,        3.75999        },        {122.84,        4.01600        },        {122.90,        4.27200        },        {122.95,        4.65599        },        {123.00,        4.65599        },        {123.05,        4.78399        },        {123.09,        5.04000        },        {123.15,        5.29600        },        {123.20,        5.55199        },        {123.25,        5.80799        },        {123.30,        5.80799        },        {123.34,        5.80799        },        {123.40,        5.93599        },        {123.45,        6.06400        },        {123.50,        6.19200        },        {123.55,        6.06400        },        {123.59,        5.93599        },        {123.65,        6.19200        },        {123.70,        6.57599        },        {123.75,        6.83199        },        {123.80,        6.57599        },        {123.84,        6.44800        },        {123.90,        6.32000        },        {123.95,        6.32000        },        {124.00,        6.32000        },        {124.05,        6.32000        },        {124.09,        6.19200        },        {124.15,        6.32000        },        {124.20,        6.19200        },        {124.25,        6.32000        },        {124.30,        6.19200        },        {124.34,        6.06400        },        {124.40,        5.93599        },        {124.45,        5.80799        },        {124.50,        5.42400        },        {124.55,        4.78399        },        {124.59,        4.27200        },        {124.65,        4.27200        },        {124.70,        4.40000        },        {124.75,        4.52799        },        {124.80,        4.14400        },        {124.84,        3.75999        },        {124.90,        3.50400        },        {124.95,        3.37599        },        {125.00,        3.37599        },        {125.05,        3.12000        },        {125.09,        2.48000        },        {125.15,        1.96800        },        {125.20,        1.58400        },        {125.25,        1.07200        },        {125.30,       0.815999        },        {125.34,       0.431999        },        {125.40,       0.176000        },        {125.45,      -8.000003E-002   },        {125.50,      -0.207999        },        {125.55,      -0.719999        },        {125.59,       -1.61600        },        {125.65,       -2.38399        },        {125.70,       -3.15200        },        {125.75,       -4.04800        },        {125.80,       -4.94400        },        {125.84,       -5.58399        },        {125.90,       -5.96800        },        {125.95,       -6.35200        },        {126.00,       -6.60799        },        {126.05,       -6.86399        },        {126.09,       -7.88799        },        {126.15,       -8.91200        },        {126.20,       -9.67999        },        {126.25,       -9.80800        },        {126.30,       -10.1920        },        {126.34,       -10.8320        },        {126.40,       -11.6000        },        {126.45,       -12.6240        },        {126.50,       -13.6480        },        {126.55,       -15.1839        },        {126.59,       -17.7440        },        {126.65,       -19.6640        },        {126.70,       -21.3279        },        {126.75,       -22.6080        },        {126.80,       -23.8880        },        {126.84,       -24.9119        },        {126.90,       -25.8080        },        {126.95,       -26.4480        },        {127.00,       -26.9600        },        {127.05,       -27.0880        },        {127.09,       -27.6000        },        {127.15,       -28.7519        },        {127.20,       -29.6480        },        {127.25,       -30.2880        },        {127.30,       -31.3120        },        {127.34,       -32.3359        },        {127.40,       -32.8479        },        {127.45,       -33.6160        },        {127.50,       -34.6400        },        {127.55,       -36.1760        },        {127.59,       -37.8400        },        {127.65,       -39.3759        },        {127.70,       -40.6559        },        {127.75,       -41.9360        },        {127.80,       -42.0640        },        {127.84,       -42.1920        },        {127.90,       -42.0640        },        {127.95,       -42.1920        },        {128.00,       -42.4480        },        {128.05,       -42.5760        },        {128.09,       -42.7040        },        {128.15,       -42.8320        },        {128.19,       -43.0880        },        {128.25,       -43.6000        },        {128.30,       -44.3680        },        {128.34,       -45.0080        },        {128.40,       -45.6480        },        {128.44,       -45.9040        },        {128.50,       -46.0319        },        {128.55,       -46.0319        },        {128.59,       -46.2879        },        {128.65,       -46.7999        },        {128.69,       -47.1839        },        {128.75,       -47.5679        },        {128.80,       -47.6959        },        {128.84,       -47.9519        },        {128.90,       -47.8239        },        {128.94,       -47.6959        },        {129.00,       -47.4399        },        {129.05,       -47.1839        },        {129.09,       -46.9279        },        {129.15,       -46.6719        },        {129.19,       -46.6719        },        {129.25,       -46.7999        },        {129.30,       -46.5439        },        {129.34,       -46.4159        },        {129.40,       -46.2879        },        {129.44,       -45.7760        },        {129.50,       -45.3920        },        {129.55,       -45.0080        },        {129.59,       -44.2400        },        {129.65,       -43.9840        },        {129.69,       -43.4720        },        {129.75,       -42.9600        },        {129.80,       -42.7040        },        {129.84,       -42.3200        },        {129.90,       -42.0640        },        {129.94,       -41.5520        },        {130.00,       -40.7839        }}


Is it possible to interact with an external program's command-line interface?

I am performing a calculation in _Mathematica_ which relies on calls to an external program that acts as a black box for calculating a function $f$, and I would like to know if it is possible for Mathematica to interact with a command-line interface that asks for user input. At the moment I am writing the arguments to my function $f$ in some external file `inputFile.txt`, and then running the external executable using one of the Run-related syntaxes:               inputstream=OpenRead["! ./external-program.x < inputFile.txt"]     ReadList[inputstream]      For the record, I'm running Mathematica 9 on Ubuntu 12.04. While this is a perfectly OK way to do things, it does mean I need to write to a file, have `external-program` read it, and then delete the file. For a long calculation with many such calls, it is overhead that I'd like to avoid. My external program does allow for command-line interaction, at least with a human user on a terminal, and this does not require piping in an already- written file. In practice, you run               ./external-program.x      on a command line, and you are then required to input the multiple arguments and press `Enter` after them. **Is it possible to automate this sort of behaviour from within _Mathematica_?**


Solution of numerical vector equation

Suppose I have a vector equation:               Y'[t]==rhs[Y[t]]       and               Y[0]==ConstantArray[0,n]      where "rhs[Y[t]]" is a black box function which numerically calculates a N-length vector given a N-length vector Y[t]. How can I solve such an equation in "NDSolve" ? Update: Say my rhs is :               rhs[{x_?NumberQ,y_?NumberQ]={x,y}


FeynArts not working properly

So I have installed all FeynArts folders (from 3.5 to 3.7) with FeynCalc 8.0.1., and none of it is working properly :\ First I load the path to specific FeynArts package (3.5 for instance), then, by:               << HighEnergyPhysics`FeynCalc`;      I load FeynCalc, and he says               Loading FeynCalc from C:\Users\*****\AppData\Roaming\Mathematica\Applications\HighEnergyPhysics     FeynCalc 8.1.0 For help, type ?FeynCalc, open FeynCalcRef8.nb or visit www.feyncalc.org     Loading FeynArts, see www.feynarts.de for documentation     FeynArts 3.5 patched for use with FeynCalc      So everything seems nice, right? Wrong! I even load FeynArts package, and no errors. But when I want to initialize the proper model I get:               In[9]:= InitializeModel[SM]          During evaluation of In[9]:=           During evaluation of In[9]:= loading generic model file C:\Users\*****\AppData\Roaming\Mathematica\Applications\HighEnergyPhysics\FeynArts-3.5\Models\Lorentz.gen          During evaluation of In[9]:= TagSetDelayed::tagnf: Tag FourVector not found in \!     \(TraditionalForm\`\(-\(TraditionalForm\`mom_\)\^\(TraditionalForm\`\(TraditionalForm\`\(Pattern[\(\(mu___, _\)\)]\)\)\)\)\)     . >>          During evaluation of In[9]:= Pattern::patvar: First element in pattern Pattern[b_,_] is not a valid pattern name. >>          During evaluation of In[9]:= Pattern::patvar: First element in pattern Pattern[b_,_] is not a valid pattern name. >>          Out[9]= $Aborted      And I can't do anything! I can plot topology, but I can't insert fields. I've been doing everything by the book :\ What seems to be wrong? :\


Programming Multipolar Expansions in Spherical Tensors

We have that a density matrix can be written in a basis of spherical tensors: $\rho =\sum _{K=0}^S\sum_{q=-K}^K \rho _{\text{Kq}}^{(S)} T_{\text{Kq}}^{(S)}$ for example for a 3x3 matrix, $S=1$, dimension of the matrix is $2S+1$, I will drop superscript (S) for simplicity $\rho =\rho_{00}T_{00}+\rho_{1-1}T_{1-1}+\rho_{10}T_{10}+\rho_{11}T_{11}+\rho_{2-2}T_{2-2}+\rho_{2-1}T_{2-1}+\rho_{20}T_{20}+\rho_{21}T_{21}+\rho_{21}T_{21}$ Now, I have a command that gives me the matrix representation of $T_{Kq}^{(S)}$ I want to know now how to make a program so that if you give as an imput the parameter S, they write you the resultant matrix dependent of the coefficients $\rho_{Kq}$. Also as $\rho_{Kq}=(-1)^q\rho_{Kq}^*$, this should also be implemented so that the final matrix depends on fewer parameters. **Edit:** Answering to Hector below. I have not programmed the command which gives $T_{Kq}^{(S)}$, to say the truth I have not made code in Mathematica never, and hardly ever elsewhere. Well command is sphtens[K,q,S] I've been thinking about the algorithm to get the desired result. To me the step are the following:   * Input the value of S   * Create a square matrix of zeros of dimension 2S+1. Call it $\rho$ for example.   * Create two loops one for the K and another one for the q for $K=0$ till $2S$ for $q=-K$ till $K$ if $q\geq 0$ $\rho=\rho + \rho_{Kq}$ \times sphtens[K,q,S] if not $\rho=\rho + (-1)^q\rho_{Kq}^* \times$ sphtens[K,q,S] end for end for Basically what I don't know is to write this in Wolfram language


import complete date string to mathematica

Based on an example from here I try to parse dates from a table including the time, but it fails. This is the modified example:               Export["test.dat", {{"2010-05-19 22:23:43", 17}, {"2010-05-20 22:23:43", 20}, {"2010-05-21 22:23:43", 19}}, "FieldSeparators" -> " "];          Import["test.dat", "Table", "DateStringFormat" -> {"Year", "-", "Month", "-", "Day", " ", "Hour", ":", "Minute", ":", "Second"}]      Does anyone understand why it doesn't work in analogy to the other case? thanks


Multiple simultaneous events in EventLocator method for NDSolve

I'm using NDSolve to integrate a system of ODEs, and EventLocator to stop the integration when it leaves a certain region in phase space. This works perfectly as it should. However, I've also added in another couple of events to Sow some bits of data (e.g, the locations of extrema of some variable). Almost all the time, this works perfectly as well. However, occasionally, both sorts of event occur simultaneously (or in the same integration step). In this case, it seems that only one of the event actions is evaluated. In particular, the integration isn't stopped when it should be. The documentation doesn't seem to mention this situation at all, so it's hard to know if this is a bug, or whether there's a good way round it. Can anyone throw some light on this? Thanks! Schematic form of the code:               NDSolve[         {ODEs for r and v}, {r, v}, {s, s0, \[Infinity]},                               Method -> {"EventLocator",  "Event" :> {edgeOfPhaseSpace,anotherEvent},            "EventAction" :> {Throw[{something;}, "StopIntegration"],                              doSomething;}}     ]      EDIT: The actual code I'm interested in is pretty complicated, with lots of spurious detail, so I've made a simpler model which illustrates concretely what I'm on about:               solution[theta_] := Module[{sol, , tf, tx = 0},       sol = First@NDSolve[          {x''[t] == 0, y''[t] == -1, x[0] == 0, y[0] == 0,            x'[0] == Cos[theta], y'[0] == Sin[theta]}, {x, y}, {t,            0, \[Infinity]},          Method -> {"EventLocator", "Event" :> {y[t], x[t] - 1/2},            "EventAction" :> {Throw[tf = t;, "StopIntegration"], tx = t;}            }, MaxStepSize -> 0.1];       sol~Join~{stopTime -> tf, xTime -> tx}]      This solves for a particle moving under gravity, sent at an angle theta, and stops the integration when the particle hits y=0 again. It also returns data about the time when the particle hits x=1/2. It works as expected most of the time. The exception is when the particle hits x=1/2 before it hits y=0, but in the same time step (e.g. theta=1.308). In this case the integration doesn't get stopped, but runs until max steps is reached.


See Local Variable at breakpoint within MODULE?

Within the debugger, can we watch local variables within a Module? As the screenshot shows, the “i” only display its global value (12) upon a message breakpoint. Is there a way to show its local value? ![enter image description here](http://i.stack.imgur.com/MeC8f.jpg)               Clear[i];      i = 12; f[] := Module[{i}, For[i = 1, i < 10, i++, Print[i]; Print[":\t"]; Print[i/0]]; ]; f[] Jimmy


Dynamic lists as function arguments

Suppose I have a function that requires a list is as input. I.e.               f[list_]:=DoSomethingWithList      Now, if I pass a variable as Dynamic like this               pts={{0.1,0.1} , {0.5,0.1}, {0.1, 0.5}};     f[Dynamic[pts]]      everything works as expected as long as I don't use parts of the list. If I use a part of a list then things no longer work as expected ( by me ). Another example               g[point_] := Slider2D[point]     p = {.1, .1}     g[Dynamic[p]]     Dynamic[p]      that works as expected, and this one               g[point_] := Slider[point[[1]]]     p = {.1, .1}     g[Dynamic[p]]     Dynamic[p]      that does not. **Question: What behaviour of Dynamic explains the above?**


Is it possible to make the Button execute two or more actions?

According to the help: > Button[label,action] Is it possible to make the button execute two actions?


NotePad++ User defined language

I know there is a xml file with language for Mathematica notebook (nb or m files). The link is http://sourceforge.net/apps/mediawiki/notepad- plus/?title=User_Defined_Language_Files Now I want a xml file to format not the code of nb file but what the user see when he opens the nb file in mathematica. Any idea before I customize this language??? Regards,


Finding the number of solutions to a diophantine equation

I want to count total number of the natural solutions (different from 0) of the equation $2x + 3y + z = 100$, but don't know how. How can I calculate it using _Mathematica_? I tried:               Solve[{2*x + 3*y + z == 100, x > 0, y > 0, z > 0}, {x, y, z}, Integers]


How to plot a "pressed" hemisphere

What I'd need is to draw an hemisphere of given radius but then it should have a reduced height. I don't mean a section of an hemisphere, I mean that the hemisphere should be pressed/flattened...so that it keeps on having the given radius but it is much less high, more flattened. I can't fine the right values or the relations between theta and phi to correctly use this formula:               SphericalPlot3D[5, {\[Theta], 0, Pi/5}, {\[Phi], 0, 2 Pi}, AspectRatio -> Automatic]      Any help? Remember, I don't want the radius/diameter to change, it only must be flattened.


How to obtain xyz-axes of same length?

> **Possible Duplicate:**   >  Controlling the 2D $x–y$ aspect ratio of a 3D plot I am plotting 1000 points in a 3-dimensional cartesian coordinate system, the plotting range for the x, y, z axes is set to {-1,1} respectively. Mathematica code:               points1 = RandomReal[{-1, 1}, {500, 3}];     points2 = RandomReal[{-1, 1}, {500, 3}];          sphere = Graphics3D[{Opacity[0.1], Sphere[{0, 0, 0}]}];     plot1 = ListPointPlot3D[points1, PlotStyle -> Green];     plot2 = ListPointPlot3D[points2, PlotStyle -> Black];     Show[{plot1, plot2, sphere}, Axes -> False,          PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}, AspectRatio -> Automatic]      ![plot](http://i.stack.imgur.com/0pxE3.png) Why does Mathematica plots axes of different lengths? Since I have given the same plotting range, I would expect and want to see a cube. How do I achieve this?


A weird thing about ListPlot3D

I plot the function f(x,y). x goes from 0 to 25 and y goes from 0 to 12. So, my plot should look elongated since the range of x is twice as long as the range of y. The problem is that, mathematica rescales the size of the axes, so that I see a square plot eventhough I see x->[0,25] and y->[0,12]. This is what I do: ListPlot3D[Abs[list], ColorFunction -> "Rainbow", AxesLabel -> {xx, yy, f(xx,yy)}, PlotRange -> All] Does anybody know how could I see an elongated plot? Thanks alot!


Taking class notes with a Mathematica Notebook

Dose anyone take notes in a technical class using a _Mathematica_ notebook? If anyone does, how does it compare to paper and are there useful commands? I have a hard time remembering ctrl/alt/esc commands. I normally type faster than I write but typing equations is a pain. Especially considering that _Mathematica_ (without Wolfram|Alpha) doesn't show the steps to a solution, which I sometimes want to copy down.


About the wrong evaluation of an integral

Here is an integral I've been studying in my research and I've just realized that Mathematica $8.0$ is unable to correctly compute it. I have 2 simple questions to ask: $1)$. Is my code below correct?                             Integrate[x^(a - 1)/(1 - x) - c x^(b - 1)/(1 - x^c), {x, 0, 1}]      $2)$. Are the newer Mathematica versions able to correctly compute it (how about W|A)? Please do not provide with mathematical solutions, I like to attend this part on my own.


Dynamically link cell content in Mathematica?

Is it possible to dynamically link the content of two cells? For example, can I set up a Notebook with two text cells that display the same value, and if the user types in one the other updates, etc.? I am familiar with Mathematica's dynamic functionality and at least the key concepts of the FrontEnd, and it seems like I should be able to assign a dynamic symbol to certain parts of a cell and just use that in an expression elsewhere, but I can't figure out how to programmatically access a cell's current content. The best I have been able to do is get a CellObject using `Cells[]`, e.g. where the first cell is a text cell containing "This is a test!", `Cells[][[1]]` gives               Cell[BoxData[     TemplateBox[{6849,"6849","\"Text\""},     "CellObject"]], "Output",     CellChangeTimes->{{3.5653627710636687`*^9, 3.5653627797706504`*^9}, {     3.5653628101959224`*^9, 3.5653628192779245`*^9}, 3.5653630492614017`*^9}]      but this doesn't include the cell's content.


Why is this semicolon in red?

I have a piece of code that works well, but when I put a semicolon after a plotting statement, the semicolon appears in red. What's the error? ![](http://i.stack.imgur.com/WXRUM.jpg)


Make mathematica treat $e_i^2$ as numeric

With `NumericQ[symbol] = True`, I can declare that a symbol is numeric. I want the expressions matching: $$e_{\text{i$\\_$}?\text{IntegerQ}}^2$$ to be treated as numerical expressions too.               e /: NumericQ[Subscript[e, i_?IntegerQ]^2] = True;      doesn't work. Also, I can't use `NumericFunction` because it's too restrictive. Is there something like `NumericPattern`?


How to speed up this TDSE code?

I'm trying to build a 1D time-dependent Schrodinger equation solver, using the Crank-Nicholson method. And I think the code is kind of working now, but the speed is still slow for me. Here is the code that calculates the wave function $\psi(x,t)$ at certain time given initial wave function $\psi(x,0)$ and a position dependent potential $V(x)$.               TDSE1[V_Function, Ct0_, {xmin_, xmax_}, {tmin_, tmax_, dt_}] :=       Module[{I0, Tmtx, Vmtx, Hmtx, Ct, Cls, dx, tls, xls,         N0Grid = Length@Ct0},       dx = (xmax - xmin)/(N0Grid - 1);       xls = Range[xmin, xmax, dx];       tls = Range[tmin + 0.5 dt, tmax, dt];       Tmtx = -(1/(2 (dx)^2))           SparseArray[{{i_, i_} -> -2, {i_, j_} /; Abs[i - j] == 1 -> 1}, {N0Grid, N0Grid}];(* kinetic energy *)       I0 = SparseArray[{{i_, i_} -> 1.}, {N0Grid, N0Grid}]; (*identity matrix*)       Ct = Ct0;       Vmtx = SparseArray[Band[{1, 1}] -> V /@ xls];(*potential energy*)       Hmtx = Tmtx + Vmtx;(*total Hamiltonian*)       Cls = Table[         Ct = LinearSolve[(I0 + I/2. (Hmtx)*dt), (I0 - I/2. (Hmtx)*dt).Ct]         , {t, tls}];       Cls       ]      and here is an example of calculating a wave function using this solver               Ct0 = Array[Exp[-#^2] &, 400, {-10, 10}] // N;(*initial wave function*)     Cls1 = TDSE1[Function[{x}, 0.5 x^2], Ct0, {-10, 10}, {0., 50., 0.01}]; // AbsoluteTiming     (*{1.329230,Null}*)          ListPlot[Re[Cls1[[1 ;; 1000 ;; 100]]], Joined -> True, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/9PUbp.jpg) And I'm pretty satisfied with this speed. However, I'm more interested in a time-dependent potential, ie, $V=V(x,t)$, than a time independent one. So I changed the code a little bit so that at every time step, it recalculates the potential `Vmtx` at that time.               TDSE2[V_Function, Ct0_, {xmin_, xmax_}, {tmin_, tmax_, dt_}] :=       Module[{I0, Tmtx, Vmtx, Hmtx, Ct, Cls, dx, tls, xls,         N0Grid = Length@Ct0},       dx = (xmax - xmin)/(N0Grid - 1);       xls = Range[xmin, xmax, dx];       tls = Range[tmin + 0.5 dt, tmax, dt];       Tmtx = -(1/(2 (dx)^2))           SparseArray[{{i_, i_} -> -2, {i_, j_} /; Abs[i - j] == 1 -> 1}, {N0Grid, N0Grid}];        I0 = SparseArray[{{i_, i_} -> 1.}, {N0Grid, N0Grid}];       Ct = Ct0;       Cls = Table[         Vmtx = SparseArray[Band[{1, 1}] -> (V[t] /@ xls)];         Hmtx = Tmtx + Vmtx;         Ct = LinearSolve[(I0 + I/2. (Hmtx)*dt), (I0 - I/2. (Hmtx)*dt).Ct]         , {t, tls}];       Cls       ]      and the function call is also changed slitly               Cls2 = TDSE2[Function[{t}, Function[{x}, 0.5 x^2]], Ct0, {-10, 10}, {0., 50., 0.01}]; // AbsoluteTiming     (*{9.446716, Null}*)      but now it is about **7X slower** than before! I tried to compile the function inside the module, replacing the `Vmtx` line by something like               Vmtx = SparseArray[Band[{1, 1}] -> (VCpf[t, xls])];      where VCpf is a compiled function defined by               VCpf = Compile[{{t, _Real}, {x, _Real}}, V[t][x], RuntimeAttributes -> {Listable}]      and that makes the problem even worse, with about **20X** slower than `TDSE1`. **So my question is, is it possible to speed up`TDSE2` to get about the same speed as `TDSE1` or even faster?**


FrameTicks and GridLines in DateListPlot

I would like to know what is the best way to configure one `GridLine` for the hour in `LightGray` and another for the days in `Gray`. In my tests, the `FrameTicks` are superposed by the GridLines and I don't know how to control the color. The data label should appear just for days. Here is my attempt that I consider very clumsy.               data={#,RandomVariate[NormalDistribution[0,1]]}&/@RandomReal[{3564979299,3565355902},1000];          DateListPlot[data        ,AspectRatio->0.2        ,DateTicksFormat->{"Day","/","Month"}        ,GridLines->{{#,LightGray}&/@DateRange[{2012,12,12},{2012,12,31},"Hour"],None}        ,FrameTicks->{Automatic,{DateRange[{2012,12,12},{2012,12,31},"Day"],None}}        ,Epilog->{Gray,Line[{{#,Min@data[[All,2]]},{#,Max@data[[All,2]]}}]&/@AbsoluteTime/@DateRange[{2012,12,12},{2012,12,31},"Day"]}     ]      ![enter image description here](http://i.stack.imgur.com/cMXPW.png) I don't like to use `Epilog` for that. It would be nice if I could have subticks between the days ticks too, one subtick for each hour, with no label.


How to avoid page break appearing between the table title and the table in Mathematica?

I'm wring a thesis which has quite amount of tables. When the thesis gets printed, Mathematica often breaks pages between the table title and table. I would like to keep the title and table in the same page. How can I do so by editing the Stylesheet? Details regarding this problem: First I chosen the initial style sheet to be Artical -> Preprint. Then I selected "TableTitle" for the cell style of the title, and self-defined "TableText" for the cell style of the table. The self- defined "TableText" basically inherits the definition of the existing cell style "Text" as follows:               Cell[StyleData["TableText", StyleDefinitions -> StyleData["Text"]], TextAlignment->Center,      MenuSortingValue->1911,      FontSize->12]      The problem is even if I group the cells of titles and tables, Mathematica still often breaks the page between the cell "TableTitle" and the cell "TableText" when the Screen Environment is in Printout and I choose Printing Settings -> Show Page Breaks. I wouldn't like to add the page break lines manually. I'm wondering how to tell Mathematica not to add the page break lines between the cells "TableTitle" and the cells "TableText". Is it possible to do so by adding something to the StyleData of "TableTitle" in the environment of "Printout":               Cell[StyleData["TableTitle", "Printout"],      PageWidth->PaperWidth,      Hyphenation->False,      FontSize->12]      I tried to add `PageBreakBelow -> False` but it did not work.


How can I avoid a scoping problem when differentiating?

I simplify my real problem as follows: I define a rule function as               Clear[rule];      rule[i_] := tt -> i;      the real rule function is not this simple. I define a matrix function as               Clear[hh];     hh[x_, y_, i_] := {{tt, x}, {y, 1}}/. rule[i];      I want to define a function `hhpar` that will differentiate `hh` with respect to `x`, so I write               Clear[hhpar];     hhpar[x_, y_, i_] := D[hh[x, y, i], x];      This doesn't work and I know why. But I still can't figure out a way to write a proper `hhpar`. How would I do that?


How to format dynamic InputField value using NumberForm?

Background: I want all numbers in `InputField`'s displayed as `NumberForm[num,2]`; Now, consider the following the snippet of code:                latsy = 1.1;      latparshx = 32;      piet = NumberForm[latsy*Tan[latparshx*Pi/180], 2];      InputField[Dynamic[piet], FieldSize -> 3]      This code produces an inputfield with a number between double quotes, which is not what I expected. I basically want 0.69 displayed. **Question: How can I ( what is the best way to ) control the display format of a number in an InputField ?** EDIT: The InputField resizes itself on the Panel it is positioned on and thus messes up the other GUI elements.


Correct way to compare arrays and do conditional evaluations

I would like to compare two arrays a=: ![enter image description here](http://i.stack.imgur.com/BR6jR.png) and b= ![enter image description here](http://i.stack.imgur.com/DehGc.png) and get: ![enter image description here](http://i.stack.imgur.com/9S737.png) using:               (b/.(b_?Positive->a+b))//MatrixForm       but this doesn't seem to work? Can anyone tell me what I am doing wrong? Basically the conditional only updates b to be sum of a and b only when a non zero is detected in b or else it should do nothing, but can't work out why it is not summing. Or must I first flatten it?


Applying an ArrayPlot as a texture to the surface of a cylinder

I would like to apply a matrix plot to the surface of a 3D cylinder. The matrix plot is the output from a custom cellular-automata, and it would be nice to see the lefthand side of the plot connected to the righthand side. ### Edit This is the solution I ended up using:               mrt =       ArrayPlot[CellularAutomaton[30, RandomInteger[{0, 1}, 100], 30],         Frame -> False,         ImagePadding -> 0,         PlotRangePadding -> 0];     ParametricPlot3D[{Sin[t]/2Pi, Cos[t]/2Pi,u},{t,0,2Pi},{u,0,2},       Boxed -> False,       Axes -> False,       PerformanceGoal -> "Quality",       ImageSize -> {300, 300},       Lighting -> "Neutral",       PlotStyle -> Texture[mrt],       Mesh -> None,       ViewPoint -> {0, 3, 1}]      ![enter image description here](http://i.stack.imgur.com/IKy4B.png)


Plotting a multivariable function

m[x_, y_] :=       0.9*Exp[-((x - 1)^2 + (y - 1)^2)] +        0.5 Exp[-(3^2 ((x - 2.5)^2 + (y - 1.5)^2))]      I'm trying to create a 3d plot for the function above. I tried `Plot3D`, but all i got was a blank. my plot attempt : `Plot3D[m, {x, -1, 1}, {y, -1, 1}]`


Retrieve values of InterpolatingFunction

While analyzing a large system of ODE's, I defined a particular ratio `p`, which contains some variables that are represented by `InterpolatingFunction`s by `NDSolve`.               p = Sum[(c[i][t] + ac[i][t] + ct[i][t] + bmct[i][t] +       ambmct[i][t]) i, {i, 0, 6}]/(6*0.58)      To plot `p`, I put `p` with a transformation rule inside of a `Plot[]`, like so:               Plot[p/.tsol,{t, 0, timeduration}]      where `tsol` stores `NDSolve`'s output. Plotting of `p` works fine and yields a nicely oscillating plot. How do I extract values of this new InterpolatingFunction `p` for certain time points `t`? Ironically enough, I do manage to calculate the derivative of this function, along with the points where the slope is 0. This more trivial looking problem, however, is giving me headaches... Thanks!!


How do I combine the data from two tables according to a rule of my own devising?

I have two matrices a = m x 5 and b =m x 5 (m is large, say 1,000) which are already sorted as below: ![enter image description here](http://i.stack.imgur.com/BRXlm.png) How to generate a new matrix c = m x 5 which consists: Column 1: exact replica of Column 1 of matrix a.   Column 2: Depends on non-zero elements of b as shown   so that it is adjusted by it's left hand side row of a - b + present row.   Zeros are not evaluated. (example: 3.7107 - 2.96856 + 23.2988 = 24.0409 ) Columns 3 4 and 5, not sure yet so maybe start off with a SparseArray of m x 5? But most likely to be an extension of Column 2. i.e. Column 3,4 and 5 will be also adjusted once I have worked out how they need to adjusted by. EDITED 31/12/2012 03:25am UK time: Solution from @halirutan is partially correct because my input matrix a: ![enter image description here](http://i.stack.imgur.com/q0Xli.png) and matrix b: ![enter image description here](http://i.stack.imgur.com/qBEU2.png) gives matrix c: ![enter image description here](http://i.stack.imgur.com/4yvYy.png) Not sure how to do conditional check for column b to be non-zero before evaluating?


MapAt and generic Functions on Associations and Datasets

These are distinct but related questions about mapping functions to Associations and Datasets. Given:               assoc = <| a -> 1, b -> 2, c -> 3|>       And               data =       Dataset@{<| a -> 1, b -> 2, c -> 3|> , <|a -> 4, b -> 5, c -> 6|>}      Re MapAt:               MapAt[Framed, Key[b]][assoc]       ![enter image description here](http://i.stack.imgur.com/WMKvE.jpg) Although Dataset is not explicitly mentioned in the doc page for MapAt, it's supposed to apply to generic expressions. However:               MapAt[Framed, Key[b]][data]      ![enter image description here](http://i.stack.imgur.com/cvR8u.png) Next, consider mapping over a named `Key` with this syntax:               data[All, {Key[b] -> Framed}] // Normal      ![enter image description here](http://i.stack.imgur.com/aOdkY.png) Why don't the following variations work on `Dataset`?               data[All, Key[b] -> Framed] // Normal      ![enter image description here](http://i.stack.imgur.com/wpseG.png)               data[All, Key[b] -> Framed[#] &] // Normal      ![enter image description here](http://i.stack.imgur.com/3H6Em.png) Finally, back to Association:               assoc[Key[b] -> Framed] // Normal      ![enter image description here](http://i.stack.imgur.com/JvPh5.png)


How to export 3D plot, without losing the specified view of rotation?

Sorry I am not sure if I got anything wrong with this version of Mathematica and Mac OS X i am running. But every time I export a 3D graph, to png or tiff, I lost the view angle, view vector viewpoint information immediately. To let you know what I meant, here is a simple code: I typed:               x = RevolutionPlot3D[Sqrt[((t/5)^2 - 1)*2], {t, 5, 20}]      And I got a plot               out[1]=       ![Original Plot](http://i.stack.imgur.com/Lv5O3.png) Then I manually rotate the plot so that it looks better, for example like this: ![Manually rotated view](http://i.stack.imgur.com/S5gyA.png) Ok, now, I used Export to export it to png:               Export["test.png", %];      What I got is pathetically, the un-rotated png plot!: ![Exported png](http://i.stack.imgur.com/2r6GR.png) This is driving me crazy and dead.. I also tried to set Viewpoint and view vector, stuff to the code, it doesn't work for me either. I also tried Export["test.png",x] too, no luck. I understand I could easily right-click to save, But I need a background-none option to make the graph transparent.. Can any one confirm (this bug?) or i am doing something stupidly wrong? I checked the documentation and googled for 1 hour, nothing found. So the question is, how can I export the graph as it is shown on the notebook (if I can not, then what's the point of allowing us to rotate it..)


Finding the maximum of a gradient vector

Im trying to find the maximum of my gradient vector G[x,y], I've tried several options including FindMaximumValue, FindMaximum etc. but i couldn't find it. The full function is shown below, any help would be greatly appreciated               G[x_,y_]:= {-5.4 E^(-2.25 ((-4 + x)^2 + (-2.5 + y)^2)) (-4 + x) -        6.4 E^(-4 ((-3.5 + x)^2 + (-1.5 + y)^2)) (-3.5 + x) -        8 E^(-4 ((-3 + x)^2 + (-3.5 + y)^2)) (-3 + x) -        9. E^(-9 ((-2.5 + x)^2 + (-1.5 + y)^2)) (-2.5 + x) -        5.5125 E^(-3.0625 ((-2 + x)^2 + (-3 + y)^2)) (-2 + x) -        1.8 E^(-(-1 + x)^2 - (-1 + y)^2) (-1 + x) -        30. E^(-25 ((-0.75 + x)^2 + (-2 + y)^2)) (-0.75 +           x), -8 E^(-4 ((-3 + x)^2 + (-3.5 + y)^2)) (-3.5 + y) -        5.5125 E^(-3.0625 ((-2 + x)^2 + (-3 + y)^2)) (-3 + y) -        5.4 E^(-2.25 ((-4 + x)^2 + (-2.5 + y)^2)) (-2.5 + y) -        30. E^(-25 ((-0.75 + x)^2 + (-2 + y)^2)) (-2 + y) -        6.4 E^(-4 ((-3.5 + x)^2 + (-1.5 + y)^2)) (-1.5 + y) -        9. E^(-9 ((-2.5 + x)^2 + (-1.5 + y)^2)) (-1.5 + y) -        1.8 E^(-(-1 + x)^2 - (-1 + y)^2) (-1 + y)}


How can I convert a formatted text cell to latex code?

I have a formatted text cell, I want to export it as latex. How can I do that? Since copy as LaTeX doesn't work, I thought of pasting it into a string and exporting, but it's a no go:                ExportString["Let M be a TM and let \!\(\*FormBox[\(A \[SubsetEqual] \     \*SuperscriptBox[\({0, 1}\), \(*\)]\),     TraditionalForm]\). We say that \!\(\*FormBox[\(M decides A\),     TraditionalForm]\) if \!\(\*FormBox[\(\[ForAll] \\\ x \[Element] \     \*SuperscriptBox[\({0, 1}\), \(*\)]\),     TraditionalForm]\), \!\(\*FormBox[\(x \[Element] A\\\  \[Implies] \\\ \     M(x) = 1\),     TraditionalForm]\), \!\(\*FormBox[\(x \[NotElement] A\\\  \[Implies] \     M(x) = 0. \),     TraditionalForm]\) We say that  \!\(\*FormBox[\(A \[SubsetEqual] \     \*SuperscriptBox[\({0, 1}\), \(*\)]\),     TraditionalForm]\) is \!\(\*     StyleBox[\"decidable\",\nFontWeight->\"Bold\"]\) if there is a TM \     that accepts it.", "TeX"]


Docked Cell lesson chooser

I have a question about creating a docked cell that will let me choose files. This is just as much a "design" question as a Mathematica question. I'm a math teacher and I want to bundle a bunch of Mathematica lesson content into a unit. I have a whole bunch of files that make up a unit. We'll call them simply Lesson1.cdf, Lesson2.cdf, Lesson3.cdf etc. We'll say there are 10 of them. I wanted to build the unit in smaller pieces , since it seems logical not to have a huge amount of info in one file. So, create in pieces. I can see how to use ActionMenu to do this... at least it's one way, not saying it's the best way!!               b1 = ActionMenu["Open a lesson",        {"Lesson 1" :>          NotebookOpen[FileNameJoin[{NotebookDirectory[], "lesson1.cdf"}]],        "Lesson 2" :>          NotebookOpen[          FileNameJoin[{NotebookDirectory[], "lesson2.cdf"}]]},       Appearance -> "PopupMenu"       ]      It works... I then create a docked cell in the Notebook...                   SetOptions[SelectedNotebook[],        DockedCells -> Cell[BoxData[ToBoxes[b1]], "DockedCell"]];      This too works... so far so good! So , sadly, that's as far as my knowledge will take me. I tried using hyperlinks to open the lesson notebooks from a main document, but it seemed really cluttered , having more than one notebook open on screen. This method seems potentially better, but can I have it close the "calling" notebook when it opens the selected lesson? Would there be an easy way to write this docked cell to all the other lessons? (Yes, I think I could do that by just getting a list of lesson files and setting their options for docked cells) Finally, this way of opening the notebooks generates the "unsafe" content warning. That will be bad since then every lesson notebook will have this issue. Way over my depth here, but hoping someone can give some "design" advice for packaging up a bunch of notebooks into a nice unit, and being able to get from one to another easily. My students do not have Mathematica and are using CDFPlayer to view my lessons. It's interesting that bundling a "NotebookOpen" inside a Button does NOT trigger the warning, which is a big thing. So, buttons aren't as elegant, but they do work and allow students to move between lessons with no issues. ![Current Progress with buttons](http://i.stack.imgur.com/z2mpR.png) But I know that can't be right... I've probably managed to add that path to my TrustedDirectories or something... it's a real nuisance not to be able to do this in a straightforward way...


Nested NIntegrate

Suppose that we have the given simple integral expression $$ \int_{-5}^{5} x \int_{-\infty}^{x} e^{\int_{0}^{z} -y dy} dz dx $$ Writing this out in _Mathematica_ we obtain:               Integrate[x Integrate[Exp[Integrate[-y, {y, 0, z}]], {z, -\[Infinity], x}], {x, -5., 5}]     30.0795      ### Question: Is it possible to do a numerical integration on this expression by using `NIntegrate`? A very naive attempt gives us the following errors:               NIntegrate[x NIntegrate[Exp[NIntegrate[-y, {y, 0, z}]], {z, -\[Infinity], x}], {x, -5, 5}]      > NIntegrate::nlim: y = z is not a valid limit of integration Notice that we want everything to be a numerical integration, this includes the inner integrals. The problem is that one of the `NIntegrate`s is an argument to the exponential function and this does not allow us to write the double integral with only one `NIntegrate` as mentioned in here ### Motivation I'm trying to evaluate an expression that is too complicated for Mathematica to do symbolically and it is composed on integrals of the kind mentioned above.


Plotting a region with thin cusps in high-definition via RegionPlot

I want a high-definition picture the real solutions $(s_1,s_2,s_3)$ of the system of inequalities $3 s_1^2 < (s_2 - s_3)^2 + 2 s_1(s_2 + s_3)\\\ 3 s_2^2 < (s_1 - s_3)^2 + 2 s_2(s_1 + s_3)\\\ 3 s_3^2 < (s_1 - s_2)^2 + 2 s_3(s_1 + s_2)$ such that $s_1+s_2+s_3=1$ and $s_1>0$, $s_2>0$, $s_3>0$. I would also like to emphasize the solutions for which at least two $s_i$'s are equal. For this, I wrote the following code:               s1 = r/Sqrt[2] - s/Sqrt[6] + 1/3;(*Parametrization of plane s1+s2+s3=1 *)     s2 = -r/Sqrt[2] - s/Sqrt[6] + 1/3;     s3 = 2 s/Sqrt[6] + 1/3;          reg = RegionPlot[6 r (Sqrt[2] + 3 r - 4 Sqrt[3] s) < 1 + 2 Sqrt[6] s + 6 s^2 && 18 r^2 < 1 + 2 Sqrt[6] s + 6 s^2 + 6 r (Sqrt[2] - 4 Sqrt[3] s) && 4 Sqrt[6] s + 30 s^2 < 1 + 18 r^2, {r, -Sqrt[2]/2, Sqrt[2]/2}, {s, -Sqrt[6]/6, Sqrt[6]/3}, PlotStyle -> LightGray, Axes -> False, Frame -> None, PlotPoints -> 500];          boundary = Plot[{Sqrt[3] r + Sqrt[6]/3, -Sqrt[3] r + Sqrt[6]/3, -Sqrt[6]/      6}, {r, -Sqrt[6]/3, Sqrt[6]/3}, AspectRatio -> 1, AxesOrigin -> {0, 0}, Axes -> False, PlotStyle -> {{Black, Dashed}}];          line1 = Plot[{r/Sqrt[3]}, {r, -(1/(10 Sqrt[2])), 1/(2 Sqrt[2])}, AspectRatio -> 1, AxesOrigin -> {0, 0}, Axes -> False, PlotStyle -> {{Black}}];     line2 = Plot[{-(r/Sqrt[3])}, {r, -(1/(2 Sqrt[2])), 1/(10 Sqrt[2])}, AspectRatio -> 1, AxesOrigin -> {0, 0}, Axes -> False, PlotStyle -> {{Black}}];     line3 = ParametricPlot[{0,s}, {s, -(Sqrt[(2/3)]/5) - Sqrt[3/2]/5, -(Sqrt[(2/3)]/5) + Sqrt[3/2]/5}, AspectRatio -> 1, AxesOrigin -> {0, 0}, Axes -> False, PlotStyle -> {{Black}}];     pic = Show[reg, boundary, line1, line2, line3];     Export["pic.pdf", pic];      obtaining the following image: ![Image](http://i.stack.imgur.com/SZVYn.gif) The region above should have the obvious symmetries, given by rotations of $120^\circ$. However, my plot looks slightly non-symmetric, since the lower cusp seems to "stop" before the top cusps. The cusps go up to the boundary of the outer triangle, but the plots don't quite make justice to that -- unless one adds a thick boundary to the region, which I don't really like (since it is supposed to represent an _open_ set). Although raising the PlotPoints to 500 rendered it a lot better, it still looks a bit strange when it is zoomed in. I tried raising PlotPoints to more than 500, but it froze my computer and I had to forcefully restart the machine (3 attempts, ranging between 550 and 1000). I would like to know if there is a better way to make the above plot, that is, something that makes Mathematica **draw the cusps more accurately, arriving all the way to the boundary, and such that all of them look the same**. Eventually I want to export it as a PDF.


Importing an mx file into a context

Consider the following simple code which dumps the global context:               var = 5;     DumpSave["test.mx", "Global`"];      Now, in a new notebook, I would like to import var in another context. Trying               Begin["myContext`"]     << "test.mx"     End[]      does not work because var remains in the global context. Is there a solution? Thank you.


Represent more nested dataset with the same color in the PieChart

I have multiple dataset that I want to plot in PieChart, as in               PieChart[{{2, 2}, {1, 2, 4}}, ChartLayout -> "Stacked"]      Now here is the catch: I want the color of the chart to be "similar" if the corresponding data belong to the same set. In my example, the regions corresponding to `{1,2,4}` would have different shades of Blue, while the ones relative to `{2,2}` would be plotted with different intensities of Red. Finally, since the original data set is more nested than this one, it would be nice to be able to specialize such color function further I have tried with ColorFunction -> Function[x, ...] but I don't manage to have info about the originating dataset. Example or more nested data set:               {{2, 2}, {1, 2, {3,1}}}     {{2, 2}, {1, 2, {{2,1},1}}}


List manipulation, replace a value

I have the following list:               AA= {300., 150., 100., 76.8421, 64.0909, 55.567, 49.1935, 44.2262,          40.2247, 36.9355, 34.1667, 31.8138, 29.7887, 28.0087, 26.4537,          25.0612, 23.8186, 22.7059, 21.6854, 20.7663, 19.9265, 19.1519,          18.4323, 17.7739, 17.1672, 16.6007, 16.0648, 15.5605, 15.098}      If a value of AA is higher than 100, I want replace this value with a an arbitrary value, e.g. 50. Has anyone any idea how to do this?


Replacing all values in a table > $T$

I want to generate a table of Euclidean distances from the points in a list to a given point, e.g.:               Table[EuclideanDistance[MyList[[i]], c], {i, 1, Length[MyList]}]      Moreover, when `EuclideanDistance` returns a value greater than $T$, I'd like to replace that value with a given real number $R$. Is there a simple way to do this?


How to change specific values in a List

In a list `lst` I want to change all values > 255 to 255. Why is this code not working?               lst= {336, 315, 395, 337, 411, 309, 408, 338, 576, 377, 508, 386, 545, \     477, 453, 424, 425, 286, 363, 248, 298, 268, 221, 162, 184, 121, 164, \     124, 161, 109, 165, 150, 183, 111, 154, 132, 136, 88, 123, 388, 387, \     382, 375, 340, 325, 374, 324, 372, 295, 398, 361, 547, 418, 483, 381, \     517, 465, 454, 432, 414, 288, 342, 241, 281, 261, 218, 172, 165, 127, \     532, 392, 397, 345, 403, 375, 400, 342, ...}          inf = Flatten@Position[lst, _?(# > 255 &)];     ReplacePart[lst, inf -> 255]      It seems that it doesn't effect the list at all. Thanks a lot for opening my eyes...


Replacing values above a threshold with 1

I have a list with some values and I want to replace a value which is greater than 1 with 1 otherwise keep the value. In this case 10562:                  list[[1]]= {0.61975, 10562., 0.43274, 0.15068, 0.13703, 0.057564}      I tried this approach:               Table[If[list[[1, x]] > 1, list[[1, x]] = 1, list[[1, x]]], {x,        1, Length[list[[1]]]}]      It works, but I'm wondering if there is a much simpler solution with mathematica. Can anybody help me out?


Bug with LinearProgramming on Integers?

With _Mathematica_ 7:               LinearProgramming[{1, 1}, {{0, 0}, {1, 1}}, {1, 1}, Automatic, Integers]      gives wrong result `{0,1}`. But               LinearProgramming[{1, 1}, {{0, 0}, {1, 1}}, {1, 1}, Automatic, Reals]      gives correct error: > LinearProgramming::lpsnf: No solution can be found that satisfies the > constraints. From my point of view this is a buggy behaviour, or did I miss something? Can someone confirm this for newer _Mathematica_ versions?


Plotting a list along with its trend line

Say I have these data:               data = {{1, 3}, {2, 4}, {3, 6}, {4, 7}};      I want to fit these data with a quadratic equation, like this:               Fit[data, {1, x}, x]      _Mathematica_ then outputs $1.5 + 1.4x$. However, trying to plot this like this:               Plot[Fit[data, {1, x}, x], {x, 0, 5}]      Results in the errors               General::ivar: 0.00010214285714285715` is not a valid variable.     General::ivar: 0.00010214285714285715` is not a valid variable.     General::ivar: 0.10214295918367347` is not a valid variable.     General::stop: Further output of General::ivar will be suppressed during this calculation.      I tried copying the $1.5 + 1.4x$ directly into `Plot`, after which I saw that it did not actually say $1.5 + 1.4x$:               Plot[1.5000000000000009` + 1.3999999999999995` x, {x, 0, 5}]      So that's where the ` came from. Surely removing them manually is not the way to go. What went wrong?


How to collect terms of a given type (with subscript and power) in an expression?

Suppose that I have an expression:               expr=(2 λ f[      z]^3 (λ (Subscript[λ, 0, 2] +           Subscript[λ, 2, 0]) - Subscript[λ^2, 0, 1] -        Subscript[λ^2, 1, 0]) - λ^2 (Subscript[z^2, 0,        1] + Subscript[z^2, 1, 0])^2 Derivative[1][f][z]^2 + f[z]^2 (4 λ^2 (-Subscript[z, 0, 2] Subscript[z, 2, 0] +           Subscript[z^2, 1, 1]) +        2 λ (Subscript[z, 0,            1] ((-Subscript[z, 0, 2] + Subscript[z, 2,                 0]) Subscript[λ, 0, 1] -              2 Subscript[z, 1, 1] Subscript[λ, 1, 0]) +           Subscript[z^2, 0,            1] (Subscript[λ, 0, 2] + Subscript[λ, 2,              0]) + Subscript[z, 1,            0] (-2 Subscript[z, 1, 1] Subscript[λ, 0,               1] + (Subscript[z, 0, 2] - Subscript[z, 2,                 0]) Subscript[λ, 1, 0] +              Subscript[z, 1,               0] (Subscript[λ, 0, 2] + Subscript[λ, 2,                 0]))) - (Subscript[z^2, 0, 1] + Subscript[z^2, 1,           0]) (Subscript[λ^2, 0, 1] + Subscript[λ^2, 1,           0]) + 2 λ^3 ((Subscript[z, 0, 2] + Subscript[z, 2,              0]) Derivative[1][f][            z] + (Subscript[z^2, 0, 1] + Subscript[z^2, 1, 0]) (            f^\[Prime]\[Prime])[z])) + 2 λ f[      z] ((Subscript[z^2, 0, 1] + Subscript[z^2, 1,           0]) (Subscript[z, 0, 1] Subscript[λ, 0, 1] +           Subscript[z, 1, 0] Subscript[λ, 1, 0]) Derivative[1][         f][z] - λ^2 (Subscript[z^2, 0, 1] + Subscript[z^2, 1,           0]) Derivative[1][f][         z]^2 + λ (2 (-2 Subscript[z, 0, 1] Subscript[z, 1, 0]               Subscript[z, 1, 1] +              Subscript[z, 2, 0] Subscript[z^2, 0, 1] +              Subscript[z, 0, 2] Subscript[z^2, 1, 0]) Derivative[1][f][            z] + (Subscript[z^2, 0, 1] + Subscript[z^2, 1, 0])^2 (            f^\[Prime]\[Prime])[z])))/(4 λ f[     z] (λ f[z] + Subscript[z^2, 0, 1] + Subscript[z^2, 1, 0]))      and I want to collect the terms of the type               Subscript[z, 0, 1]      and               Subscript[z^2, 0, 1]      here 0, and 1 can be change. I can do for the first one as               Collect[ expr// ExpandAll, Subscript[z, _, _], Simplify]      but while I try to use               Collect[ expr// ExpandAll, Subscript[z^2, _, _], Simplify]      to collect the second one, it doesn't work, Why? What's more, can I write a pattern that will collect both of them at the same time?


How to explain the results of the following integrals?

Why does the following program lead to different results of `a21` and `a211`?               moveconst[x_] := (x /. Integrate[factor_ expr_, {var_, min_, max_}] /;            FreeQ[factor, var] :> factor Integrate[expr, {var, min, max}]);          inta1 = 2 (2 Cos[q3[t]] fec1[x1] q5[t] - fe1[x1] Sin[q3[t]] );     a1 = Integrate[inta1, {x1, 0, L1}] q6[t];          inta2 = (4 Cos[q3[t]] fec1[x1] q5[t] q6[t] -2 fe1[x1] Sin[q3[t]] q6[t]);     a2 = Integrate[inta2, {x1, 0, L1}];          a21 = a1 - a2;     Simplify[a21, TransformationFunctions -> {Automatic, moveconst}]               inta11 = 4 Cos[q3[t]] fec1[x1] q5[t] - 2 fe1[x1] Sin[q3[t]] ;     a11 = Integrate[inta11, {x1, 0, L1}] q6[t];          inta21 = (4 Cos[q3[t]] fec1[x1] q5[t] q6[t] - 2 fe1[x1] Sin[q3[t]] q6[t]);     a21 = Integrate[inta21, {x1, 0, L1}];          a211 = a11 - a21;     Simplify[a211, TransformationFunctions -> {Automatic, moveconst}]


Arranging elements in a Grid by drag&drop

I have some elements in a `Grid`. I want to change their positions within that `Grid`. Can I swap their positions just by dragging cursor on to them? For example                      Grid[{{1, 2, 5, 7, 9}, {3, 4, 8, 4, 2}, {5, 12, 7, 3, 8}}]      I want to swap positions of 8 and 2 in drag&drop fahion. Is it possible?


Poor performance when evaluating double integral of hat functions

I am trying to evaluate a double integral but am having performance issues. **First a bit of math** I am using a Galerkin like scheme to discretize operators in an equation I am working with. The problem I am trying to solve is this: I start with hat functions in x and y, $ \Psi_j(z) \left\\{ \begin{array}{ll} \frac{1}{\Delta z}(z-z_{j-1}) & , z < z_j\\\ -\frac{1}{\Delta z}(z-z_{j-1}) & , z >z_j \\\ 0 & , \left\vert z - z_j \right\vert > \Delta z \\\ \end{array} \right. , $ $ \Psi_i(y) \left\\{ \begin{array}{ll} \frac{1}{\Delta y}(y-y_{i-1}) & , y < y_i\\\ -\frac{1}{\Delta y}(y-y_{i-1}) & , y >y_i \\\ 0 & , \left\vert y - y_i \right\vert > \Delta y \\\ \end{array} \right. . $ where $i$ and $j$ correspond to a node on our grid. I then define an arbitrary function and the variable of interest (pressure in my case) as, $ \Theta(y,z) \cong \sum\limits_i \sum\limits_j \Theta_{ij} \Psi_i(y)\Psi_j(z) , $ $ p(y,z) \cong \sum\limits_i \sum\limits_j p_{ij} \Psi_i(y)\Psi_j(z) . $ The arbitrary function corresponds to the coefficient of the operator we are approximating. The integral I am trying to solve is, $ \Theta p |_{z = z_i} \cong \frac{\int \int \Psi_i \Psi_j \Theta p dz dy}{\int \int \Psi_i \Psi_j dz dy} $ **Now the Code** I am building off of what I had done earlier. Here are the piecewise functions:               ψzt[z_, c_] := Piecewise[{{(z - c)/Δz + 1, z <= c},                                {-(z - c)/Δz + 1, z > c}}];     ψz[z_, c_] := Piecewise[{ {ψzt[z, c], ψzt[z, c] > 0},                                {0, ψzt[z, c] <= 0}}];     ψyt[y_, c_] := Piecewise[{{(y - c)/Δy + 1, y <= c},                                {-(y - c)/Δy + 1, y > c}}];     ψy[y_, c_] := Piecewise[{ {ψyt[y, c], ψyt[y, c] > 0},                                {0, ψyt[y, c] <= 0}}];      Here are the functions I have defined (I just expand the double sum):               θ [y_, z_] :=      Subscript[θ, i - 1, j - 1] ψy[y, Subscript[Y, i - 1]] ψz[z,Subscript[Z, i - 1]] +                    Subscript[θ, i - 1,j] ψy[y, Subscript[Y, i]] ψz[z, Subscript[Z, i - 1]] +       Subscript[θ, i - 1,j + 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z, i - 1]] +       Subscript[θ, i,j - 1] ψy[y, Subscript[Y, i - 1]] ψz[z, Subscript[Z,i]] +     Subscript[θ, i,j] ψy[y, Subscript[Y, i]] ψz[z, Subscript[Z, i]] +      Subscript[θ, i, j + 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z,i]] +       Subscript[θ, i + 1,j - 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z, i - 1]] +       Subscript[θ, i + 1,j] ψy[y, Subscript[Y, i]] ψz[z, Subscript[Z, i + 1]] +      Subscript[θ, i + 1,j + 1] ψy[y, Subscript[Y, i + 1]] ψz[z,Subscript[Z,i + 1]];                μ[y_, z_] :=      Subscript[μ, i - 1, j - 1] ψy[y, Subscript[Y, i - 1]] ψz[z, Subscript[Z, i - 1]] +       Subscript[μ, i - 1, j] ψy[y, Subscript[Y, i]] ψz[z, Subscript[Z, i - 1]] +      Subscript[μ, i - 1,j + 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z,i - 1]] +       Subscript[μ, i,j - 1] ψy[y, Subscript[Y, i - 1]] ψz[z, Subscript[Z, i]] +     Subscript[μ, i, j] ψy[y, Subscript[Y, i]] ψz[z, Subscript[Z, i]] +     Subscript[μ, i, j + 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z, i]] +     Subscript[μ, i + 1, j - 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z,i - 1]] +      Subscript[μ, i + 1,j] ψy[y, Subscript[Y, i]] ψz[z, Subscript[Z, i + 1]] +      Subscript[μ, i + 1,j + 1] ψy[y, Subscript[Y, i + 1]] ψz[z, Subscript[Z,i + 1]];        Note: We use $\mu$ to represent $p$. Here are the assumptions I make:               BasisAssumY = {Δy > 0, Subscript[Y, i] ∈ Reals,     y ∈ Reals, Δy ∈ Reals,      Subscript[Y, i - 1] ∈ Reals,      Subscript[Y, i + 1] ∈ Reals,      Subscript[Y, i - 1] < Subscript[Y, i] < Subscript[Y, i + 1],      Subscript[Y, i + 1] - Subscript[Y, i ] == Δy,      Subscript[Y, i] - Subscript[Y, i - 1 ] == Δy,      Subscript[Y, i ] - Subscript[Y, i + 1] == -ΔY};      The same assumptions are made in the z direction.               BasisRulesAll = {Subscript[Z, i + 1] - Subscript[Z,      i ] -> Δz,      Subscript[Z, i] - Subscript[Z, i - 1 ] -> Δz,      Subscript[Z, i ] - Subscript[Z, i + 1] -> -Δz,      Subscript[Y, i + 1] - Subscript[Y, i ] -> Δy,      Subscript[Y, i] - Subscript[Y, i - 1 ] -> Δy,      Subscript[Y, i ] - Subscript[Y, i + 1] -> -Δy};      Here is my integrating procedure:               Simplify[Integrate[     Integrate[ψz[z, Subscript[Z, i]]  θ [y, z] μ [y,          z], {z, Subscript[Z, i - 1], Subscript[Z, i + 1]},        Assumptions -> BasisAssumZ] ψy[y, Subscript[Y, i]], {y,       Subscript[Y, i - 1], Subscript[Y, i + 1]},      Assumptions ->       BasisAssumY]/(Δz Δy)] //. \BasisRulesAll      This will run for hours without returning a result. In contrast, I have done a similar calculation in 1D (get the notebook here) that takes about 10 seconds. I did manage to get the integral to evaluate but I had to remove all $y$ terms from the $x$ integral (I grouped together like terms and factored). After doing that, the integral took about 10 seconds to be evaluated, but it was very messy and I cannot be sure that human error was not introduced. It would be simpler if the method above worked in a reasonable amount of time. Does anyone have any suggestions on how I could improve the performance of the double integration?


Moving From Dynamic Module to Manipulate

In trying to implement Vitaly's suggestion about how to take control of `Locator` events, I have been able to make headway using `DynamicModule`. However, the ultimate destination is a demonstration, so I'd like to make the code work in `Manipulate`. **The Code** The following pared-down version works fine. It places 5 locators in a coordinate space with _x_ and _y_ axes displayed.               DynamicModule[{p1 = {0, 2}, p2 = {2, 0}, p3 = {4, -3}, p4 = {-3, 3}, p5 = {1, 1}},     EventHandler[     dQ[p_, q_] := EuclideanDistance[p, MousePosition["Graphics"]] <      EuclideanDistance[q, MousePosition["Graphics"]];     Dynamic[      Style[Graphics[{       {Red, Disk[{0, Round@p1[[2]]}, .2]},       {Blue, Disk[Round@p2, .2]},       {Green, Disk[p3, .2]},       {Brown, Disk[p4, .2]},       GraphicsGroup[{Black, Line[{.1 {0, 1.5} + p5, .1 {0, 3} + p5}],          Line[{.1 {0, -1.5} + p5, .1 {0, -3} + p5}],          Line[{.1 {-1.5, 0} + p5, .1 {-3, 0} + p5}],          Line[{.1 {1.5, 0} + p5, .1 {3, 0} + p5}],          Circle[{0, 0} + p5, .2], Gray, Disk[p5, .1]}]},      PlotRange -> 5, Axes -> True],Selectable -> False]],      {"MouseDragged" :>       (Which[       dQ[p1, p2] && dQ[p1, p3] && dQ[p1, p4] && dQ[p1, p5],        p1 = MousePosition["Graphics"],       dQ[p2, p1] && dQ[p2, p3] && dQ[p2, p4] && dQ[p2, p5],        p2 = MousePosition["Graphics"],       dQ[p3, p1] && dQ[p3, p2] && dQ[p3, p4] && dQ[p3, p5],        p3 = MousePosition["Graphics"],       dQ[p4, p1] && dQ[p4, p2] && dQ[p4, p3] && dQ[p4, p5],        p4 = MousePosition["Graphics"],       dQ[p5, p1] && dQ[p5, p2] && dQ[p5, p3] && dQ[p5, p4],        p5 = MousePosition["Graphics"]])}]]      **Moving to Manipulate** The issue is really quite simple. How can I successfully wrap this code in `Manipulate`? I've tried this:                Manipulate[         <above code>,        {x,1,12,Slider} ]      [The slider serves no purpose at the moment.] **What happens** The manipulate screen appears as expected. However, evaluation goes into a loop. The cell right bracket blinks endlessly. What causes this loop? Why doesn't it occur when I use `DynamicModule` without `Manipulate`?


How to find the maximum of this function on the positive real line?

I need to maximize this function on the positive real line: $$ \frac{1}{\Gamma(x)^{14}}\cdot\frac{1}{{\frac{323.6}{14x}}^{14x}}\cdot(1.22578*10^{19})^{x-1}e^{-14x} $$ the correct answer should be around $x=514$, but I could not use mathematica to show it. My plot has a peak at $x=680$ instead. I want to ask if anyone has any idea how to get the correct answer. The code I am using now is:               A = 1/Gamma[x]^{14}*(301.6/(14*x))^{-14 *x}*(1.22578*10^{19})^{x -1} E^{-14 x}      and I plot it by               Plot[A, {x, 513, 700}, PlotPoints -> 1000]      The result is something very strange: ![enter image description here](http://i.stack.imgur.com/KWqRb.png)


What is a type in Wolfram Mathematica programming language?

"Everything is an expression" is a popular citation from many _Mathematica_ guidebooks. So, what is type in _Mathematica_? How does it relate to common types from Haskell, for example? I did some _simulation_ of dependent types:               DependentType::illegal= "Value is illegal for dependent types with constraints";     FixedSizedVector[n_?(Positive[#]&)] :=     Module[{type = Symbol["Vector" <> ToString[n]]},         type[dat_] := Message[DependentType::illegal] /; VectorQ[dat] && Length[dat] != n;         type     ];     types =     Map[         FixedSizedVector[#]&,         Range[1, 25]     ];      I have received an array `types` of symbols that are constrained with pattern checking rules. Is it a family of types? Another point is `Head` replacing. For example, for list `Range[1, 5]` I can just type `Plus @@ Range[1, 5]` and get `Integer[15]`. From the point of view of type, what is `Apply`?


How to convert each pair of { and } into ( and )?

I am a learn-by-example person. I have no idea to change every `{` and `}` to `(` and `)` respectively. Could you let me know which concept in Mathematica is related to this problem so I can learn it much faster? The objective is to convert the output of               Tuples[{{a, b, c}, {1, 2}}]      which is > {{a, 1}, {a, 2}, {b, 1}, {b, 2}, {c, 1}, {c, 2}} to LaTeX-friendly output as follows. I have learnt `TeXForm` but it must be called at the last phase.               $\{(a, 1), (a, 2), (b, 1), (b, 2), (c, 1), (c, 2)\}$


Why does CUDAQ (from CUDALink) download data from Wolfram servers?

I understand why functions like `ElementData` or `CountryData` need to download up-to-date data when first launched. However, when trying to use CUDA for the first time in Mathematica, I ran:               Needs["CUDALink`"]; CUDAQ[]      which downloaded data for several minutes. Given that I have a quite fast net connection, that must amount to a really large amount of data. What does Mathematica download in that case? I guess drivers, but how can I _check_ what it downloads?


How to make GraphicsGrid with content tight inside it?

I am trying to use GraphicsGrid to typeset some labels for my plots. I found the labels look little better when I use GrapicsGrid vs Grid. The labels have equations in them and not just plain labels. I just do not know how to make a GraphicsGrid which has no wasted space in it. Here is an example using Grid, which does not have the problem of wasted space, and same example, using GraphicsGrid. Ps. in this example, I am using a nice little makeBoxes function I found on the net by P.J. Hinton to make Derivatives in Traditionalform come out like they are in our textbook. Here is a link to the original post if needed               Remove["Global`*"];     MakeBoxes[Derivative[indices__][f_][vars__], TraditionalForm] :=        SubscriptBox[MakeBoxes[f, TraditionalForm],         RowBox[Map[ToString,           Flatten[Thread[dummyhead[{vars}, Partition[{indices}, 1]]] /.             dummyhead -> Table]]]];          title = 2 Derivative[2, 0][u][x, t] ==         1.1 Derivative[0, 1][u][x, t] + 80 Derivative[1, 0][u][x, t];          title = Style[title, 16];          GraphicsGrid[{{Item[title, Alignment -> Top], SpanFromLeft}},       ImageSize -> {150, 80}, Frame -> All, ImageMargins -> 0,       ImagePadding -> 0, BaselinePosition -> Center]      This gives ![enter image description here](http://i.stack.imgur.com/xeQw7.png) and using normal Grid, gives (noticed I had to call TraditionalForm once more here, but not with the above to get it to work)               Remove["Global`*"];     MakeBoxes[Derivative[indices__][f_][vars__], TraditionalForm] :=        SubscriptBox[MakeBoxes[f, TraditionalForm],         RowBox[Map[ToString,           Flatten[Thread[dummyhead[{vars}, Partition[{indices}, 1]]] /.             dummyhead -> Table]]]];          tr = TraditionalForm;     title = 2 tr@Derivative[2, 0][u][x, t] ==         1.1 tr@Derivative[0, 1][u][x, t] + 80 tr@Derivative[1, 0][u][x, t];          title = Style[title, 16];     Grid[{{Item[title, Alignment -> Top], SpanFromLeft}}, Frame -> All]      ![enter image description here](http://i.stack.imgur.com/jrQi7.png) Played around with GraphicsGrid, but can't figure how to automatically tell it to put the object inside it as tight as possible. It will be best if I do not not specify `ImageSize`. But using `ImageSize-> Automatic` does not work:               GraphicsGrid[{{Item[title, Alignment -> Top], SpanFromLeft}},       ImageSize -> Automatic, Frame -> All, ImageMargins -> 0,       ImagePadding -> 0, BaselinePosition -> Center]      ![enter image description here](http://i.stack.imgur.com/L89EL.png) Is there an option or a trick to do this? thanks


Dijkstra without Combinatorica

There is some overlap between Combinatorica and the Graph related framework but there are also various elements missing. As far as I can see there is no 'Dijkstra' method or algorithm in Mathematica or is there a way (combination of other Graph methods) to do it? That is, without accessing Combinatorica by converting Graph to an EdgeList and so on.


How can I draw the Olympic rings with Mathematica?

How can I draw the 5 interlocking Olympic rings with Mathematica? ![Olympic rings](http://i.stack.imgur.com/fJthQ.png) (SVG version) * * * **Edit** Hard choice, but some pretty cool answers here. I didn't have 3D answers in mind when I posted the question but without a doubt they look much better than the 2D. Very subjective choice for the selected answer but I do like @cormullion's answer.


Functional style using lazy lists?

Let's say I want to answer the question "what are the first 400 palindromic prime numbers?" The first approach that comes to my mind from the set of languages that I know is to use some sort of lazy list materialization, a la `IEnumerable` (and `yield`) in C#, generators in Python, or `sequence` blocks in F#. For example, in C#:               PrimesEnumerator().Where(n => n.ToString() == n.ToString().Reverse()).Take(400);      This would cause the PrimesGenerator to be pumped for primes long enough for the `Where()` clause to find enough numbers that meet the requirement for `Take()` to meet its quota. The best I've come up with in Mathematica is something like:               i = 1; results = List[];     While[Length[results] != 400,       If[IntegerDigits[Prime[i]] == Reverse[IntegerDigits[Prime[i]]],         results = Append[results,Prime[i]]];       i = i + 1]      It surprises me that I end up writing in such an imperative style in Mathematica. Am I missing something that would let me write this entirely functionally? Maybe even with lazy lists? > **Update:** I took inspiration from WReach's work of art answer, and made a > package that took his ideas and expanded them into a broad, general solution > for lazy data in Mathematica. I describe its usage in an answer below.


Graph and manipulate DSolve result

Given a `DSolve` example:               sol = Flatten[     DSolve[{D[x[t, th], {t, 2}] == -0.2*D[x[t, th], t]/2.30,       Derivative[1, 0][x][0, th] == 10.8*Cos[th], x[0, th] == 0},      x[t, th], t]]      Then assigning `sol` to a function:                x[t,th]/.sol[[1]]      I'm having trouble plotting a 2D portion of it:               Plot[x[t,1],{t,0,20}]      And also trouble Manipulating it:               Manipulate[x[t,th], {th, 0, Pi/2}]      What mistakes am I making?


PrependTo fails on a Table of Evaluated funtions

My task is something like this:               PrependTo[Evaluate[Table[{x, Sin[x]}, {x, 0.1, 2 \[Pi], 0.1}], {0., 1.}]]      where I tried also skipping the               Evaluate       and I get a               PrependTo::rvalue:      error. If I do:               a = Table[{x, Sin[x]}, {x, 0.1, 2 \[Pi], 0.1}];     b = PrependTo[b, {0., 0.}];      everything works fine. I want it to be a part of a big code, so doing it in one line without defining the first list separately would speed up the program. And I don't need the first list, only the second one, so why should I store both? How can I deal with this problem? Edit: The case is to make               Join[{{0., 0.}}, Table[{x, Sin[x]}, {x, 0.1, 2 \[Pi], 0.1}], 1]      but are there other, maybe better, solutions?


Does every Symbol in Mathematica induce a monad?

From my question about types in Mathematica, I assume that every `Symbol` in Mathematica is a type if it appears as a `Head` of some expression. So I can implement operators for monad associated with that `Symbol` (let it be `F` for instance):   1. monad _lift_ function ( _return_ in Haskell notation) is just `return[p_] = F[p]`;   2. monad _bind_ function ( _>>=_ in Haskell notation) is just a rule `bind[F[p_], f_] := F[f[p]]` (as monad Maybe is for example). From point of view of category theory, in Mathematica one can define some common rules for symbols to model monad multiplication (just flatten of repeating `Head`): `monadMultiplyRule = {p_[p_[params___]] -> p[params]}`. So expression `F[F[F[p_]]] //. monadMultiplyRule` will be just `F[p]`. Also all monad axioms are satisfied:   1. `return` acts as a neutral element of `bind`: `bind[return[p], f]` is `F[f[p]]` and `bind[F[p], Identity]` is `F[p]`;   2. sequential `bind` of two functions `f` and `q` is the same as a single `bind` with their "composition" `Bind[F[f[p]], q]`: `Bind[Bind[F[p], f], q]` and `Bind[F[f[p]], q]` produce both the same result `F[q[f[p]]]`. So, does Mathematica provide a natural maybe-like monad for every symbol and does it provide a natural framework for any explicit monadic computations?


Solving an integral equation numerically for an unknown within the integral

I'm trying to solve an integral equation of the form `Constant == Integrate [g(x)f(x,Efermi), {x,-200,200}]`, for the parameter `Efermi`. The function `g(x)` is `Exp[-(x^2)/5000]` and `f(x)` is `1/(1+Exp[(x-Efermi)/25]`. In addition to this, if the `Constant` is an array, I'd like to extract `Efermi` as an array. Any inputs on how to go about solving this would be appreciated.


How to avoid font substitution with Mathematica fonts?

When I export a `Plot` to `PDF`, a journal publisher complains that they do not have the Mathematica fonts. I believe there is a way to inhibit Mathematica from substituting its fonts (e.g., for `"("`) but I cannot figure it out. I tried this but it did not work.                Plot[<deleted> , BaseStyle -> {PrivateFontOptions -> {"OperatorSubstitution" ->False}}]


Solving systems of equations and derivatives

I am new to Mathematica, and I'm not sure how to solve a system of equations that include differentiation. Given that f and g are differentiable functions:               f(x) < 0 for all x       g(5) = 2       h(x) = f(x) / g(x)       h'(x) = f'(x) / g(x)       Then g(x) = ?      (The answer is 2) I didn't expect it to work, but I tried this:               DSolve[{f[x] < 0, g[5] = 2, h[x] == f[x]/g[x], h'[x] = f'[x]/g[x]}, g[x], x]      And of course it didn't work. How would I do this?


Is it possible to embed fonts in a .cdf?

I am trying to use a special font with musical symbols in a .cdf that I send to some friends. The font is called "Tempera" and is freely distributed here: http://christian.texier.pagespro-orange.fr/mididesi/free/index.htm#tempera In the .cdf I use substitutions like this:               sub = "A" -> "\*StyleBox[\(\!\(\*StyleBox[\"A\",\n\        FontFamily->\"Mathematica6\"]\)\!\(\*StyleBox[\"U\",\n\        FontFamily->\"Tempera\",\nFontSize->18,\nFontWeight->\"Plain\"]\)\)]";      which are used in this manner:                "A" //. sub      What this does is to change the regular "A" character into a curly A (from the Mathematica6 font) and a symbol that is a half-sharp (the "U" from the Tempera font). This works fine in Mathematica, and also in the .cdf on my computer. However, when I send it to my friend, he sees the "U" and not the half-flat. This is probably what you will see too, unless you download the Tempera font. I believe this means that Mathematica does not embed the font in the .cdf, and I'm wondering if there is any way to force the embedding to occur. While I could have my friend download the font, if I ever want to place the .cdf on the web, this would not be practical.


Finding exact local extrema of simple functions

I want to _exactly_ find all the local maxima of               f[x_] := x^4/4 - x^2/2      over the interval `[-Sqrt[2], 1 + Pi/10]`. The correct answer is that we have global maxima at `x = -Sqrt[2]` and `x=0`, and a local maximum at `x= 1 + Pi/10`. Right now my approach is to iterate the `Maximize` command, which finds global maximums symbolically, and each time it finds a maximum I tell it to not find the same one again. Of course after it finds the two global maxima, it doesn't give me anything useful on the third application, as the one I am trying to find is merely local. Now I could use `FindMaximum`, but that only yields a numerical approximation, and I want the exact value. Also note that in this case my algorithm fails to find the local maximum at an endpoint, but it would be easy to use a different function where the method would fail to find a local maximum properly inside the interval. **Iteration 1:**               Maximize[{x^4/4 - x^2/2, (x >= -Sqrt[2]) && (x <= 1 + Pi/10)}, x]      This finds the point `x=0`. **Iteration 2:**               Maximize[{x^4/4 - x^2/2, (x >= -Sqrt[2]) && (x <= 1 + Pi/10) && (x != 0)}, x]      This finds the point `x = -Sqrt[2]`. **Iteration 3:**               Maximize[{x^4/4 - x^2/2, (x >= -Sqrt[2]) && (x <= 1 + Pi/10) && (x != 0) && (x != -Sqrt[2])}, x]      Of course this throws a "no maximum in the region" error, when I would like it to find `x = 1 + Pi/10`. I am open to patches for this approach or completely different algorithms as well.


Is it possible restore initial values after modify a control in manipulate?

I used to program in Visual Basic, but in _Mathematica_ I have not seen some kind of restore default values after any user modification command in the `Manipulate` environment. For instance, in               Manipulate[x + y, {{x, 1, "First"}, 1, 6}, {{y, 40, "Second"}, {40, 50, 60}}]      ![enter image description here](http://i.stack.imgur.com/dscU5.png) The user modify the slider for `x` to `5`. ![enter image description here](http://i.stack.imgur.com/D0rat.png) After that, when the user pick other value for `y`, there is a way to restore `x` to the initial value? such that: ![enter image description here](http://i.stack.imgur.com/aRi3y.png) And also by modifying the slider `x` again restore the value `y` to `40`. In other words, by detect a modification in the controllers, could `Manipulate` restore the default values?


Cancelling units in two-argument ArcTan

Consider               ArcTan[3, -3]       (* out: *) -Pi/4            ArcTan[3 a Sin[t/2], -3 a Sin[t/2]]     (* out: *) ArcTan[3 a Sin[t/2], -3 a Sin[t/2]]        However, we can fix the second one with some assumptions (where applicable)               $Assumptions = a > 0 && Pi > t > 0       Refine@ArcTan[3 a Sin[t/2], -3 a Sin[t/2]]     (* out: *) -Pi/4        I need a way to force mathematica to similarly realize it can cancel units in the ArcTan (which is basically a ratio, except for the sign consideration for the quadrant). For example, say I now have               $Assumptions = a > 0 && Pi > t > 0        aa=(4 Pi/(3 Sqrt[3]))(Quantity[1.42, "Angstroms"])^(-1)       b=(Quantity[5, "Angstroms"])^(-1)     ArcTan[b+3 aa Sin[t/2],-b-3 aa Sin[t/2]]      How can I force Mathematica to recognize that these arguments are just +c and -c and thus the ArcTan significantly reduces? I wish to avoid removing the units here artificially with QuantityMagnitude[] because elswhere in these expressions the units appear outside of these ArcTan[]s. However, a last ditch solution would be one that simply searched for these ArcTan[] and applied QuantityMagnitude[] to their arguments, I suppose.


Replacing functions

Given an expresion 'e' in terms of a function 'f' and given another function 'g', how could I write a Module that replaces the function f to g in the expresion e and returns it? An example:               MyFunction[expresion_, f_, g_] := (...)      `MyFunction[f[x]-3, f, Sin[x]]` should evaluate to `Sin[x]-3` `MyFunction[D[f[x],x], f, x]` should evaluate to `1` `MyFunction[f[x], f, 19]` should evaluate to `19` I hope it's clear. Sorry about my bad english.


Why mathematica have difficulty solving nonlinear equations?

I tried to solve this equation via Mathematica:               Solve[-(0.35 - b)/sigma == 9.8602 &&A*Exp[-(0.35 - b)^2/(2*sigma)] == 0.150099           &&A*Exp[-(0.55 - b)^2/(2*sigma)] == 0.895049, {A, b, sigma}]      However, mathematica shows that: Solve::inex: Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system. Since many of the methods used by Solve require exact input, providing Solve with an exact version of the system may help. What should I do?