Skip to main content

Posts

Showing posts from May, 2017

matrix - Time-efficient manipulation (zeroing) of expression

I have huge matrices in the form of mtx1 = {{24+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8]},{24+24 FF[5,10] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[7,8] ...

plotting - Calculating volume between two surfaces of revolution

Once again, I'm very new to Mathematica and winging it as I go. I probably don't have the math education at this point to even justify buying it in the first place, but that's off topic. I wanted to model a simple curve by rotating it around the x axis, and then actually use it as a function and take its integral, etc. To be more specific, all I want to do is rotate the area enclosed by y == 10 - 6 x + x^2 and y == x around the x axis to get a 3D model and calculate its volume. However I either can't find the related Help topic, or did find it but found that it so quickly jumped from the basic explanation to complicated examples that I couldn't understand it, something I'm finding more common. Does anyone have any advice? Sorry if this question is too obvious or dumb. EDIT: Oops, my mistake, the function I was trying to plot was 10 - 6 x + x^2 with a negative 6x. This way y=x intersects it and what's being plotted, assuming the bounds are 2 to 5, is just...

plotting - Graphics plot of point using unfilled circle

I'd like to be able to place points on a plot using Graphics[{Point[{a,b}],....}] but have the plot symbol be an unfilled circle. I've looked around but can't find any way of doing this. Is there one? Thanks. After reading the first response, perhaps I should add a bit more. I'd like to be able to do the following: p1 = Plot[x^2,{x,-3,3}] p2 = Graphics[Style[Point[{0,0}],PointSize[Large]] Show[p1,p2] but with an unfilled circle instead of a dot. The solution proposed in the first answer falls short in two ways: first, the unfilled circle does not properly hide graphics elements underneath it; second, the circle will appear as an ellipse, not a circle, in the (likely) event that the underlying graphic does not have aspect ratio 1. The application here is for plotting piecewise discontinuous functions and showing clearly which endpoint at a jump discontinuity holds the value at the point. Answer The purpose of the circles is to mark discontinuities, but if I understand...

matrix - Taking the product of a list of matrices

Suppose I create a list of matrices: data = Table[RandomInteger[5, {2, 2}], 5] Which produces: {{{0, 5}, {2, 1}}, {{5, 2}, {2, 1}}, {{4, 4}, {0, 1}}, {{5, 3}, {2, 5}}, {{2, 0}, {5, 0}}} How can I quickly take the product of these five matrices? Answer Dot@@data should do what you're looking for. It replaces the main Head , List , with Dot , which just multiplies all of the matrices—which used to comprise the List data—together. data = Table[RandomInteger[5, {2, 2}], 5]; MatrixForm /@ data Dot @@ data // MatrixForm

Output is Input for a Differential with Sign?

Here's the problem: For one of my classes, we're supposed to use Mathematica to solve the equation y''=y-b*y' for a variety of b values and specified boundary conditions and plot the outputs. There I have no problem and Mathematica runs well. However, the next problem is to replace the -b*y' with -b*sign(y') and repeat part one. When I do this, Mathematica runs for a long time, then gives up and outputs the input. I tried removing the boundary conditions and just doing the general solution, but it can't figure that out, either. It isn't giving any errors, it just doesn't work. Any ideas? This is what my input looks like: In[5]:= beta = 0.2; Solution = DSolve[{y''[x] == - y[x] - beta * Sign[y'[x]], y[0] == 1, y'[0] == -1}, y[x], x] Out[6]= DSolve[{y''[x] == -0.2 Sign[y'[x]] - y[x], y[0] == 1, y'[0] == -1}, y[x], x] Answer Try to solve the problem numerically beta = 0.2; As you have observed, the problem ...

list manipulation - Confused about how Partition works

I have a problem about the padding list about Partition command. For instance, Partition[{a, b, c, d, e, f, g}, 3, 1, {-2, 1}, {x, y, z}] {{z, a, b}, {a, b, c}, {b, c, d}, {c, d, e}, {d, e, f}, {e, f, g}, {f,g, y}, {g, y, z}} However, my understanding about padding list shown as below: Another example Partition[{a, b, c, d, e, f}, 3, 3, {1, 1}] {{a, b, c}, {d, e, f}} My understanding: Question Can someone give me a good explanation? Answer Example #1 Let me make your example a bit smaller for brevity: Partition[{a, b, c, d}, 3, 1, {-2, 1}, {x, y, z}] {{z, a, b}, {a, b, c}, {b, c, d}, {c, d, y}, {d, y, z}} This is in effect: PadRight[{a, b, c, d}, 7, {x, y, z}, 1] Partition[%, 3, 1] {z, a, b, c, d, y, z} {{z, a, b}, {a, b, c}, {b, c, d}, {c, d, y}, {d, y, z}} Think instead: + Equals Example #2 The documentation states: Critical to your example is: "appear at or after position k R in the last sublist." Therefore in this case it does not matter if k R is any of: 1 , 2...

graphics - Text[] with offset not positioned correctly in M11.1 and M11.2

Bug introduced in 11.1 and persisting through 11.3 When the first argument of Text is a Graphics , and the third argument (offset) is used, positioning is incorrect in M11.1 and M11.2. Mathematica 11.0 behaves correctly. Example: inset = Graphics[{Circle[{0, 0}, 2]}, Frame -> True, FrameTicks -> None, ImagePadding -> 1, PlotRangePadding -> None, ImageSize -> 90] figure = Graphics[ {Text[inset, Scaled[{0.5, 0.5}], {1, 1}]}, PlotRange -> {{0, 1}, {0, 1}}, Frame -> True, GridLines -> {Range[0, 1, .1], Range[0, 1, .1]}, ImageSize -> 360 ] (This is wrong) With the {1,1} offset, the upper right corner of the inset should line up with the middle of the plot range in the enclosing figure. In Mathematica 11.0 we get the expected output: In M11.1 and 11.2 we also get a correct positioning if the inset is a general notebook expression instead of a Graphics . We can, for example, wrap it in Framed to achieve this. figure = Graphics[ {Text[Framed[inse...

programming - How can I overload a function with multiple bracket-slots so f[a][b] and f[a] can coexist?

Maybe this is not even possible: I want to create a function f that can have two input brackets like: f[a_][b_:1]:= a*b and alternatively just one input bracket: f[a_]:= a But with overloading the definitions the second definition interferes with the first definition, because the pattern f[a_] is replaced in a expression like: In: f[2][3] Out: 2[3] with the result of f[2] (in this case) Of course, I could use just one bracket slot like f[a_,b_:1] , instead of f[a_][b_:1] , but thats not the point. So i am asking for an optional bracket slot. Is that possible? (BTW, I dont know the correct name of the []-Pattern, and called it bracket slot) Answer In the Standard Evaluation Sequence the heads of expressions are evaluated first: If the expression is a raw object (e.g., Integer, String, etc.), leave it unchanged. Evaluate the head h of the expression. Evaluate each element of the expression in turn ... Therefore since f[1] is the head of f[1][2] it will evaluate if it has a definiti...

UNIX time to DateList

I have data that is timestamped with UNIX time, which is the number of seconds since January 1, 1970 UTC. Unfortunately, it seems that most of the date and time functions in Mathematica are based on the system's local time zone. How can I convert a UNIX timestamp to a DateList in UTC? Answer Since Mathematica version 10.1 there is the function FromUnixTime that performs the conversion from a UNIX timestamp to a DateObject . FromUnixTime[1427793986] FromUnixTime[1427793986] // DateList {2015, 3, 31, 11, 26, 26.} FromUnixTime[0, TimeZone -> 0]

plotting - Switching parameter lines on/off in a 3D parametric plot

In a classroom demonstration for ParametricPlot3D [{f[u, v], g[u, v], h[u, v]}, {u, ... }, {v, ... }] I want to show u lines only without v, v lines only without u, no lines, only surface, no surface, only u, v lines. How can it be done? Answer Manipulate[ ParametricPlot3D[ {Cos[u], Sin[u] + Cos[v], Sin[v]}, {u, 0, 2 \[Pi]}, {v, -\[Pi], \[Pi]}, Mesh -> {If[uMeshOn, uMesh, 0], If[vMeshOn, vMesh, 0]}, Boxed -> boxed, Axes -> boxed, PlotStyle -> pltStyle], Row[{ Control[ {{uMesh, 15, "u Mesh"}, 0, 36, 1, Appearance -> "Labeled", ImageSize -> Small}], Spacer[5], Control[ {{vMesh, 15, "v Mesh"}, 0, 36, 1, Appearance -> "Labeled", ImageSize -> Small}]}], Row[{Control[ {{uMeshOn, True, "u Mesh"}, {True, False}}], Spacer[20], Control[ {{vMeshOn, True, "v Mesh"}, {True, False}}], Spacer[20], Control[ {{pltStyle, Automat...

plotting - Solving a differential equation involving the square of the derivative

I want to solve the differential equation $$\left( \frac{dr}{d\lambda} \right)^2 = 1-\frac{L^2}{r^2} \left( 1-\frac{1}{r} \right)$$ where $L$ is some parameter. The behavior I am looking for is when $r$ starts "at infinity" at $\lambda=0$, reaches some minimum $r$, and increases out to infinity again. (I'm trying to describe the path that light takes in the presence of a Schwarzschild black hole.) The issue I'm running into is when I use ParametricNDSolve, I can't tell Mathematica to smoothly transition from negative $dr/d\lambda$ to positive $dr/d\lambda$ after reaching the minimum $r$. f[r_]:=1-1/r; soln = ParametricNDSolve[{r'[\[Lambda]]^2 == 1 - L^2/r[\[Lambda]]^2 *f[r[\[Lambda]]], r[0] == 1000}, r, {\[Lambda], 0, 1000}, {L}] Plot[r[30][\[Lambda]] /. soln, {\[Lambda], 0, 1000}] In the above code, it plots the graph fine. However if I try to increase the range of $\lambda$ (say to 1200), it breaks down; the situation where I solve for $r'(\lambda)$ firs...

graphics - LocatorPane, selecting multiple Locators

Consider the following snippet pts = RandomReal[1, {3, 2}] g = Graphics[{Polygon[Dynamic[pts]]}, PlotRegion -> {{0, 0}, {2, 2}}]; Panel[LocatorPane[Dynamic[pts], g]] I would like to be able to drag the triangle as a whole. I found none and assume this has to be added via code, i.e. EventHandler but found no examples of this. Question: How can I select, and act upon multiple locators, i.e. drag, scale, apply a transformation to the points? Answer Here's one way to do it. In this example I've used one list of points for the vertices of the two shapes. The inner EventHandler sets the flag drag which indicates which shape should be moved. The outer EventHandler actually moves the shape. Releasing the mouse resets drag to 0 again. I'm using PassEventsDown -> True in the outer event handlers to make sure that the mouse events are handed over from outer to the inner event handlers. DynamicModule[{pts, range, gr, drag, pts0}, pts = RandomReal[1, {7, 2}]; range...

list manipulation - How can I know the length of each part of the arrow and what their full length?

How can I know the length of each part of the arrow and what their full length? points = {{6, 32}, {9, 53}, {18, 42}, {32, 51}}; Graphics[{Arrow[points]}] Answer You can know the length of each part of the arrow and his full length in this way: distList = EuclideanDistance[points[[# + 1]], points[[#]]] & /@ Range[Length[points] - 1] // N Plus @@ distList {21.2132,14.2127,16.6433} 52.0692

variable definitions - `Quit` vs `ClearAll["Global`*"]`

Quit erases all the definitions (by quitting the kernel), but so does ClearAll["Global`*"] (or other contexts). What's the difference in terms of variables in the notebook? Answer There are significant practical differences. Quit does not "clear" anything, it instead restarts the kernel, i.e. resets it to the default state. There is a lot of internal state that changes during the session in ways that are different from creating new symbols or attaching definitions. So simply clearing (or removing) symbols won't reset the kernel. Examples include: When you load a package, it does not only create its own context, it also causes $Context and $Packages to be modified Symbolic results are cached ( ClearSystemCache ) and will actually cause symbolic processing functions to return different results than they would in a fresh session. $ModuleNumber changes Directory[] changes pseudo-random number generator states change (and this also involves caching behin...

interoperability - Running PowerShell commands in Mathematica

I'm trying to execute a PowerShell command using Mathematica . Someone has made it before? I tested my command direct in PowerShell, and it worked nice, but no idea on how can I make Mathematica to call it. Here is a related answer dealing with scripts. Maybe the new RunProcess can be a nice new function to handler that, and I could better collect the prompted results. Here is the command I want to execute: git -C C:\somePath pull ssh://git@github.com/myaccount/myProject.git A better toy command is welcome...

list manipulation - Fitting multiple peaks

I am using the code found here to fit multiple peaks of a large dataset which I don't know anything about. This was the only code I could find on the internet to do such a thing. So this is my attempt (it is pretty much the same code with the beginning deleted and a residual plot added) of a certain dataset and the results are good, it gets the correct number of peaks and it works. However when trying it with a larger dataset, and the one I actually need to analyze, the code fails (it gives a lot of errors). I am guessing there is only a small technical error in the code or dataset somewhere. This is the dataset I need to analyse. That data was made by importing a text document and transposing it with integers. The data: data = Uncompress@Import["http://pastebin.com/raw.php?i=hkhuyvza"]; Peak function: peakfunc[A_, μ_, σ_, x_] = A^2 E^(-((x - μ)^2/(2 σ^2))) Model: Clear[model] model[data_, n_] := Module[{dataconfig, modelfunc, objfunc, fitvar, fitres}, dataconfig = ...

How to stop optimization (e.g. NMinimize) after reaching target value

Suppose we have some function f[x,y] that we want to optimize in way that we are only interested in values (x,y) that guarantee our function value is below some value target . See the following MWE: f[x_, y_] := f[x, y] = x^2 - 4*x + y^2 - y - x*y; findMin[target_, steps_] := Block[{nbr = -1}, solsOpt = NMinimize[ f[x, y], {x, y}, Method -> "NelderMead", (*EvaluationMonitor:>{nbr += 1; If[Mod[nbr, steps] == 0, Print["Step: ", nbr," ; Current value: ",f[x,y], " ; parameters: ",{x,y}],Print]}*) EvaluationMonitor :> {nbr += 1; If[Mod[nbr, steps] == 0, Print["Step: ", nbr," ; Current value: ", f[x, y], " ; parameters: ", {x, y}], Print] || If[f[x, y] ]; Print["Number of iterations: ", nbr]; Print["Final value: ", solsOpt[[1]]]; Return[solsOpt]; ] Of course findMin[-5,1] stops after a few iterations and I can read the values (x,y) that satisfy my criterion....

core language - Implementing key-value associations in Mathematica 9 with inexact numbers for keys

I'm not sure of what type of problem my issue falls into, so I haven't been able to search forums with any success. If this has already been solved then my apologies! Essentially I'm trying to set a list equal to a calculated value then call that list back. -15*0.1 + 6*0.1 (* -0.9 *) -15*0.1 + 6*0.1 == -0.9 (* True *) a[-15*0.1 + 6*0.1] = 5 (* 5 *) a[-0.9] (* a[-0.9] *) a[-0.8999999999999999`] (* 5 *) I've reset Mathematica 9.0.1.0 according to this guide http://support.wolfram.com/kb/3274 to no avail. Answer It would seem from the title that the OP is asking not only why the scheme does not work but also how to implement it. Three solutions, each with drawbacks, are given below. An obstruction Others have given an explanation why it doesn't work. I would add that it is also pointed out in the documentation for Equal in the Details section and under Possible Issues that the tolerance for Equal in comparing approximate machine numbers is the last seven bits (...

plotting - How does Plot work?

I considered the following function: sin[x_] := Module[{}, Print["x=", x]; Sin[x] ] in Mathematica . Next, I tried to plot it using: Plot[sin[t], {t, 0, 2 Pi}] Surprisingly, the first three lines of output are: x=0.000128356 x=t x=1.28228*10^-7 Can someone explain this behavior? In this case it doesn't cause a problem, but in my "real" case it does. Summary acl's answer below offers, at its very beginning a solution to the specific problem. In very-short, the reason that this x=t appears is hidden somewhere in the way Mathematica evaluates the functions. The answers below provide interesting insight into the way it works. The interested reader should read all the answers and details below, they are invaluable, although might be behind the reach of some of the readers (like, partially, in my case). Answer If the problem is that a symbolic argument is passed, you can avoid it thus: ClearAll[sin]; sin[x_?NumericQ] := Module[{}, Print[x]; Sin[x] ]...

pattern matching - Why can't I replace I with HoldPattern@I?

Just try this sample: I /. HoldPattern@I -> a (* I *) Why does it fail to replace I with a ? I've checked // Hold // FullForm but found nothing useful. Answer @xzczd has always struck me as a very mature person, and this question hasn't really changed that opinion :-) The answer is because I evaluates internally as Complex[0,1] , so I /. HoldPattern[Complex[0, _]] -> a would work, or even I /. HoldPattern[Complex[0, 1]] -> a and in a more practical example, FourierTransform[f[tt], tt, I ww] /. HoldPattern@FourierTransform[a_, t_, Complex[0, 1] w_] :> myfourier[a, t, J w] (* myfourier[f[tt], tt, J ww] *)

replacement - Continuous substitution of one equation into another and summarizing terms

I have the following equations where I need to lag and substitute one equation into another back and forth to obtain equation 1 expressed in terms of $i_{t-2}$, $i_{t-3}$ and earlier. $x_{t}=a_{0}+a_{1}x_{t-1}+a_{2}y_{t-1}+\epsilon_{t} \quad (Eq. 1)$ $y_{t}=b_{0}+b_{1}y_{t-1}+b_{2}i_{t-1}+\eta_{t} \quad (Eq. 2)$ e.g. {x[t]->a[0]+a[1] x[t-1] + a[2] y[t-1] + \[Epsilon][t], y[t]->b[0]+b[1] y[t-1] + b[2] i[t-1] + \[Eta][t]} I look for an automated way to the following steps that I am able to manually, yet. Step 1) Lag equation 2 once and substitute it into equation 1 to get: $x_{t}=a_{0}+a_{1}x_{t-1}+a_{2}(b_{0}+b_{1}y_{t-2}+b_{2}i_{t-2}+\eta_{t-1})+\epsilon_{t}$ where rearranging the terms give $x_{t}=a_{0}+a_{2}b_{0}+a_{1}x_{t-1}+a_{2}b_{1}y_{t-2}+a_{2}b_{2}i_{t-2}+\epsilon_{t}+a_{2}\eta_{t-1} \quad (Eq. 3)$ Step 2) As $x_{t-1}$ is a function of $y_{t-2}$, we substitute it in equation 3 to obtain: $x_{t}=a_{0}+a_{2}b_{0}+a_{1}(a_{0}+a_{1}x_{t-2}+a_{2}y_{t-2}+\epsilon_{t-1})+a_{2}b_...

performance tuning - Memory usage optimization for a large Association/SparseArray

Reformulating my question in simpler terms. Take two lists list1 = RandomInteger[{1, 100000000}, 25000000]; list2 = RandomReal[{1, 10}, 25000000]; Make an Association out of them as = AssociationThread[list1, list2]; Export["somewhere", as, "WDX"];) And I want to do this for even larger lists. At the moment I can't manage it - the reason being that Mathematica eats all my RAM. I have noticed that when I try creating the Association there is a spike in RAM usage (in steps of a few hundred Megabytes). If a make the lists a bit smaller, so that the command can be evaluated, after the spike is gone, I can go on using as in other calculations with far less RAM being taken. This spike in memory usage is also seen when I Import the exported file (the file is around 200mb). My question is whether it is possible to avoid this somehow - maybe create (and later Import ) the Association in pieces or something else? I also tried using a SparseArray instead, replacing ...

polynomials - What is the inverse of CoefficientList?

I have numbers in vector notation. I need to get polynomial notation from them. My numbers are {0, 1, 23, 5, 15, 0, 0, 0} . I want to get $x + 23x^2 + 5x^3 + 15x^4$ from this list. How can I get that polynomial? Answer One straightforward approach is to calculate the answer directly: Total[{0, 1, 23, 5, 15, 0, 0, 0} x^(Range[8] - 1)]

plotting - How to visualize slope fields of differential equations without vectors?

I'm looking to visualize slope fields of differential equations for my differential equations course. Every example I see draws them as vectors, adding unnecessary "arrows" that, to me, are visually distracting. Is there a way to plot these slope fields without the "arrows" that get in the way? Answer You can use the options VectorScale and VectorStyle of VectorPlot . To create the slope field for the first order equation $y'=f(x,y)$, I usually do something like so. f = Exp[-x] - y; VectorPlot[{1, f}, {x, -2, 2}, {y, -2, 2}, VectorScale -> {0.03, Automatic, None}, VectorStyle -> {Gray, Arrowheads[0]}]

numerics - Arbitrary-Precision Arithmetic behaves unexpectedly

I want to understand how small numerical errors propagate through a computation and may drastically change the final result. To this end, I consider a toy world in which every number is limited to exactly 5 significant digits. The output of $MaxPrecision = 5; $MinPrecision = 5; x = SetPrecision[10^(-10), 5]; x // FullForm y = 1 + x; y // FullForm y - 1 // FullForm is 1.`5.*^-10 1.`5. 1.`5.*^-10 The last line puzzles me. The FullForm of y shows that the Precision of 5 significant digits is not sufficient to resolve the small deviation x from 1 . However, y - 1 still yields the exact result, instead of y - 1 = 0 . If one writes explicitly 1.`5. - 1 // FullForm this yields, of course, 0 as it should. Does this mean that FullForm[y] hides something?

numerics - Eisenstein Series in Mathematica?

Mathematica doesn't seem to have built-in tools to deal with the Eisenstein series: $$\begin{align*} E_{2}(\tau)&= 1-24 \sum_{n=1}^{\infty} \frac{n e^{2 \pi i n \tau}}{1-e^{2 \pi i n \tau}}\\ E_{4}(\tau)&= 1+240 \sum_{n=1}^{\infty} \frac{n^{3} e^{2 \pi i n \tau}}{1-e^{2 \pi i n \tau}} \end{align*}$$ I'm wondering what is the best way to deal with this. Just messing around, informally, on Wolfram, it seems like these series all converge pretty fast. Can I carry out the sums manually in Mathematica including a small number of terms? Or is there a better way? I'm worried this is prone to severe inaccuracy for $\Im(\tau)$ either large or small, both cases I'm interested in. If it simplifies anything, I only need the cases $\Re(\tau) \in \mathbb{Z}$ where the series outputs real numbers. Answer Since EllipticTheta[] is a built-in function, and since the Eisenstein series $E_4(q)$ and $E_6(q)$ are expressible in terms of theta functions (I use the nome $q$ as the...

hold - Pure functions are not functions?

According to the manual: "HoldAll is an attribute which specifies that all arguments to a function are to be maintained in an unevaluated form." The following code yields, as expected, g[2,3] in Mathematica v9.01. SetAttributes[f, HoldAll]; f[x_] := g @@ Unevaluated[x]; f[2 3] When the function given the HoldAll attribute is defined as a pure function, the argument is evaluated despite the HoldAll attribute. SetAttributes[h, HoldAll]; h = g @@ Unevaluated[#] &; h[2 3] The above code returns 6 because the 2 3 multiplication is evaluated before being fed to h (use Trace to confirm the order). 1) Is the above behavior a bug or should it be considered a "documented feature"? 2) Is the above behavior consistent across Mathematica versions? Answer A response to this comment: I understand that there are workarounds. I am wondering whether I am misinterpreting the manual. Yes. The use of the word "function" in the manual may be confusing here. It is s...

notebooks - Overwrite contents of a cell

I am trying to figure out a way to change the contents of a cell that has previously been evaluated in my notebook. To do this, I'd like to overwrite the cell. I've seen questions like How to pipe a stream to another notebook? and How do I direct output to a specific notebook or cell? and so far they have not helped me accomplish this. NotebookApply[cell, data] The above is supposed to write data to the specified cell, but I haven't had any luck with this, I'm most likely incorrectly identifying the cell. The most promising example I've seen so far has been this from the CellObject page: Do[CellPrint[ Cell["1", "Output", ShowCellTags -> True, CellTags -> "overwrite" ToString[i]]], {i, 1, 3}]; obj = Cells[CellTags -> "overwrite2"][[1]]; NotebookWrite[obj, Cell["2", "Output"]]; But I don't really understand what it's doing, and I don't understand how to adapt it to suit m...

map - Element-wise test on List elements

This question could sound pretty silly but I can't find a way to apply element -wise tests to a list. For example if I digit {0.6, 1.2}>1 {{0.6,1.2},{5,0.1}}>1 I would expect to obtain {False,True} {{False,True},{True, False}} respectively, but it is not the case. Of course I can define a function or using Map , but I can't believe there is not a core function providing this kind of result. Thank you for any indication Answer To my knowledge, there aren't built-in versions for comparison operators that would be automatically threaded over lists. One reason for that is that Mathematica is a symbolic system, and every auto-simplification has a cost, because there may be cases when this isn't desirable. It is relatively easy however to construct the behavior you want: ClearAll[l]; l[f_] := Function[Null, f[##], Listable] Now, you can call: {{0.6, 1.2}, {5, 0.1}} ~ l[Greater] ~ 1 (* {{False, True}, {True, False}} *) and similarly with other comparison operations. No...

mathematical optimization - Find the maximum Z in {(X + Y)==Z} using all the digits 0-9 only once

II want to add two integers with different digits to get a third integer with different digits. At the end, all 10 digits have to be different. So there should be 10 digits in total. How you distribute them is your (or Mathematica's ) decision. Lets say these numbers are $X$, $Y$ and $Z$, so that $X + Y = Z$. There is no rule how many digits a number should have. For example $X$ can have two digits or it can have three digits. What is the maximum possible value for $Z$? How can I tell Mathematica to chose such two numbers in order to get a third one which satisfies the conditions I impose above? Please explain your answer in simple terms. I am a beginner, and I want to understand the code in the answer so I could do it on my own at some later time. Answer Brute forcing it: (The edit at the end is a much faster alternative) n = 9; IntegerPartitions[n + 1, {3}] (* {{8, 1, 1}, {7, 2, 1}, {6, 3, 1}, {6, 2, 2}, {5, 4, 1}, {5, 3, 2}, {4, 4, 2}, {4, 3, 3}}*) are the ways to split t...

front end - How to Enable Syntax Coloring of Pattern Match Variable Only (i.e. Without Coloring any Associated Pattern)?

Syntax coloring for the following function definition foo[x_List] := ... will color green (and italicize by default) the argument name x as well as the pattern name _List : On the other hand, syntax coloring for foo[x:_List] colors only the identifier x green and not the _List qualifier: Is there a way to configure the front end to color just the identifier name as in the second example? Looking through the Option Inspector, I cannot find any relevant switches, so I suspect not. I do wonder however if this behavior is a bug or a feature whose purpose I don't fully understand. EDIT: The remaining issue in this question is the following: The syntax coloring rule which specifies that function argument names should be colored green in the body of the function in which these names are bound also colors green any head to the right of the underscore that is present for pattern matching purposes. In what sense is the underscore itself and any head that is attached to it part of the fun...

plotting - BarChart frame labels

This barchart was tricky to style, and I had to resort to the legacy BarCharts` package. Any ideas how to omit the labels from the bottom edge? Ideally I'd also like separator ticks between the column pairs. data = {{-2.8, -5.8, -7.4, -9.2}, {-3.7, -6.8, -8.9, -11.8}}; colour1 = RGBColor[82/255, 85/255, 255/255]; colour2 = RGBColor[132/255, 178/255, 255/255]; Quiet[Needs["BarCharts`"]] BarChart[data, Frame -> True, AxesOrigin -> {0, 0}, PlotRange -> {{0.525, 4.825}, {-14, 0}}, BarLabels -> {"March", "June", "September", "December"}, BarGroupSpacing -> 0.3, BarSpacing -> 0, BarStyle -> {colour1, colour2}, BaseStyle -> {10, FontFamily -> "Verdana"}, AspectRatio -> 0.4, ImageSize -> 350] Answer Just some fun seeing how well I can dial it in by eye: BarChart[Thread @ data, ChartStyle -> {colour1, colour2}, ChartLabels -> {Placed[{"March", "June", "Septem...

NDSolve mixing many scalar and vector equations

I have a set of scalar equations in many unknowns, which I want to combine with a vector equation inside an NDSolve. The equations are a mix of differential and algebraic equations. A set of scalar equations: eqns = {-a[0][t] + a[1][t] == 0, a[1]'[t] == - fx[1][t] + fy[1][t] - a[1][t], a[2]'[t] == - fx[2][t] + fy[2][t] - a[2][t], a[2][t] + a[3][t] == 0, 0 == x[0][t], a[1][t] == - x[0][t] + x[2][t], a[2][t] == - x[1][t] + x[3][t], a[3][t] == x[1][t] + x[3][t], 1 == y[0][t], a[1][t] == - y[0][t] + y[2][t], a[2][t] == - y[1][t] + y[3][t], a[3][t] == -y[2][t] + y[3][t]}; Along with a vector equation, defined using a function fCalc. feqn = {{fx[0][t], fy[0][t]}, {fx[1][t], fy[1][t]}, {fx[2][t], fy[2][t]}, {fx[3][t], fy[3][t]}} == fCalc[{{x[0][t], y[0][t]}, {x[1][t], y[1][t]}, {x[2][t], y[2][t]}, {x[3][t], y[3][t]}}]; My actual function fCalc is complicated, but it only evaluates for numerical input. It takes a list of {x,y} points and returns a ...