title: DictionaryLookup very slow

text: I'm trying to plot, given a list of words, how many words belongs to each language. I'm using the following code:               Total /@ Transpose@        ParallelMap[         Function[word,           Length@DictionaryLookup[{#, word}] & /@ DictionaryLookup[All]] ,          wordList]      I am finding it way too slow, the lengths of the lists of words which I am using are about 45000 (sample file: https://dl.dropboxusercontent.com/u/35192406/words.txt) Is DictionaryLookup really slow? Does it use Internet? How can I speed up my function?


title: Why there is no SlotSequence (##) form analogical to #[[ ;; n]]

text: I'm aware that this may be closed as offtopic but there are people around with "offtopic" knowledge :) So, in `List` context we can: `#[[n ;; ]]` and `#[[ ;; n]]`, but we can't do this in context of `Sequence`. Only `##n` is available. One may do               f[n_] := Unevaluated[##][[;; n]] &     f[2][1, 2, 3, 4]      > >     Sequence[1, 2] >   but it is not what I'm looking for. It is very often when I would like to use it. Of course thare are no problems with workarounds. I'm just curious. p.s. Syntax is an issue for sure, I thought something like `###2` could stand for this but `###` is automatically interpreted as `##1 #1`.


title: Select repeating cluster of numbers

text: I have a list with measured data. There are multiple measurements in the list, but each measurement requires some time to find its equilibrium. I'd like to know the positions of the equilibria, but because of errors (during the measurement and in the behaviour of the measured quantity), I'd like to get five consecutive values from each equilibrium, so I can take the average (or at least compare them). Here is the graph of the data:   ![picture of data](http://i.stack.imgur.com/CVmja.png)   The useful data can be extracted at the positions used by               data[[450;; ;; 500]]      I know the following will work               Tranpose@Table[data[[445+i;; ;;500]],{i,0,10}]      But I expected the following to work (which it does not sadly)               data[[Range[445,455];; ;;500]]      Can this be done without using `Table` (or similar constructs)?


title: Law of Cosines to determine angle change along spiral

text: # The Spiral I'm trying to place circles along the outside of an Archimedean spiral. Shown below: ![Archimedian Spiral from 0 to 6 Pi](http://i.stack.imgur.com/nbgyo.png)               ParametricPlot[{θ/(2*π)*Cos[θ], θ/(2*π)*Sin[θ]}, {θ, 0, 6π}, PlotStyle -> Red]      # The Circles ![Circle placement](http://i.stack.imgur.com/k60VS.png) To do this effectively I have been trying to use the Law of Cosines to determine the change in the angle. I found the path that would contain the circle centers:               f[θ_] := {((π+θ) Cos[θ])/(2π), ((π+θ) Sin[θ])/(2π)}      Using the Law of Cosines for the following: ![Law of Cosines for this example](http://i.stack.imgur.com/bTZ7J.png) Seems pretty straight forward, right? Well, when I went to solve for the angle alpha Mathematica seems to have trouble. ![code](http://i.stack.imgur.com/pUoAQ.png) seems to work "fine", but any subsequent evaluations don't seem to go smoothly. In fact, any evaluation that does not contain Pi seems to fail, and an evaluation of the distance between the points shows that the angle is off (!=1). ![Distance](http://i.stack.imgur.com/hK9FI.png) # The Question What am I doing wrong to be more than 5% off from what I expect. Also, is there a more efficient and correct method to solve for the angle? # An End Product Thanks to KennyColnago for his response. ![Final Product](http://i.stack.imgur.com/YVpvo.png)


title: Question about plotting

text: I have to plot this graph http://i.imgur.com/hf54aiT.jpg I tried `Graphics[{Circle[{0, 0}, 3, {-2Pi, 2Pi}]},PointSize[.025]]` I don't know how to proceed from here. Any help would be appreciated!


title: What are the most common pitfalls awaiting new users?

text: As you may already know, _Mathematica_ is a wonderful piece of software.   However, it has a few characteristics that tend to confuse new (and sometimes not-so-new) users. That can be clearly seen from the the fact that the same questions keep being posted at this site over and over. Please help me to identify and explain those pitfalls. Suggestions for posting answers:   * One topic per answer    * Focus on non-advanced uses (it's intended to be useful for beginners and as a question closing reference)   * Include a self explanatory title in h2 style   * Explain the symptoms, the mechanism behind the scenes and all possible causes and solutions you can think of. Be sure to include a beginner's level explanation (and a more advance one too, if you're in the mood)    * Include a link to your answer by editing the **Index** below (for quick reference) ## Index   * ### Basic syntax issues   * ### Avoiding procedural loops   * ### Understand what `Set` (=) really does   * ### Understand the difference between exact and approximate (Real) numbers   * ### Understand the difference between `Set` (or `=`) and `SetDelayed` (or `:=`)   * ### Lingering Definitions: when calculations go bad   * ### Learn how to use the Documentation Center effectively   * ### Understand that semicolon (;) is not a delimiter   * ### Using the result of functions that return replacement rules   * ### Attempting to make an assignment to the argument of a function   * ### Use Consistent Naming Conventions   * ### Assuming commands will have side effects which they don't:   * ### Undo is not available in general   * ### What the @#%^&*?! do all those funny signs mean?   * ### User-defined functions, numerical approximation, and NumericQ   * ### The displayed form may substantially differ from the internal form   * ### Why is my picture upside-down?   * ### Mathematica can be much more than a scratchpad   * ### Mathematica's own programming model: functions and expressions


title: How to define a function based on the output of DSolve?

text: I would like to define a function based on the output of the following DSolve call: `DSolve[{b Varx^2 - 2 b Varx x'[t] + b x'[t]^2 + m x''[t] == 0, x[0] == x0, x'[0] == V0x}, x[t], t]` I've tried to do the following: `x[t_] := DSolve[{b Varx^2 - 2 b Varx x'[t] + b x'[t]^2 + m x''[t] == 0, x[0] == x0, x'[0] == V0x}, x[t], t]` It showed the message: `$RecursionLimit::reclim: Recursion depth of 256 exceeded.`, so I believe I'm not doing it the right. Any ideas?


title: Find minimum value of function which calls NDsolve

text: I have defined a function which takes a coefficient for a differential equation as an argument, solves the differential equation with NDSolve, and returns the value of the solution at time t=10. I can plot this, but I can't seem to find the minimum value. This code demonstrates the problem i'm having:               f[k_] := y[10] /. NDSolve[         {y''[t] == -k*y[t], y[1] == 2 , y'[2] == 1},         y,         {t, 0, 10}     ];     Plot[f[k], {k, 0, 2}] (* works great *)     NMinimize[{f[k], k > 0, k < .75}, k] (* fails *)      > The NMinimize fails with the error NDSolve::ndnum: Encountered non-numerical > value for a derivative at t == 1.'. So how do I find the minimum of my function f?


title: Converting the output for variable assignments to a usable array form

text: Output from built-in _Mathematica_ functions often has this form (e.g. from `Solve`): > {1 -> {166., 254.214}, 2 -> {237.214, 254.}, 3 -> {121., 253.5}, 4 -> > {221.318, 251.682}, 5 -> {45., 246.}, 6 -> {125., 245.214}, 7 -> {166.5, > 244.7},...} How would I efficiently (without converting back and forth from a string) convert this to array of the form: > {{166., 254.214}, {237.214, 254.}, {121., 253.5}, {221.318, 251.682}, {45., > 246.}, {125., 245.214}, {166.5, 244.7},...}


title: How do I assign a formula to a variab

text: I want to compute equations and assign them to variable. This is a wxMaxima program that calculated symbolic PID gains for an integrating first order system               remvalue(all)$                      /* Undefine                         */     Gp: K*%alpha/(s*(s+%alpha));        /* System transfer function         */     Gc: Ki/s+Kp+Kd*s;                   /* Simple PID controller            */     CLTF: ratsimp(Gc*Gp/(1+Gc*Gp));     /* Closed loop transfer function    */     CE: expand(denom(ratsimp(CLTF)));   /* Characteristic equation          */     DIFCE: expand(CE-(s+%lambda)^3);     Ki: solve(coeff(DIFCE,s,0),Ki);     Kp: solve(coeff(DIFCE,s,1),Kp);     Kd: solve(coeff(DIFCE,s,2),Kd);     grind(Ki,Kp,Kd);      The grind outputs text that I can paste here               [Ki = %lambda^3/(%alpha*K)]$         [Kp = 3*%lambda^2/(%alpha*K)]$     [Kd = (3*%lambda-%alpha)/(%alpha*K)]$      Notice that Ki, Kp and Kd represent equations. This is what I want because I can change the values and compute new gains. This is my Mathematica equivelent               ClearAll["Global`*"];     Subscript[G, p][s] = (K*\[Alpha])/(s*(s + \[Alpha]))     Subscript[G, c][s] = Ki/s + Kp + Kd*s     T[s] = Subscript[G, c][s]*        Subscript[G, p][s]/(1 + Subscript[G, c][s]*Subscript[G, p][s]) //        Simplify     Solve[{CoefficientList[Denominator[T[s]], s] ==         CoefficientList[(s + \[Lambda])^3, s]}, {Ki, Kp, Kd}]      This looks ugly because I haven't found the Mathematica version of grind() yet. Notice that the results are in the form Ki->Lamba^3/(K*Alpha). The -> is not an assignment so I can't treat Ki as a formula.                            3                    2         \[Lambda]          3 \[Lambda]         -\[Alpha] + 3 \[Lambda]     {{Ki -> ---, Kp -> ----, Kd -> --------}}         K \[Alpha]        K \[Alpha]           K \[Alpha]      How do I assign Lambda^3/(K*Alpha) using equations instead of by hand? I give up. formatting what get much better. Edit Solve[{CoefficientList[Denominator[T[s]], s] == CoefficientList[(s + [Lambda])^3, s]}, {Ki, Kp, Kd}] /. Rule-> Equal Does not work. When I type Ki for I get Ki in return and not the equal for Ki. This looks like it works s = Solve[{CoefficientList[Denominator[T[s]], s] == CoefficientList[(s + [Lambda])^3, s]}, {Ki, Kp, Kd}] {{Ki, Kp, Kd}} = { Ki, Kp, Kd } /. s


title: Storing solution to x and y

text: If I do               sol=Solve[{2x+2==y,3x+9==y},{x,y}]      then Mathematica will tell me               {{x -> -7, y -> -12}}      But I would like to store values to x and y even if I don't write the following thing explicitly.               x = -7     y = -12      At least I know this is possible, because I found how to do it by myself. But now I forgot. But I am sure it is possible.


title: How to modify function argument?

text: Usually in programming languages, function arguments are normal local variables, which can be modified. Is this not true in Mathematica?               In[94]:= TTT[x_] := Block[{},        x += 2        ];          In[95]:= TTT[3]      > During evaluation of In[95]:= AddTo::rvalue: 3 is not a variable with a > value, so its value cannot be changed. >>               Out[95]= 3 += 2      Is it possible to simulate normal argument behavior somehow?


title: How to get a number from Solve

text: It's often useful to get just one number from `Solve`. I use the following construction for acquiring one solution from the expression returned by `Solve`.               q = t /. Solve[p == 2 t + 1, t][[1]]      Mostly I don't like to use the different variable name within `Solve`. And the rule-applying seems very unnatural. I think a solution that is more elegant must exist. Can anyone show me this?


title: Assign the result of Solve in a list

text: > **Possible Duplicate:**   >  Assign the results from a Solve to variable(s) I want to assign the results of a Solve command in a list. For example Solve[-((287 s^3)/50) == 0, s] returns {{s -> 0}, {s -> 0}, {s -> 0}} I want it to return {0,0,0}. Can this be done automatically and not manually? Thank you very much


title: Error in extracting a column

text: I imported excel data to Mathematica using this command.               kuruzD = Import[     "C:\\Users\\TMH\\Documents\\Problem Set 4\\kuruzData.xlsx"][[1]] //TableForm       I want to extract the 5th column. So, I used the command,               kuruzD[[All, 5]]      but, it results the data in 5th row? Could anyone please tell me what is my mistake?


title: Table of values for functions with random variables

text: I'm trying to get a table of values for functions with random variables. First of all, i have a function like that:               t = 100.0;     LimMatrix3x3[a11_, a12_, a13_, a21_, a22_, a23_] :=        SetPrecision[         TableForm[{           MatrixForm[             MatrixPower[{                 {a11, a12, a13},                  {a21, a22, a23},                  {1 - a11 - 21, 1 - a12 - a22, 1 - a13 - a23}               },               t],              TableAlignments -> Left]},           TableHeadings -> {{"m", "Value"}, Null},            TableSpacing -> {4, 2}],          3]      And two matrices:               MatrixIn :=        SetPrecision[         MatrixForm[{             {p11, p12, p13},              {p21, p22, p23},              {1 - p11 - p21, 1 - p12 - p22, 1 - p13 - p23}           },            TableAlignments -> Left], 3];          MatrixOut := LimMatrix3x3[p11, p12, p13, p21, p22, p23];      where variables pij are:               p11 = RandomReal[];     p12 = RandomReal[];     p13 = RandomReal[];     p21 = RandomReal[{0, 1 - 11}];      p22 = RandomReal[{0, 1 - p12}];     p23 = RandomReal[{0, 1 - p13}];      Now i want to get the table with values for matrices above and use this function:               k = 5;      TableForm[       Table[{MatrixIn , MatrixOut} , {, 0, k}],        TableHeadings -> {Table[a, {a, 0, k}], {"Basic Matrix", "Matrix infinity"}},        TableSpacing -> {3, 2},         TableAlignments -> Center]      As a result i get the table with 5 lines, which are identical. It happens because pij are evaluated only once. But i need to get random values for each pair of matrices. Is there a way to create from `MatrixIn`, `MatrixOut` functions? Or, i heard, it's possible to use `&` in some cases. Any other idea?


title: How to manipulate lists to get only part of the value

text: This is really a question about manipulating the output of `Maximize`. I have a function of 2 variables, defined thus:                Pqpcum[r_, b_] = Integrate[2 Pi*x*Pqp[x, b], {x, 0, r}, Assumptions -> {b > 0}]      I want to find the point where the maximum of a certain function, defined below, occurs:               Abs[Pqpcum[x1, b] - Pqpcum[x1, 0]], x1]      The function `Maximize` returns an array, like this:               In[24]:= Maximize[Abs[Pqpcum[x1, 0.1] - Pqpcum[x1, 0]], x1]          Out[24]= {0.0204023, {x1 -> 1.77787}}      Now I want to plot the location of the maximum, which is 1.77787 in this case, as a function of b. Attempting to get the second element of the array returns an element like this:               {x1 -> 1.777869648006448`}      The above cannot be plotted. I need to do something like this:               Plot[Maximize[Abs[Pqpcum[x1, b] - Pqpcum[x1, 0]], x1][[2]],{b,0,0.2}]      except that the above doesn't return anything, since I have plotted the list. How can I go about doing it? I could discretize the data and manually copy- paste the location of maximum values to do a `ListLinePlot`, but it would be a pain to do it. **EDIT:** I found my answer- I can use ArgMax instead. It directly returns the location of the maximum, so the above can be done. But the question still remains- how in general can one manipulate a list that reads like `{x1 -> 1.777869648006448}` to get only the numeric value `1.777869648006448`?


title: Do loop - variable does not change

text: I got the follwing code which should add a '1' 100 times to an empty list.               plotVals = {}     Do[Append[plotVals, 1], {l, 1, Nmax}];      The output is again an empty list, why is this the case?


title: Plot not displaying

text: I'm trying to perform a basic plot to show that two equations align, but I'm not getting any results. Plot[{[Pi]*Cos (3 x - [Pi]), [Pi] * Sin (3*[Pi] - 3 x)}, {x, -3 [Pi], 3 [Pi]}] To me this seems fairly straightforward, but I'm getting a graph without the functions.


title: Mathematica, nested optmization

text: I want to use the solution of `Maximize`, defined as a function, in another function. Here's an example:               f1[y_] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]]  (* or any other function *)      This definition is fine, for example if I give `f1[4]`, I get the answer `-((3 \[Pi])/8)`. The problem is that when I want to use it in another function I get an error. For example:               FindRoot[f1[y] == Pi/4, {y, 1}]      Gives me the following error: > ReplaceAll::reps: {x} is neither a list of replacement rules nor a valid > dispatch table, and so cannot be used for replacing. >> > > FindRoot::nlnum: The function value {-0.785398+(x/.x)} is not a list of > numbers with dimensions {1} at {y} = {1.}. >> I've been struggling with this for several days now! Any comment, idea, help, ... is deeply appreciated!


title: On reimplementing the Select function

text: I am working through the course _Programming Paradigms via Mathematica_. One of the exercises asks that you construct a function that mimics `Select`,even with three arguments. It also includes the following direction: > Do not use the `Select[]` function in your definition. Here is an example of how `Select` works:               Select[{1, 2, 3, 4, 6, 8, 10}, EvenQ, 4]     (* {2, 4, 6, 8} *)      First I tested the following code and got the same result as `Select`:               l1 = {1, 2, 3, 4, 6, 8, 10};     l2 = {};     crit = EvenQ;     n = 4;     While[Length[l1] > 0 && Length[l2] < n,      If[crit[First[l1]], l2 = Append[l2, First[l1]]];         l1 = Rest[l1];      ]     l2          (* {2, 4, 6, 8} *)      I then tried to write a function that would do the same thing (caution causes infinite loop):               Clear[whileSelect]     whileSelect[l1_List, crit_, n_] := Module[{l2},       While[Length[l1] > 0 && Length[l2] < n,         If[crit[First[l1]], l2 = Append[l2, First[l1]]];             l1 = Rest[l1];         ]        l2       ]      However I got a series of `Set::shape: Lists {1,2,3,4,6,8,10} and {2,3,4,6,8,10} are not the same shape. >>` error messages and the code put the computer into an infinite loop. I have looked at documentation on `Module`,`Rest`,`Set` and `If` but have not been able to figure out what I am doing wrong. I would greatly appreciate a point in the right direction.


title: Combined numerical minimization and maximization

text: I want to numerically calculate the maximum of a function defined by the minimization of another function, like the following:               NMaximize[b/.NMinimize[(a^2+b)^2,{b}][[2]],{a}]      Obviously the intended result (for this simple test function) would be:               {0., {a->0.}}      because the inner minimization would give b=-a^2 for any value of a, and maximizing that gives 0 for a=0. However I get the error message `NMinimize::nnum: "The function value (-0.829053+a^2)^2 is not a number at {b} = {-0.829053}."` and the result `NMaximize[b/.{b},{a}]`. I figured that this is due to premature evaluation of the argument (i.e. before `a` got anumerical value), therefore I tried to wrap either the whole first argument of just the `NMinimize` call in `Unevaluated`, but neither helped. So my question is: How can I do this combined numerical optimization?


title: Circumventing the default scoping: Assign a variable inside a function

text: I'm currently trying very hard to assign a variable inside a function.   Therefore I'm using a function like this, which should reassign a predefined variable.               assign[a_] := (HoldForm@a = 2)     a=1;     assign[a]      The problem is that Mathematica uses the value of "a" instead of its name.   Any suggestions?


title: Store results of inequality

text: I eveluated some values using `Reduce` commend and I store them in a `Table`               t = Table[       N[Reduce[ 1/(1 + f) <= p[[i]] <= 1 + f , f], 100], {i, 1, n}]      Elements of a table looks like: `{f>= 99.000000000000000000000000000000000, f>=49.00000000000000000000000000000000...}` Now I want to plot this values for an integer domain. So I wanted to use ListPlot, but to use it I have to have a table which looks like: `{99.00000000000000000000000000000, 49.000000000000000000 ...}` How can I transform the first table to the second, which includes only values?


title: How to find the x-axis intersections/zeroes of a parametrized integral?

text: Consider the situation with this functions,                F[mm_, q_] :=  NIntegrate[(q/2) * (x Tanh[π x]) *( ( (Coth[π q Sqrt[x^2 + mm] ]                                 )/Sqrt[ x^2 + mm] - Coth[π x])/x,                     {x, 0, ∞}] + (1/2) Tan[Sqrt[mm] π ]   ;          Plot[ F[mm, 2], {mm, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/mGvpo.png) Looking at the graph it is clear that the function has roots in the range of $mm \in [0,1]$. But I am unable to use any of the root finding commands to get those numbers! Why are they not working here? * * * Also what are those vertical lines that the Mathematica is plotting here?


title: FindMinimum, NMinimize, etc. with external process

text: I was hoping to be able to use MMA's minimization power to work with an external process. I want to minimize the function 'TryThisNumber[x_]' which sends the value of x to something external and gets back a result from that external object. I want to find the number which minimizes the returned result. But ... I can only talk to the external process using strings. So, assume I have a function SendNumberToProcess[m_String] which does the actual communication with the process, I try:               TryThisNumber[x_]:= ToExpression[SendNumberToProcess[ToString[x]]];      and then,               FindMinimum[{TryThisNumber[a],0<a<10},{a}];      The problem is that ToString[x] in the above is just evaluating to the symbol, a, not a numerical value, and thus I'm not actually able to send a number to the external process. Any ideas? Update. Presumably the problem is that FindMinimum has the HoldAll attribute, but this attempt doesn't work either:               TryThisNumber[x_]:= ToExpression[SendNumberToProcess[ToString[Evaluate[x]]]];


title: "not a list of numbers" and "cannot be used for replacing "

text: I am trying to plot a function which is based on the solution of some equation; I could get the correct figure but only after lots of warnings are printed out. The following is a minimum version of my problem:               solx[z_] := FindRoot[x z == 40, {x, 1.}]     r[z_, f_] := f x /. solx[z];     Plot[Evaluate[Table[r[z, f], {f, 1., 5., 1.}]], {z, 1., 5.}]      Then I got the following warning messages: > FindRoot::nlnum: The function value {-40.+1. z} is not a list of numbers > with dimensions {1} at {x} = {1.}. > > ReplaceAll::reps: {FindRoot[x z==40,{x,1.}]} is neither a list of > replacement rules nor a valid dispatch table, and so cannot be used for > replacing. > > FindRoot::nlnum: The function value {-40.+1. z} is not a list of numbers > with dimensions {1} at {x} = {1.}. > > ... What can be done to avoid the warning messages? (I have tested that if I remove the $f$-dependence and plot $r[z]$, there is no warning messages, i.e.,               solx[z_] := FindRoot[x z == 40, {x, 1.}]     r[z_] := x /. solx[z];     Plot[r[z], {z, 1., 5.}]      works without any problem.)


title: Stop function evaluating input at time of definition

text: I would like to create a function that acts on whether the input is even or odd, e.g.:               In[644]:= f[a_] = If[EvenQ[a], 2 a, 3 a];               f[2]          Out[645]= 6      I've determined (I think) that this is because `a` is an expression and `QEven` returns false for expressions. How do I hold off evalution of this until input is given? I thought something like `Defer` would work but then it is never evaluated (see below)!               In[641]:= g[a_] = If[Defer[EvenQ[a]], 2 a, 3 a]          Out[641]= If[EvenQ[a], 2 a, 3 a]          In[643]:= g[3]          Out[643]= If[EvenQ[3], 2 * 3, 3 * 3]      Apologies if this gets asked a lot - I assume this is a common issue, but I was unable to come up with appropriate search terms to describe it (I'm not very familiar with Mathematica terminology yet). Thanks!


title: Error when solving equations constructed with Table

text: I have a couple of questions about the problem I am trying to solve               n = 7;     alpha = 0.01; c = 10;          atable = Table[a[i], {i, 0, n}];      Solu = y^Range[0, n].atable;          Leftequ = Solu;      Rightequ =  A y^2 +  B y + DD + 1/2/alpha Integrate[Solu^2, y];          Lec = CoefficientList[Leftequ, y];     Rec = CoefficientList[Rightequ, y];          Lec = PadRight[Lec, Min[Length[Lec], Length[Rec]]];     Rec = PadRight[Rec, Min[Length[Lec], Length[Rec]]];          eqs = Lec == Rec;          Sol = Solve[eqs, atable]      If I check `a[0]` it will show that `a[0]=a[0]`, but I want to set it to `a[0] = DD`. This is probably a mistake I overlooked, but nevertheless could not find it. Thanks in advance.


title: Mathematica "Insert" not working

text: Why doesn't this work:               mergeList[a_, b_] := (       list = a;       Insert[list, 98, 3];       Do[        Do[         (          If[           b[[f]] < list[[s]],           (Insert[list, b[[f]], s]; Break[])           ]          ),         {s, Length[list]}         ],        {f, Length[b]}        ];       list       )      It doesn't give an error, it just outputs the original value of list = a For example:               mergeList[{1, 2, 3, 4}, {2, 3, 4, 5}]      outputs `{1, 2, 3, 4}`, and I don't know why.


title: NMinimize not starting

text: I am new to Mathematica so I might be asking a trivial question, although I wasn't able to resolve it for several days. I am trying to optimize a 7x7 matrix with 12 variables with a certain evaluation function. The evaluation function is defined as:               SumCenter[v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, v12_] :=        Re[Sum[N[Func[v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, t]], {t, 0, 3, 0.01}]]      `Func` is a time dependent outcome of the matrix which is a little long if I tried to write it down here. Some functions that are used are: `MatrixExp[]`,`Tr[]`. I can guarantee that it gives a near accurate number, although it generates a very small amount of imaginary number which is not supposed to be there. That is why there is the `Re[]` function. `N[]` might not be necessary. Then I used `NMinimize` to find the optimal value and the variables:               NMinimize[{SumCenter[z1, z2, z3, z4, z5, z6, z7, z8, z9, z10, z11, z12],        -1 <= z1 <= 1 && -1 <= z2 <= 1 && -1 <= z3 <= 1 && -1 <= z4 <= 1 &&       -1 <= z5 <= 1 && -1 <= z6 <= 1 && -1 <= z7 <= 1 && -1 <= z8 <= 1 &&        -1 <= z9 <= 1 && -1 <= z10 <= 1 && -1 <= z11 <= 1 && -1 <= z12 <= 1},        {z1, z2, z3, z4, z5, z6, z7, z8, z9, z10, z11, z12},        StepMonitor :> Print["Step to z1 = ", z1]]      The calculation did not begin. Even though I put StepMonitor, it did not show the first step. I made a rather simple version with 3x3 matrix and 3 variables, which worked perfectly. I would like to figure out what might be causing the problem.


title: Why would this function work only when I make a copy of the variable?

text: Why would this function work with a copy of the function variable:               Clear[zero]     zero[list_] := Module[{listCopy = list}, listCopy[[2]] = 0; listCopy]     zero[{1, 2, 3, 4, 5}]     (* {1, 0, 3, 4, 5} *)      but not when using the variable directly?               Clear[zero]     zero[list_] := Module[{}, list[[2]] = 0; list]     zero[{1, 2, 3, 4, 5}]      ![Mathematica graphics](http://i.stack.imgur.com/DSZFZ.png)


title: Check if an inequality holds among the solutions returned by Solve

text: Let's say I solve a system:               Solve[{a == 3* c, b == 2 *a}, {a, b}]      and then want to see if the values found for `a` and `b` satisfy an inequality:               Reduce[a < 7 b]      What I would usually do is copy and paste by hand the result of the `Solve[]` to make it available to `Reduce`:               Solve[{a == 3* c, b == 2 *a}, {a, b}]     (output) {{a -> 3 c, b -> 6 c}}          a = 3 c;     b = 6 c;     Reduce[a < 7 b]      but there must be a better way to do this? I would also like all those variables (`a`,`b` and `c`) to stay local because I will have to solve a lot of similar equations with the same variable names on the same notebook and I wouldn't want the values to mix.


title: Mathematica can't minimize a function

text: Mathematica seems not to be able to minimize this univariate function over integer arguments, $r>2, r \in \mathbb{Z}$.               k=6;     SB[n_, r_] :=       Sum[Binomial[r Binomial[2 k, 2]/2, i] Binomial[         Binomial[n, 2] - r Binomial[2 k, 2]/2,          r Binomial[k, 2] + r - i], {i, r Binomial[k, 2] + r/2,         r Binomial[k, 2] + r}]               NMinimize[{SB[k r, r], Element[r, Integers] && r > 2}  , r]      This takes forever, even if, evaluated with `Table` the function in the interval $r=(2,100]$ for example, has perfectly valid values. The other command `FindInstance` seems unable to tell me a valid value when checking if $S_B(k r,r) > 0$ even if this is true for every value of $r$. Some help to make this computation faster or let it converge to a feasible solution? I know the solution is at $r=2$ but I just want to know how to properly specify this problem that is part of a more general framework.


How to convert the expression '{a->a0, b->b0}' to the expression 'a=a0; b=b0'? I think this is a common question and do not know if someone has asked it before. Any help or suggestion will be appreiated!


title: Evaluation of m.v is blocked by applying MatrixForm. Why?

text: I'm trying to understand what is happening in the notebook session below. I have a 2x2 matrix `m = {{-1,-1}, {-1,-1}}`. And a vector `v ={1,1}`. `m.v` (not shown) gives `{-2,-2}` as expected, and applying `MatrixForm` to `m`, to `v`, and to `m.v` gives presents the 3 values in the form I would expect. However, if `MatrixForm` is applied to `m` and `v` prior to evaluating `m.v` (as shown) then both `mm.vv` and `mm.vv` give the same unexpected result -- what appears to be then "unevaluated" product. (And possibly the wrong "kind" of product: "m dot v", rather than "m times v".) I realize there are (probably related) issues around Mathematica not actually operating in terms of "column vectors", and instead doing some more general tensor based operation. I'm in the process of trying to understand all that as well. But my basic question here is what exactly `MatrixForm` is doing. I thought that is was simply a presentation-level operation, but it appears that is not the case? ![MatrixForm, applied after and before](http://i.stack.imgur.com/n2oS7.png)


title: Fitting a Function With a Numerical Integral

text: I am having trouble using FindFit with the following function.               f[x_] := NIntegrate[a x k, {k, 0, 1}];          data = {{0, 0}, {0.2, 0.1}, {0.4, 0.2}};          param = FindFit[data, {f[x],2>a>1},a, x]      I get the following error               NIntegrate::inumr: The integrand a k x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>      Yet I can easily plot the function if I set "a" to any value between 1 and 2. So I assume FindFit is not assigning "a" a numerical value for some reason? This function is the simplest function in which I can reproduce the error (The data set is similarly a toy dataset). The actual function I need to use will be more complicated, so unfortunately getting rid of NIntegrate is not possible. Thanks


title: Replace doesn't replace the denominator

text: I have the following expression in Mathematica                   -((E^(2 - 2 Sqrt[(x[1] - x[2])^2]) (x[1] - x[2]))/Sqrt[(x[1] -         x[2])^2])      I want to replace anything of the form `Sqrt[t^2]` to `t`. I tried               -((E^(2 - 2 Sqrt[(x[1] - x[2])^2]) (x[1] - x[2]))/       Sqrt[(x[1] - x[2])^2]) /. Sqrt[(t_)^2] -> t      But it just does the changes in the numerator and not in the denominator. What is that I am doing wrong here? Thanks in advance! -dbm


title: Defining a Function, := versus =

text: Consider:               crossRatio[z_, q_, r_, s_] := (z - q) (r - s)/((z - s) (r - q));     points1 = {-1, 1, (-1 + Sqrt[2]) I};     points2 = {I, -I, 1};     ff[z_] :=       w /. Solve[          crossRatio[z, Sequence @@ points1] ==            crossRatio[w, Sequence @@ points2], w][[1]] // Simplify      Now               ff[(-1 + Sqrt[2]) I]      gives me a sequence of errors: > Power::infy: Infinite expression 1/0 encountered. >>   >  Solve::infc: The system ComplexInfinity==((1/2-I/2) (-I+w))/(-1+w) contains > an infinite object ComplexInfinity. >>   >  ReplaceAll::reps: {ComplexInfinity==((1/2-I/2) (-I+w))/(-1+w)} is neither a > list of replacement rules nor a valid dispatch table, and so cannot be used > for replacing. >> However, if I leave out the semicolon:               ff[z_] = w /.         Solve[crossRatio[z, Sequence @@ points1] ==            crossRatio[w, Sequence @@ points2], w][[1]] // Simplify      Then it works.               In[262]:= ff[(-1 + Sqrt[2]) I]          Out[262]= (I Sqrt[2] (Sqrt[2]-1)-I (Sqrt[2]-2))/(I Sqrt[2]+I (Sqrt[2]-2) (Sqrt[2]-1))          In[263]:= Simplify[%]          Out[263]= 1      How come? What's the difference between f[z_]:= and f[z_]= ?


title: How can I access numerical values of variables calculated with Solve?

text: I am trying to calculate some thermodynamical cycles so I often use lists with equations. Here's a simple example:               list1 = {          x + 2 y == z,          z - 2 x == 3z,          y - z == 5 x}          Solve[list1,{x,y,z}]      > >     {{x -> 0, y -> 0, z -> 0}} >   The problem appears when I want to use the calculated values of `x,y,z` later on to calculate some other parameters. _Mathematica_ every time keeps returning `x,y or z` instead of its numerical value. Is that because the result of `Solve` is a nested list? Anyway, what should I do to have an access to these values?


title: Getting message NIntegrate::inumr: in V10; did not happen in V9

text: I just tried making a `ParametricPlot` that worked error-free in _Mathematica_ 9, but now produces errors before successfully plotting in _Mathematica_ 10\. It appears to have something to do with which order _Mathematica_ evaluates the various expressions. A very simple example that generates this error is the command               ParametricPlot[{t, NIntegrate[a*t, {a, 0, 1}]}, {t, 0, 1}]      which produces > NIntegrate::inumr: "The integrand a t has evaluated to non-numerical values > for all sampling points in the region with boundaries {{0,1}}. " a couple times before suppressing the error and showing the plot. My actual functions are much more complicated, and, while I'd like to get rid of this annoyance, I'd also prefer to not have to rewrite many function definitions.


title: Use FindRoot solution as number in function

text: I would like to save a number that I gain with FindRoot so that I can use it in another function. I tried:               alph := FindRoot[BesselJ[0, x], {x, 0, 2}]     f[x_] := alph*x     Plot[f[x], {x, 0, 10}]      This does not work because `alph` is not a number but an expression `{x -> 2.40483}`. So how do I do this correctly?


title: What is wrong with setting one list to another within function?

text: I have built a function which carries out a set of operations given two parameters. The function looks as follows:               playingHand[Player_, Name_String] :=      Row[{Style[Name <> ":", FontSize -> 48, FontFamily -> "Calibri"],         Spacer[20]}~Join~        If[Player == {}, {Style["Not playing", 48, Gray,            FontFamily -> "Calibri"]},         {ButtonBar[Table[            With[{i = i},             Player[[i, 3]] :>              {AppendTo[discardPile, Player[[i]]],                Player = Delete[Player, i]}],            {i, Length@Player}]]}]]      The gist of this function is that as its first input it takes a list, which looks something like: ![enter image description here](http://i.stack.imgur.com/S6cOs.jpg) and displays the third elements of each list within that list: ![enter image description here](http://i.stack.imgur.com/ejcR3.jpg) It also makes these images clickable, so that when one of these cards is clicked, it should disappear from `player1` and get added to an initially empty list called `discardPile`. So far so good. When I run this function by itself without the defined function, namely like this:               ButtonBar[Table[        With[{i = i},         player1[[i, 3]] :>          {AppendTo[discardPile, player1[[i]]],            player1 = Delete[player1, i]}],        {i, Length@player1}]] // Dynamic      it works like a treat. The cards are clickable and they disappear from the `ButtonBar` as soon as they are clicked and added to `discardPile`. When I try to do the same from within the function though, namely `playingHand[player1, "Aron"] // Dynamic` it suddenly stops working. A `Set::shape` error message comes up warning that two lists are not the same length, and although it does add the card to `discardPile`, it does not remove it from `player1`. So:   1. What is wrong with this function and why won't it delete the card from the list when it is clicked, and   2. How come the same error does not occur when I run the function directly without calling it by its function name?


title: Adding a tree to a list of trees within a loop

text: I'm trying to write a function which for a list of trees checks if a given tree is isomorphic with any of the listed, and if not - adds it to the list. I tried to use both `Append` and `AppendTo`, but they don't work ( I checked for non-isomorphic trees, and whole loop is executed, but nothing is added to the list).   `Append` doesn't seem to work at all (I mean outside of the loop), and `AppendTo` works outside, but doesn't work in loop.   What can be a problem here?               checkIsomorph[outList_, seedling_] :=       For[i = 1, i <= Length[outList], i++,       If[IsomorphicGraphQ[outList[[i]], seedling], Break[],        If[i == Length[outList], AppendTo[outList, seedling],         Continue[]]]]


title: Assign the results from a Solve to variable(s)

text: I understand Mathematica can't assign the results of a Solve to the unknowns because there may be more than 1 solution. How can I assign the 4 values of following result to variables? ![enter image description here](http://i.stack.imgur.com/wu2c0.png)


title: How to fit ODE's coefficient, just like using NMinimize

text: I want to fit ODE's coefficients to a model. I tried using `NMinimize`, but it seems it does symbolic instead of numerical calculations.               ode[a_] := Block[{am=a},            sol=NDSolve[{x''[t]==a,x[0]==0,x'[0]==1},x,{t,0,2}];            Abs[x[1]/.sol]]     NMinimize[ode[a],a]      And then, I got the Error Message: > >     NDSolve::ndnum: Encountered non-numerical value for a derivative at t == > 0.`. >   I have also tried `Method->"RandomSearch"` ect. I got:               {Abs[x[1] /.         NDSolve[{(x^\[Prime]\[Prime])[t] == a, x[0] == 0,         Derivative[1][x][0] == 1}, x, {t, 0, 1}]], {a -> -0.829053}}      I receive the error message > >     ReplaceAll::reps: "\!\({NDSolve[{\*SuperscriptBox[\"x\", > \"\[Prime]\[Prime]\", >       MultilineFunction->None][t] == a, x[0] == 0, \*SuperscriptBox[\"x\", > \"\[Prime]\", >       MultilineFunction->None][0] == 1}, x, {t, 0, 1}]}\) is neither a list >       of replacement rules nor a valid dispatch table, and so cannot be used > for replacing." >   It seems to me that it performs symbolic calculations instead of numerical. Is there a way to solve this problem OR is there other ways to fit ODE's coefficients to a model ?


title: The /. syntax in numerical methods

text: I have an analytical approximation method for solving an ODE and want to compare this to an NDSolve solution, but the syntax is confusing me. To get the solution from NDSolve, I define the ODE as eqn and use the following command to solve for O2n;               s = NDSolve[{eqn == 0, O2n[rn] == 0, O2n[ro] == po/omega},        O2n, {r, rn, ro}]          Af = Plot[{(O2n[r]) /. s}, {r, rn, ro}, PlotStyle -> {Blue},        PlotLegends -> LineLegend[{"Numerical"}]]      This works fine, but the /. syntax confuses me a little - what exactly does it signify, and how can I manipulate this? Specifically, I want to subtract my analytical function p[r] from this solution over the same range (rn - ro) to see how much they differ. Ideally I'd like to be able to export this data and analyze it further - can anyone explain the syntax to me, and how I might go about comparing the twain? Thank you!


title: How to use output from previous line in Plot?

text: Suppose, I want to solve a equation and want to obtain it's first root. In this case I've used               In[1]=:Solve[b^2 + b*z + 1 == 0, b][[1]]      This gives               Out[2]={b -> 1/2 (-z - Sqrt[-4 + z^2])}      Now I want use this result directly in Plot command. My code for this is               In[3]:Plot[Out[2], {z, -1000, 1000}, PlotRange -> All]      But I'm not getting the plot. If I use               In[4]:Plot[1/2 (-z - Sqrt[-4 + z^2]), {z, -1000, 1000}, PlotRange -> All]      I'm getting the plot correctly. I guess in In[3], `Out[2]` contains `b->`, that's why it's unable to plot. How to handle this situation? p.s. This is a prototype of my actual problem. I want to solve this in this way because my output is too large to copy and paste in the `Plot` command.


title: NIntegrate/NSum with parameters

text: I'm trying to calculate a continuous integral within a discrete integral. Something similar to this (yet more complex):               NSum[NIntegrate[x^2 + y, {x, 0, 1}], {y, 2}]      I receive the following error code: > NIntegrate::inumr: "The integrand x^2+y has evaluated to non-numerical > values for all sampling points in the region with boundaries {{0,1}}. " What is the proper way to tell Mathematica to evaluate this expression?


title: How to define a variable updating function?

text: I tried to program a `Sudoku` solver when I suddenly ran into this problem: I need a function which effectivley does this:               Updater[a_,b_,c_,Sudoku_]:=Sudoku[[a]][[b]]=c      Quasi an updater. But the code above won't work because the only thing I get is: > SetDelayed::setps: > "{{Null,Null,8,1,7,6,Null,2,Null},{Null,4,Null,Null,Null,9,7,Null,Null},{Null,Null,Null,Null,Null,Null,Null,Null,Null},{Null,7,1,8,Null,Null,Null,Null,Null},{Null,Null,Null,Null,Null,Null,6,7,9},{Null,Null,Null,5,9,7,Null,8,1},{Null,Null,Null,Null,2,Null,Null,Null,Null},{Null,5,9,Null,Null,Null,Null,1,Null},{Null,1,4,6,5,Null,3,Null,Null}} > in the part assignment is not a symbol." The list in the error message is what I used as `Sudoku` in my `Updater` function.


title: Modifying a List in a function in place

text: An example will be most specific:               func[list_, column_] := list[[All, column]] = Map[#*2 &, list[[All, column]]];      This throws errors. I want to avoid doing something like this:               func2[list_] := Map[#*2 &; list];     list[[All, 2]] = func2[list[[All,2]]]      because nesting a couple of functions raises complexity unnecessarily, the output would have to be reassigned every time. Thanks in advance. As a followup, using HoldFirst works fine, but using the so defined function in a Map gives again errors. The setup is as follows: create a nested list               testList = Table[Table[{x y, x y 2}, {x, 1,3}], {y,1,3}]      define afunc with HoldFirst Attribute               afunc = Function[{list, col}, list[[All, col]] = Map[# * 2 &, list[[All, col]]], HoldFirst]      and another function using the first               bfunc[nestedList_, col_] := Map[afunc[#, col] &, nestedList]      now, a call to               bfunc[testList, 2]      should alter the 2'nd columns of the nested lists I'd expect, but it instead throws errors i've tried to set Attribute HoldFirst on this function as well but it didn't work out as expected


title: Simplifying expressions with square roots

text: I would like _Mathematica_ to simplify this expression: $4 \left(16 \sqrt{\left(-1+2 c^2\right)^2}-32 c^2 \sqrt{\left(-1+2 c^2\right)^2}+\sqrt{\left(1-8 c^2+8 c^4\right)^2}\right)^2$               expression = 4*( 16*Sqrt[(-1 + 2*c^2)^2] - 32*c^2*Sqrt[(-1 + 2*c^2)^2]                       + Sqrt[(1 - 8*c^2 + 8*c^4)^2])^2;      I have tried               PowerExpand[expression]          FullSimplify[expression]      but they did not simplify `expression`.


title: Assigning the answer of Solve to a variable

text: If I enter               Solve[(x-2)(x+2)==0,x]      then the answer comes up as               {{x -> 2}, {x -> -2}}      I want to make two variables sol1 and sol2, and sol1=2 and sol2=-2. I don't mean I want to make sol1 and sol2 from {{x -> 2}, {x -> -2}} I want to make them directly before anything such as {{x -> 2}, {x -> -2}} comes up. As long as I get sol1 and sol2, I don't need such answers like {{x -> 2}, {x -> -2}} I know it's possible because a year ago I could manage to do it after hours of trial-and-error. But I don't remember now.


title: Change input variable in a function

text: I'd like to write a function, that would take a matrix as an input parameter and would change it by multiplying one of its rows by a factor. I try to do it in the following way:               matrix=Table[i*j,{i,Range@2},{j,Range@2}]     MultiplyRowByFactor[m_,factor_,iRow_]:=Module[{},m[[All,iRow]]*=factor;m]     MultiplyRowByFactor[matrix,2,1]      and get an error message               Set::setps: "{{1,2},{2,4}} in the part assignment is not a symbol. "      Of course, if I change the matrix outside of the function:               matrix[[All,1]]*=2;     matrix      everything works as expected. What is the problem and how can I write a function to modify a matrix "in place"?


title: save all inputs as list

text: I received three results of calculations: > >     {k->0.190729} >   >     {k->0.197575} >   >     {k->0.249319} >   Could you help me write the results in the following form: > >     {0.190729,0.197575,0.249319} >


title: FindRoot gives strange results when used on an interpolating function with vector output

text: I am currently experiencing a problem when I try to use `FindRoot` with an interpolating function that outputs a vector. I have constructed a minimal example that illustrates the problem. Consider the following function, that parametrizes a circle in the plane.               circle[t_] := {Cos[t], Sin[t]};      Suppose you want to find the point at which the x coordinate of the circle equals one half.               FindRoot[ circle[t][[1]] - 0.5, {t, 0.1, 0, Pi/2}]      Of course, `FindRoot` finds the root: > >     {t -> 1.0472} >   However, sometimes you do not have an exact function, and you need to use an `InterpolatingFunction` instead. The function `circleInterpol` is an interpolation of $100$ points sampled from the circle. Although the interpolation of lists of the type `{ t, {x,y}}` is not considered in the reference, _Mathematica_ does not issue any warnings and plotting using `ParametricPlot` works fine.               circleInterpol = Interpolation[ Table[{t, circle[t]}, {t, 0, Pi/2, Pi/200}]]     ParametricPlot[{circle[t], circleInterpol[t]}, {t, 0, Pi/2}]      However, when I try to use `FindRoot` in the same way as before:               FindRoot[circleInterpol[t][[1]] - 0.5, {t, 0.1, 0, Pi/2}]      but with circle replaced by `circleInterpol`, I get a completely different (and obviously wrong) result: > >     {t -> 0.5} >   `FindRoot` does not issue any warnings at this point. Changing the syntax to (I realize that `{0.5, 0.1}` is not a point on the circle, but since you take the first part anyway, this should not matter.)               FindRoot[(circleInterpol[t] - {0.5, 0.1})[[1]], {t, 0.1, 0, Pi/2}]      issues the warning: > >     FindRoot::nveq: The number of equations does not match the number of > variables in >     FindRoot[(circleInterpol[t] - {0.5, 0.1})[[1]], { t, 0.1, 0, Pi/2}]. >> >   Replacing the interpolating function by the exact function still gives the correct result. So it seems to me that something is going wrong with the combination of `FindRoot` and `InterpolatingFunction`. An obvious solution to the problem is to construct two interpolating functions; one for each coordinate (`x` and `y`). Although this would solve the problem, I do not understand why this extra step is necessary. Could someone help me to understand what is going wrong here?


title: How to extract Solve results as variables

text: > **Possible Duplicate:**   >  Assign the results from a Solve to variable(s) In the following example:               Clear[g1, z1, a, g2, z2]     sa = Solve[ g1 == 1 + l z1/(z1^2 + a), a]     sb = Solve[ g2 == 1 - l z2/(z2^2 + b), b] /. z2 -> z1 + l      This gives me solutions for `a` and `b` that are in the form               {{ a -> astuff }}     {{ b -> bstuff }}      I want to use this result in a secondary computation, and did so by cut and pasting from the `Solve[]` results like so                Solve[ astuff == bstuff, z1 ]      How can I just extract those results without cut and pasting? I don't like the cut and paste dependency since I'd have to redo it all if I make any sort of correction to the first couple identities.


title: NMinimize and FindRoot Issues with System of Equations

text: I am trying to solve a constrained optimization problem with a system of transcendental equations and am running into issues with NMinimize. I have a system of equations (`twoPopsVac`) and a function (`popRootsVac`) to find the roots of these.               twoPopsVac[V1_, V2_, alpha_, S1_, S2_, R01_, R02_, N1_, N2_] := {(S1 - V1)*(1 -      Exp[-R01*(1 - alpha)*Zinf1/N1 - R02*alpha*Zinf2/N2]) - Zinf1,     (S2 - V2)*(1 - Exp[-R02*(1 - alpha)*Zinf2/N2 - R01*alpha*Zinf1/N1]) - Zinf2}          popRootsVac[V1_, V2_, alpha_, S1_, S2_, R01_, R02_, N1_, N2_ ] :=      FindRoot[twoPopsVac[V1, V2, alpha, S1, S2, R01, R02, N1, N2], {Zinf1,     S2 - V1}, {Zinf2, S2*V1}]      I then create an objective function (`finalSize`) that is a function of the roots and try to use it in NMinimize.               finalSize[vac1_, vac2_] := Total[{Zinf1, Zinf2} /. popRootsVac[vac1, vac2, 0, N1*s01,     N2*s02, R01, R02, N1, N2 ]]          NMinimize[{finalSize[x, y], x + y == Vtotal && 0 <= x <= N1 && 0 <= y <= N2}, {x, y}]      Unfortunately, when I try to minimize, it seems like the attempted values of the parameters (x and y) are not being passed all the way through the equations. Any idea what is going on? `FindRoot::srect: Value 9000. -x in search specification {Zinf1,9000. -x} is not a number or array of numbers. >>` `ReplaceAll::reps: {FindRoot[twoPopsVac[x,y,0,9000.,9000.,3,2,10000,10000],{Zinf1,9000. -x},{Zinf2,9000. x}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>`


title: Minimizing roots of a transcendental equations

text: I'm trying to use the solution of FindRoot with parameters for further calculations. Annoyingly enough it always gives me trouble with replacing the parameters. As an example I'm attaching a simple example I've cooked, since the solution is obvious. First I've defined the function "root", which is the solution for the equation, and is obviously (x-1)^2               root[x_] := y /. FindRoot[y - (x - 1)^2, {y, 1}]      Next I've tried to minimize this function, which should obviously return x=1, but I get a string of errors:               FindMinimum[root[x], {x, 2}]          FindRoot::nlnum: The function value {1. -1. (-1.+x)^2} is not a list of numbers with dimensions {1} at {y} = {1.}. >>          ReplaceAll::reps: {FindRoot[y-(x-1)^2,{y,1}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>          FindRoot::nlnum: The function value {1. -1. (-1.+x)^2} is not a list of numbers with dimensions {1} at {y} = {1.}. >>          ReplaceAll::reps: {FindRoot[y-(x-1)^2,{y,1}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>          FindRoot::nlnum: The function value {1. -1. (-1.+x)^2} is not a list of numbers with dimensions {1} at {y} = {1.}. >>          General::stop: Further output of FindRoot::nlnum will be suppressed during this calculation. >>          ReplaceAll::reps: {FindRoot[y-1. (-1.+x)^2,{y,1.}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>          General::stop: Further output of ReplaceAll::reps will be suppressed during this calculation. >>          FindMinimum::lstol: The line search decreased the step size to within the tolerance specified by AccuracyGoal and PrecisionGoal but was unable to find a sufficient decrease in the function. You may need more than MachinePrecision digits of working precision to meet these tolerances. >>          Out[87]= {0., {x -> 1.}}      The result comes out right in the end, but obviously something isn't right. Any ideas?


title: Use Output as Input

text: I have this function which as a result returns a point               f[x, y] =        Max[((x - #[[1]])^2 + (y - #[[2]])^2) & /@ Subscript[Rp, A0]];     min = Minimize[{f[x, y], {20 <= x <= 80, 20 <= y <= 80}}, {x, y}]        > >     {576.25, {x -> 34.5, y -> 52.}} >   How can I use this point $(x,y)$ as an input ?


title: Nested For Loops that result in no output

text: I am sure that this is not the most elegant code you will have seen, but I am trying to loop through an expression to see if `FultonHarrisn]` produces any outputs that are equal to a prime squared. My function `FultonHarris` is defined as follows:               FultonHarris[n_] := Product[(Sum[a[k], {k, i, j - 1}] + j - i)/(j - i), {j, 1, n}, {i, 1,     j - 1}]      and my for loop runs as follows, looping through `n` from `3` to `9`, and `j` from `1` to `n`, and `i` from `1` to `j-1`:               numPoints = 10; For[n = 3, n < 10, n++,      For[j = 1, j <= n, j++,       For[i = 1, i < j, i++,          a[i] := x; a[j] := y;  a[k_] /; k != {i, j} := 0;          dd[x_, y_, p_] := FultonHarris[n] - p^2;         FindInstance[         dd[xx, yy, pp] == 0 && xx > 0 && yy > 0 && PrimeQ[pp], {xx, yy,           pp}, Integers, numPoints]        ]       ]      ]      However, when I run this, it doesn't return anything, not even empty braces. Do I need to put a `Print` statement in there?


title: How to find the Mean of results given as a list of Rules?

text: How can we find the mean of the following type of data?               {{β -> 0.516819}, {β -> 0.499907},       {β -> 0.494064}, {β -> 0.472742},       {β -> 0.537485}, {β -> 0.478291},       {β -> 0.523855}, {β -> 0.483624},       {β -> 0.50126},  {β -> 0.527267}}      Which command could be used to find the mean of this data?


title: How to strip all formatting from a string and convert it to plain text?

text: The documentation on `String` states: ![Strings preserve internal formatting](http://i.stack.imgur.com/f0DA7.png) But if I try to perform some manipulations on this string, for example, take 2 words from the left, I get some shards of internal representation instead (which is understandable):               (* In[2]:= *) StringTake[%1, 8]     (* Out[2]= "\!\(\*\nStyl" *)      _Question:_ Is it possible to write a function which strips all formatting (colors, fonts, style, size, etc) from a string and returns just a plain text?


title: Replace inverse function

text: I'm solving an expression like so:               Solve[u[x] == u[a] + u[b], x]      Mathematica returns               {{x->(u^(-1))[u[a]+u[b]]}}      If I now specify the function `u` more precisely, via               % /. {u[x_] -> x}      what I get is               {{x->(u^(-1))[a+b]}}      i.e. Mathematica replaces the function but not its inverse. Is there any way of replacing the inverse appropriately as well?


title: when is f@g not the same as f[g]?

text: I have always thought that `f@g` will give the same result as `f[g]` in all cases, and it is just a matter of style which one to use and that `g` will always evaluates first, and then `f` will evaluate using the result of `g` evaluation. I never thought that there can be any precedence issue here, since no one ever mentioned it in all the times I have been using Mathematica. So I was really surprised when I found one case where this was not so. So my question is: How does one know when `f@g` is not the same as `f[g]` ? The help says nothing about this (thanks to chat room for giving me the link to this, I searched and could not find it) http://reference.wolfram.com/mathematica/ref/Prefix.html Even though one can see the word `precedence` and `grouping` but no explanation of where these are talked about and no more links to follow `Prefix[expr, h, precedence, grouping] can be used to specify how the output form should be parenthesized.` clearly this is a precedence issue. But I have never seen this mentioned before any where.               Tr[Times @@@ {{2, 3}, {4, 5}}]      ![Mathematica graphics](http://i.stack.imgur.com/YaTTM.png)               Tr @ Times @@@ {{2, 3}, {4, 5}}      ![Mathematica graphics](http://i.stack.imgur.com/cfoD2.png)               Tr @ ( Times @@@ {{2, 3}, {4, 5}} )      ![Mathematica graphics](http://i.stack.imgur.com/uNYZs.png) What seems to have happened is that in `Tr@Times@@@....` the command `Tr` grabbed `Times` before `Times` was applied. You can replaced `Tr` by `Total` also and see the same effect. ps. This is another reason for me to not use `@` too much. I I really never liked to use `@` and always liked the good old fashioned `[]` as it seems clearer also, and now safer also. **question is** : What is the rule(s) of thumb to use? One should always look ahead and check before using `@` to make sure precedence is met? Any other cases than this one might have to watch out for? If there are very few cases, may be one can add them to their cheat sheet. Where are the `precedence` of all operators listed so one can check?


title: Conditioned Probability Task

text: I have this task with two questions I would like to compute in Mathematica. > Suppose a pair of random variables $(X, Y)$ has a equal distribution on the > following 7 points: > > $\begin{matrix} & x & y\\\ 1 & -1 & 0\\\ 2 & 0 & 0\\\ 3 & 1 & 0\\\ 4 & -2& > 1\\\ 5 & 2 & 1\\\ 6 & -1 & 3\\\ 7 & 1 & 3 \end{matrix}$ > > The simultaneously probability function $p(x, y)$ is then given by: $p (1,0) > = \ldots = P (1, 3) = 1/7 \text{ and } p(x, y) = 0$ for all other points > > **1)** Find the conditional mean $E (Y\; |\; X = x)$ and the conditional > variance $V (Y\; | \;X = x)$ for $x = -2, -1,0,1,2.$ > > **2)** Compute the variance on Y and the variance on the conditional mean of > Y given X This additional information might help you:               E(X)=0     E(Y)=8/7      I have tried over and over but without any luck. Ps. I use Mathematica 8.


title: Converting this recursive function definition into nested sums?

text: Here's the recursive function I'm using:               DH[n_, k_, s_] := Sum[Binomial[k, k - j] DH[n/m^j, k - j, m + 1], {m, s, n^(1/k)}, {j, 1, k}]       DH[n_, 0, s_] := 1      Now, on paper, if I expand out the recursion of DH by hand, I know that               DH[n,1,1] == n.        I also know, expanding by hand, that               DH[n,2,1] == 2 Sum[Floor[n/k], {k, 1, Floor[n^(1/2)]}] - Floor[n^(1/2)]^2      Can Mathematica do that for me, especially for larger values (like, say, `DH[n,8,1]` or `DH[n,10,2]`)? I would like to type in `DH[n,2,1]` or `DH[n,3,1]` and get those sums, but right now, I just get a recursion depth exceeded error and no answers. * * * * * * **The following is a note, not part of the original question** Computing `DH[n,2,1]` by hand, For Mr. Wizard: _Here's our starting formula_               DH[n,2,1] = Sum[Binomial[k, k - j] DH[n/m^j, k - j, m + 1], {m, s, n^(1/k)}, {j, 1, k}]      _apply`s=1, k=2` and remove the `{j,1,k} Sum` by manually looping `j` from `1 to k`, with `k=2`_               DH[n,2,1] = Sum[ Binomial[2,1] DH[ n/m, 2-1,m+1 ] + Binomial[2,2] DH[n/m^2, 2-2, m+1],         {m,1,n^(1/2)}]      _apply binomials, simplify trivial arithmetic_               DH[n,2,1] = Sum[ 2 DH[n/m, 1,m+1] + DH[n/m^2,0,m+1], {m,1,n^(1/2)}]      _Swap in`DH[n,0,s] = 1`_                DH[n,2,1] = Sum[ 2 DH[n/m, 1,m+1] + 1, {m,1,n^(1/2)}]      _Inspection should make clear that`DH[ n/m, 1, m+1 ] is Floor[n/m] - (m+1) + 1`_               DH[n,2,1] = Sum[ 2 (Floor[n/m]-m) + 1, {m,1,n^(1/2)}]      _Distribute the`x2`_               DH[n,2,1] = Sum[ 2 Floor[n/m] - 2 m + 1, {m,1,n^(1/2)}]      _Extract the`1` from the sum_               DH[n,2,1] = Floor[n^(1/2)] + Sum[ 2 Floor[n/m] - 2 m, {m,1,n^(1/2)}]      _Use the triangle number formula`(n)(n+1)/2` to pull `-2 m` out of the sum as `-2 ( Floor[n^(1/2)] (Floor[n^(1/2)] + 1))/2`_               DH[n,2,1] = Floor[n^(1/2)] -2 ( Floor[n^(1/2)] (Floor[n^(1/2)] + 1))/2 + Sum[ 2Floor[n/m],      {m,1,n^(1/2)}]      _Cancel the`2s` outside the sum, and move the `2` inside the sum out front_               DH[n,2,1] = Floor[n^(1/2)] - ( Floor[n^(1/2)] (Floor[n^(1/2)] + 1)) + 2 Sum[ Floor[n/m],      {m,1,n^(1/2)}]      _Multiply the terms in parenthesis outside the sum_               DH[n,2,1] = Floor[n^(1/2)] - Floor[n^(1/2)]^2 - Floor[n^(1/2)] + 2 Sum[ Floor[n/m],         {m,1,n^(1/2)}]      _get rid of cancelling terms, and we are left with_               DH[n,2,1] = -Floor[n^(1/2)]^2 + 2 Sum[ Floor[n/m], {m,1,n^(1/2)}]      ...which is what I wanted to show. Check http://en.wikipedia.org/wiki/Divisor_summatory_function and you should see that is indeed the equations for D(n) when using the hyperbola method. That page mentions a generalized Divisor function, D_k(n). The k in that function corresponds to the k here - this recursive expression applies the hyperbola method to D_k(n) for any k, a whole number. By way of comparison, I have simplified `DH[x,4,2]` to               1 - Floor[x^(1/4)]^4 +       Sum[           4 (Floor[x/(u^3)] + Floor[Floor[x/u]^(1/3)]^3)           - 6 Floor[ Floor[x/(u^2)]^(1/2)]^2 +           12 (Sum [Floor[x/(u^2 s)], {s, (u + 1),        Floor[Floor[x/(u^2)]^(1/2)]}] +           Sum[Floor[x/( u s^2)] - Floor[Floor[x/(u s)]^(1/2)]^2, {s, (u + 1),         Floor[Floor[x/u]^(1/3)]}]) +           24  Sum[ Floor[x/(u m s)], {s, u + 1, (x/u)^(1/3)}, {m, s + 1, (x/(u s))^(1/2)}],        {u, 2, x^(1/4)}]      I haven't gotten up the gumption to go higher, as it's a bit exhausting to work through - thus my question.


title: Interpolating Function inside of NDSolve

text: I have a problem and it seems to be connected to an Interpolating function inside of an `NDSolv`e command. The `resistivity[x`] function inside the `NDSolve` command is an interpolation of measurement data. The code works fine with an ordinary function instead of the interpolating function. When I run the code, it does not give an error, but no results are displayed either. Does anybody know what the problem is? The code is:               xydataplot = Reap[          For[i = 1, i <= n, i++,            J = i j;            s =             NDSolve[{y'[x] == (resistivity[y[x]]  J^2)/nC              - alpha/nC (-T + y[x]), y[0] == T}, y, {x, 0, t}];            Te = y[t] /. s;            resis2 = resistivity[Te];            efeld = J resis2;            Sow[efeld];            Sow[J];            ];          ][[2, 1]]~Partition~2;


title: Piecewise of different functions

text: You know, NDsolve coupled with Piecewise can be used to solve a series of discontinuous differential equations. But what if one of the function is different? For example: $$z''(t)=\begin{cases}x(t)-(1+y(t)), & \text{if } x>(1+y) \\\ \\\ \\\ x(t)+(1+y(t)), & \text{if } x<-(1+y) \end{cases} $$ $$\rm{and}$$ $$z'(t)=0, \rm{if } |x|<(1+y) $$ I tried something like below               xyz = First@NDSolve[{x''[t] == -2.25 Cos[1.5 t] - x[t] - x'[t],      x[0] == 0, x'[0] == 0,      y''[t] == -1.125 Cos[1.5 t] - 4 y[t] - y'[t],      y[0] == 0, y'[0] == 0,      z''[t] == Piecewise[{         {x[t] - (1 + y[t]), x[t] > 1 + y[t]},          {0, Abs[x[t]] <= 1 + y[t]},          {x[t] + (1 + y[t]), x[t] < -1 - y[t]}}],      z[0] == 0},      {x, y, z}, {t, 0, 30}];      but have no idea how to correctly incorporate $z'(t)$ condition.


title: How to use a matrix variable for a compiled function

text: I want to compile the following function which takes a matrix variable.               ClusterFind =      Compile[{{Inte, _Real}, {Matrix}},      Map[If[Last@# == Inte, Take[#, 4]] &, Matrix], CompilationTarget -> "C",     RuntimeAttributes -> {Listable}, Parallelization -> True];      Here `Matrix` is a $m\times n$ matrix of real,integer or complex numbers. I also would like to know if it is possible to compile without knowing the dimension of the variable matrix beforehand. Can the `Matrix` in the above example be of `PackedArray` data type? **UPDATE** Thanks for the suggestions. I found the following compiled version most efficient as far as speed is concerned.               ClusterFind =      Compile[{{Inte, _Real}, {Matrix, _Complex, 2}},      Take[Select[Matrix, (Last@# == Inte) &], All, 4],      CompilationTarget -> "C"];      BR


title: MATLAB-like convolution and derivation using Mathematica

text: > **Possible Duplicate:**   >  Discrete Convolution I would like to be able to convolve two functions of two variables in Mathematica, and then plot derivatives (or functions of derivatives) of the solution. However, the result of the convolution is itself a function of two variables and in many cases there is no exact formula or it takes a very long time to compute. In Mathematica, is it possible to convolve two functions numerically (by this I mean compute g(x,y)*f(x,y) where x and y correspond to sets of data), obtain and take derivatives of the solution (also both sets of data)? I know the first answer will be "use MATLAB." I would prefer not to do this. If anyone has some example code where this has been done and is willing to share, I would be very grateful.


title: refer to result of cell above current cell?

text: `%` allows to refer to the result of the preceding calculation (preceding in time) but this seems not necessarily to be the cell just **above** a given cell. How can one refer to the result of the cell just above ?


title: Expand modulus squared

text: Is it possible to make a function in Mathematica that expands expressions of the form $$|z + w|^2 = |z|^2 + 2\text{Re} \overline{z}w + |w|^2?$$ Preferably it should also be able to handle things like $$\left |\sum_{i = 1}^n z_i \right |^2.$$ The last thing can obviously be mathematically deduced from the first one by consecutively applying the first equality.


title: How to use custom Dynamic inside Manipulate

text: I was wondering if it is possible to use a custom `Dynamic[var, function]` inside a `Manipulate`. The reason for the need is this: Suppose you have a time consuming computation like               timeConsuming[x_] := (Pause[1]; x)      and you want to use it in a `Manipulate`. Writing               DynamicModule[{y},      Manipulate[       y = timeConsuming[x]; {x, y, other},       {x, 0, 1},       {other, 0, 1}]      ]      entails the following issue: you have to wait for `timeConsuming` to be computed even when you change `other` and leave `x` unmodified. A (simple) solution is to code the dynamic by hand:               DynamicModule[{x = 0, y = timeConsuming[0], other = 0},      Panel@Column[{         Grid[{           {"x", Slider[Dynamic[x, (x = #; y = timeConsuming[x]) &], {0, 1}]},           {"other", Slider[Dynamic[other], {0, 1}]}           }],         Dynamic@{x, y, other}         }]      ]      This is feasible, but as a drawback makes you renounce all other `Module`'s conveniences. I tried coding something like               Module[(* result *), {x, 0, 1, some-suitable-function}]      but had no success in the attempt. A (clean) use of `Manipulate` would be much appreciated. Just to summarize, the question is: How can I make some statements be executed only when some specified controls are touched?


title: Solving a system of equations with conditions related to the number of solutions

text: The equation below describes a conic with oblique axis: $$9 + 22 x + 9 x^2 + 46 y + 24 x y + 16 y^2=0$$ It is a parabola, as the coefficients in $x^2$, $y^2$, $xy$ form a perfect square. To find the coordinates of its vertex, it's either the hard way using algebra only on paper (I summarise that at the end of my entry) or possibly an easy way with _Mathematica_.   Let me describe my _Mathematica_ approach: Looking at the $x^2$ and $y^2$ coefficients I know that the slope of the tangent to the parabola at its vertex is $4/3$ so this tangent is of the form $y = 4x/3 + b$ and it intercepts the parabola at its vertex $(x,y)$ exactly one time. When I translate this in _Mathematica_ terms, I have the following system of equations to solve:                {x, y, b} /.       Solve[{9 + 22 x + 9 x^2 + 46 y + 24 x y + 16 y^2 == 0,              y - (4/3)x - b == 0}, {x, y, b}]      which is not enough of course to find unique values for $(x,y,b)$.   Is it possible to add conditions to the above `Solve` expressions such as only one solution for $(x,y,b)$ is to be returned (or more exactly as there are squares in the expression) two solutions but identical?. On paper, I transformed with factors the equation of the parabola. End result put into _Mathematica_ :               eq1 = (3 x + 4 y + 5)^2  - 2 (4 x - 3 y + 8)       eqc = 9 + 22 x + 9 x^2 + 46 y + 24 x y + 16 y^2     eqc == eq1 // FullSimplify     tangentvertex = Reduce[4 x - 3 y + 8 == 0, y]     vertex = {x, y}/.Solve[{eqc == 0, y - 8/3 - (4 x)/3 == 0}, {x, y}] // FullSimplify      Vertex coordinates at last: > `{-47/25, 4/25}` Thanks for any answer.


title: Calculating the rank of a huge sparse array

text: By virtue of the suggestion in my previous question, I constructed the sparse matrix whose size is $518400 \times 86400$, mostly filled with $0$ and $\pm 1$. Now I want to calculate its **rank**. Since `RowReduce` requires a huge amount of memory to fill in $0$s, my first approach was to divide the matrix into many parts, e.g., each containing 144 rows ($144\times 86400$).               Module[{i, part, rank},      For [i = 0, 144 (i + 1) <= 518400, i++,        part = RowReduce[input[[144*i + 1 ;; 144 (i + 1)]]];        rank = MatrixRank[part];        If[i == 0, result = part[[1 ;; rank]],          result = Join[result, part[[1 ;; rank]]]]        ];      ]      Unfortunately, this does not work because all rows in each part are linearly independent so that the number of rows does not decrease. Does anyone have such an experience? Should I export the matrix to the file and calculate its rank via other language / packages? If so, any suggestion?


title: Elegant solution to the Zebra [logic] Puzzle ("Einstein's Riddle")

text: The famous Zebra Puzzle (Wikipedia), often called "Einstein's Riddle," is a logic puzzle that can be solved deductively by applying a list of logical rules. One version of the riddle (from Wikipedia) begins: >   1. There are five houses. >   2. The Englishman lives in the red house. >   3. The Spaniard owns the dog. ... > The idea is that there are five houses, painted different colors, with occupants (one in each house) of different nationalities each of whom smokes a different brand, drinks a different beverage, and keeps a different pet. Given the "clues," the puzzle asks which resident owns the zebra. Given that Mathematica is a rule-based language, it seems that there should be a way of solving the puzzle without resorting to brute-force (i.e. while loops or searching). Can Mathematica be used to elegantly deduce the solution? How?


title: Can I put subscripted parameter values into a package?

text: When defining packages, can I put parameter values alone or along with functions into a package in subscripted form?               BeginPackage["Myfunction`"];      Subscript[q, 1] = 0;     Subscript[q, 2] = 0.5;     myfunction::usage ="...";     Begin["`Private`"];     myfunction[ak__List] := blablabla...;     End[];     EndPackage[];      Because these global subscripted parameters in the package are needed in many programs, I separated them from the main programs and put them into a single package. In the main programs, I only need to load the package rather than bothering to redefine these parameters again. For plain symbols, it works fine. But whem it comes to subscripted symbols, it fails. And I found that is because I used                 Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]];      in the main program. subscripted symbols like                 Subscript[q, 1]       are transformed into                 q_Subscript_1      I also tried to use Symbolize function in the package, but it fails. The clarity for using subscripted symbols made me reluctant to avoid them.


title: Triangle mapped on a sphere in $\mathbb R^3$?

text: How can I map a triangle on an sphere? I want to visualize (plot or animate) it for my student in my Non Euclidean geometry. I have no restrictions on the triangle's kind or on the sphere in $\mathbb R^3$. Thanks for any hint.


title: DSolve does not solve my system of PDEs

text: I am a long time Maple user who had just recently got hands on _Mathematica_. I have a "simple" system of PDEs, one can be solved easily. But I cant seem to get it work in _Mathematica_. I am nos sure whether I'm having a synatex problem or it's just not doable in _Mathematica_.               FF = f[a, b, c, d]          eq1 = D[FF, d] + (1 - a)*D[FF, a]/d == 0          eq2 = D[FF, c] + (b - (a - 1)*d)*D[FF, a]/(c*d) == 0          eq3 = D[FF, b] + D[FF, a]/d == 0          DSolve[{eq1, eq2, eq3}, {FF}, {a, b, c, d}]      ![Mathematica does not work](http://i.stack.imgur.com/SL7pI.png) Tried using different parameters to avoid the double subscript ![Tried using different parameters to avoid the double subscript](http://i.stack.imgur.com/CyHVM.png) Here is how it works in Maple: ![Maple works fine](http://i.stack.imgur.com/63Em1.png) Thanks The Mathematica Notebook is here Mathematica NB


title: Limit the output of financial indicators list

text: Imagine I have a list of Forex data as below:               data= {{"2014 06 30  07:49", {1.36535, 1.36525, 1.36543, 1.36542, 81}},             {"2014 06 30  07:50", {1.36543, 1.3654, 1.36545, 1.36544, 25}},             {"2014 06 30  07:51", {1.36544, 1.36544, 1.36562, 1.36552, 116}}      The list has different sizes in different case. Then using `FinancialIndicator["WildersMovingAverage", i][data]` you can get a list of `WildersMovingAverage` given period `i`. The output of this function is a list. My question is how one may limit the function in order to just compute the value of `WildersMovingAverage` for last data point and not to compute the whole list which is time consuming when the list is huge?


title: Multi-Camera streaming using Mathematica

text: I am attempting to capture dynamic streams from multiple usb webcams using only mathematica. Using `ImageCapture["Device" -> $ImagingDevices[[x]]`, I've tried to open multiple instances of _Mathematica_ using ImageCapture on different devices for the different instances. No Luck :( Is this too complex a task for _Mathematica_ alone?) Wolfram Community related question link


title: Replacing matrix values

text: I want to find the n largest values in a matrix and replace all others with zero. The solution I found uses `ReplaceAll` and becomes very slow as the size of matrices grows:               FindLargestValues[m_?MatrixQ, n_Integer] :=       With[{v = (Union @ Flatten @ m)[[-n]]},         m /. x_Real /; x < v :> 0]      Example:               (small = RandomReal[{1, 10}, {5, 5}]) // MatrixForm      ![enter image description here](http://i.stack.imgur.com/Sb5tz.jpg)               FindLargestValues[small, 10] // MatrixForm      ![enter image description here](http://i.stack.imgur.com/xGhvU.jpg) Timing example:               large = RandomReal[{1, 10}, {50, 50}];          Do[FindLargestValues[large, 50], {1000}]; // Timing // First      > 2.574016 Is there a faster way to do this?


title: What is the default ColorFunction for 3D plots?

text: This should be a really simple question, but it isn't in the documentation for some perverse reason. I like the default `ColorFunction` that _Mathematica_ uses for `Plot3D` and the like. I'd like to use the same color scheme for other _Mathematica_ plots that don't have it as the automatic default. However, after looking through all of the Color Gradients listed by `ColorData["Gradients"]` I can't find any that match the effect of just setting `ColorFunction->Automatic`. My question: What does _Mathematica_ call its default color palette, why isn't it listed in `ColorData`, and how can I access it to apply it to other plots?


title: ParametricPlot with DSolve does not show anything

text: I manage to plot strn[t] and sig[t] where sig[t] is the solution from my DSolve. However, when I want to ParametricPlot sig[t] vs strn[t], I failed to do it as the parametric plot does not show anything.               strn[t] = t*0.00025;     modulus = 20000;     sol1 = DSolve[{D[strn[t], t] == D[sig[t], t]/modulus, sig[0] == 0}, sig[t], t]     Plot[strn[t], {t, 0, 100}]     Plot[sig[t] /. sol1, {t, 0, 100}]     ParametricPlot[{sig[t] /. sol1, strn[t]}, {t, 0, 10}]      Can someone please tell me why?