Skip to main content

Posts

Showing posts from May, 2014

mathematical optimization - Why does Maximize return a wrong answer?

I want to find the maximum of the following function, but get a wrong result. What am I doing wrong? Clear[x, y, xx, yy] peaks[x_, y_] := 3*(1 - x)^2.*Exp[-(x^2) - (y + 1)^2] - 10*(x/5 - x^3 - y^5) Exp[-x^2 - y^2] - 1/3 Exp[-(x + 1)^2 - y^2]; N[Maximize[peaks[xx, yy], {xx, yy}]] NMaximize[{peaks[x, y], x >= -2, x <= 2, y >= -2, y <= 3}, {x, y}] peaks[0, 2] peaks[1.28568, -0.00484756] When you look at these graphs, you realize that the results are strange: peaks[x_, y_] := 3*(1 - x)^2*Exp[-(x^2) - (y + 1)^2] - 10*(x/5 - x^3 - y^5) Exp[-x^2 - y^2] - 1/3 Exp[-(x + 1)^2 - y^2]; Plot3D[peaks[x, y], {x, -2, 2}, {y, -2, 3}, ColorFunction -> "DarkRainbow", AxesLabel -> Automatic] ContourPlot[peaks[x, y], {x, -2, 2}, {y, -2, 3}, ColorFunction -> "DarkRainbow", ContourLines -> False, Contours -> 25] Answer You should use FindMaximum : FindMaximum[peaks[xx, yy], {xx, yy}] {8.106, {xx -> -0.009, yy ->

list manipulation - Applying filters to data of the form {{x1,y1},{x2,y2},...}

When working with any kind of measurement data there is (at least) for me always a phase where I have to play around with different filters (such as MedianFilter , MeanFilter , LowpassFilter ...) to figure out how to improve my data in some aspect (filtering noise, detecting outliers, detecting edges...). Two things have always bugged me when using the build-in filter functions: filters expect simple list like {y1,y2,y3,y4} when (more often than not) measurement data is of the form {{x1,y1}, {x2, y2}, {x3, y3}, {x4, y4}} where $x_i$ is some index (e.g. time or frequency) and $y_i$ is the respective measurement (e.g. voltage or force) filters have a syntax of the form someFilter[data, parameters] and not an operator form someFilter[parameters][data] This leads often to a Kuddelmuddel of [[]] mixed with a bunch of Transpose and/or intermediate (global) variables What is a stylistically good way to deal with this? Answer The answer I came up with is Clear@applyFilter; applyFilter

png format - How to export a Graphics to PNG with BitDepth greater than 8?

According to the PNG ref page, it is possible to generate PNG with 8 or 16 BitDepth. I cannot find a way to impose 16 for a graphics generated by Plot. Here is the example: gr = Plot[Cos[x], {x, -4, 4}, Filling -> Bottom]; png=Export["test.png", gr, "BitDepth" -> 16]; Import[png, "BitDepth"] (* out *) 8 Thanks Answer I guess the rasterization into a 16 bit image is not done even though you specified the option. Does it work for you, if you use this: gr = Plot[Cos[x], {x, -4, 4}, Filling -> Bottom]; png = Export["test.png", Image[gr, "Bit16"]]; Import[png, "BitDepth"]

plotting - How can I plot the direction field for a differential equation?

I'd like to plot the graph of the direction field for a differential equation, to get a feel for it. I'm a novice, right now, when it comes to plotting in Mathematica, so I'm hoping that someone can provide a fairly easy to understand and thorough explanation. My hope is that I will become fairly proficient at understanding plotting in Mathematica, as well as differential equations. I'm a little more familiar with differential equations, but very far from what I'd consider to be an expert. I do have an equation in mind, taken from this question from Math.SE: $$y'=\dfrac{y+e^x}{x+e^y}$$ I ran DSolve on it, and after a minute it was unable to evaluate the function. So perhaps this could make for an interesting exploration for others as well. I'm wondering what experience in Mathematica has taught others about what can be done in Mathematica - I'm hoping someone can offer some useful tips and demonstrations. I'm really interested in learning about wha

graphics - ListPlot with conditions

I have a data file containing the position of about $10^5$ stars of a spiral galaxy. Here is the plot and this is the corresponding code Clear["Global`*"] SetDirectory[" ... "]; data = Import["data_SGC.out", "Table"]; L0 = ListPlot[data, PlotStyle -> {Blue, PointSize[0.001]}, Axes -> False, Frame -> True, FrameLabel -> {"x", "y"}, RotateLabel -> False, LabelStyle -> Directive[FontFamily -> "Helvetica", 20], AspectRatio -> 1, PlotRange -> 100, ImageSize -> 550]; As we can see, there are two arms starting at about $(x,y) = (-14.6,0)$ and $(x,y) = (14.6,0)$. Now I would like to customize ListPLot , so as the arm starting at the left part $(x,y) = (-14.6,0)$, be in green color, while the other one in red. All the other points between the two yellow banana-type areas should be in gray. Any suggestions? The complete data file can be found here: data .

How to resample a list of Images

I have a list of picture(Noting the ordering) first: second: third: forth: My target is get the 3D'image,Now I get the mask of it like following(If you use it,you should Binarize it by yourself) Then I can get the result by slices Image3D[slices, BoxRatios -> {1, 1, 1}] As you can see,the color transition of surface is so bad that you can see it clearly that it is made up of 4 pictures.For the smooth color transition we needs some sampled picture,then we use the Image3D build 3D-image.So the question is how to resample a list of image.If the target is a list of number,we can use ArrayResample like as: In[1]:= ArrayResample[{1,2,3,4,5},9] Out[1]= {1,3/2,2,5/2,3,7/2,4,9/2,5} But the list is picture now.How to do it?Can Any body have a try? Answer You can use ImageResize to resample the z-direction for your purpose. imgs = Import /@ { "http://i.stack.imgur.com/CXvgm.jpg", "http://i.stack.imgur.com/RJJnL.jpg", "http://i.stack.imgur.com/

graphics - TextRecognize with crosses, circles and spaces results into oddities, why?

I am investigating this answer here about detecting crosses and circles with TextRecognize. I tried to solve this problem here by directly using the builtin command TextRecognize but it does not work as expected: this example should print xoo x xx x x in ASCII and not xoo x 'xx . Elements are so that empty should return space, x should return x or circle should return o . Is TextRecognize bad choice for this task having ASCII gameplay characters such as x, o, # and possibly others? What can explain TextRecognize's malfunctioning? You can see that there is no ' but it still prints it and it misses some characters.

calculus and analysis - Inconsistent results for equivalent converging symbolic integrals

Bug introduced in 9.0 or earlier and persisting through 11.0.1 or later I have looked at previous questions and I'm aware that this seems to be a known bug: Mathematica giving inconsistent results for symbolic integrals done in different ways. The origins for the bugs seem to be varied. I'm having a hard time tracking down where Mathematica is going wrong with this particular one, especially since I am explicitly assuming that all my variables ($L$ and $\rho$) are positive. I've played around with the assumptions without any luck. Here's my code: $Assumptions = {ρ > 0, L > 0}; limits = Sequence[{ux, 0, L}, {vx, 0, L}, {uy, 0, ux}, {vy, 0, vx}] N1 = Integrate[a1 = Exp[-ρ (ux - uy) (vx - vy)], limits]; N2 = Integrate[a2 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy)), limits]; N3 = Integrate[a3 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy))^2, limits]; N4 = Integrate[a4 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy))^3, limits]; int1 = Integrate

plotting - Why does Plot3D appear to traverse the points twice?

While plotting a slow to evaluate function and trying to get some sense of progress, I noticed that Mathematica traverses the grid of points twice. Here's the reduced example: points = {}; Dynamic[ Show[ ListPlot[Take[points, Max[0, Length@points - 5]], PlotRange -> All], ListPlot[ Take[points, -Min[Length@points, 5]], PlotRange -> All, PlotStyle -> Directive[PointSize[Large], Opacity[0.1], Red] ], AspectRatio -> Automatic ] ] Monitor[ Plot3D[Pause[0.05]; 0, {a, -5, 5}, {b, -5, 5}, PlotRange -> All, PlotPoints -> 10, MaxRecursion -> 0], AppendTo[points, {a, b}]; ] If you watch the plot, you'll see that the red points move twice over the grid. If you inspect the plots variable after plotting, you'll see that not all the points are duplicates: some are offset from their originals by $\sim10^{-8}$. Why does Plot3D do this, even though I asked for MaxRecursion -> 0 ? Is there any way to convince it to only scan the funct

numerics - Non-linear curve fit problem

I am having a problem with making a fit to data in Mathematica , which may involve my understanding of the methods available. I am trying to fit the derivative of a Frota function (which is a Single Peak curve) together with two Gaussian Amplitudes. The raw data looks loke this: In theory, the Frota function can be described as: f[V_, phi_, gamma_, ek_, a_, b_, c_] := a*Im[E^(I*phi)*Sqrt[(I*gamma)/(V - ek + I*gamma)]] + b*V + c; As you can see that is not a function that can be differentiated easily. First I tried to differentiated it in the following way: df[V_, phi_, gamma_, ek_, a_, b_, c_] := D[ComplexExpand[f[x, phi, gamma, ek, a, b, c]], x] /. x -> V; df[V, phi, gamma, ek, a, b, c] In principle that works, but the function f has to be complex expanded before taking the derivative, due to the imaginary part not having a non numeric derivative. Moreover, when I plot the function, I have to take the real part. Still I get reasonable results and can fit my data with the func

symbols - TeXForm and Symbolize

I would like to use TeXForm to generate LaTeX output as usual. However, I use subscripted variables such as c_t . Unfortunately, when using Symbolize from the package Notation for this end, TeXForm does not work as expected. While I expected output such as c_t, I receive: Needs["Notation`"]; Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]]; TeXForm[c _t] \text{c$\mathsym{\UnderBracket}$Subscript$\mathsym{\UnderBracket}$t}. Can anyone think of a better solution? Thanks. Answer When you load Notation` package it automatically assigns definitions to MakeExpression and MakeBoxes function. Those definitions call NotationMakeExpression and NotationMakeBoxes functions respectively. After symbolizing expression with a pattern, special definition is assigned to NotationMakeExpression function. This definition forces Mathematica to perform some tasks when expression, matching symbolized pattern, is encountered. A symbol, with name reflecting symbolize

function construction - A question about two ways to use Default

Usually we define a function with default values by the syntax x_:default , but there is another technique to do this by registering a global default value with Default . In the Document , there are three ways to use Default , two of which have confused me. The document tells that Default[f,i] gives the default value to use when _. appears as the i-th argument of f , while Default[f,i,n] gives the default value for the i-th argument out of a total of n arguments . Therefore, I have tried the following comparison: Default[f, 1] = a1; Default[f, 2] = a2; Default[f, 3] = a3; f[x_., y_., z_.] := {x, y, z} {f[], f[1], f[1, 2], f[1, 2, 3]} The result is {{a1, a2, a3}, {1, a2, a3}, {1, 2, a3}, {1, 2, 3}} . ClearAll[f]; Default[f, 1, 3] = a1; Default[f, 2, 3] = a2; Default[f, 3, 3] = a3; f[x_., y_., z_.] := {x, y, z} {f[], f[1], f[1, 2], f[1, 2, 3]} This give the same result. It seems that there is no difference between these two ways to use Default . If there were no difference, why would t

evaluation - Replacement inside held expression

I wish to make a replacement inside a held expression: f[x_Real] := x^2; Hold[{2., 3.}] /. n_Real :> f[n] The desired output is Hold[{4., 9.}] , but I get Hold[{f[2.], f[3.]}] instead. What is the best way to make such a replacement without evaluation of the held expression? Answer Generally, you want the Trott-Strzebonski in-place evaluation technique: f[x_Real]:=x^2; Hold[{Hold[2.],Hold[3.]}]/.n_Real:>With[{eval = f[n]},eval/;True] (* Hold[{Hold[4.],Hold[9.]}] *) It will inject the evaluated r.h.s. into an arbitrarily deep location in the held expression, where the expression was found that matched the rule pattern. This is in contrast with Evaluate , which is only effective on the first level inside Hold (won't work in the example above). Note that you may evaluate some things and not evaluate others: g[x_] := x^3; Hold[{Hold[2.], Hold[3.]}] /. n_Real :> With[{eval = f[n]}, g[eval] /; True] (* Hold[{Hold[g[4.]], Hold[g[9.]]}] *) The basic idea is to exploit the sem

How convert list of numbers to list of points on x-axis?

I have a list of real numbers, say: vec = RandomInteger[{1, 20}, 6] (* {2, 4, 7, 10, 13, 6} *) I want to convert each of these numbers to the corresponding point on the x -axis, that is, to obtain: {{2, 0}, {4, 0}, {7, 0}, {10, 0}, {13, 0}, {6, 0}} The purpose of doing this is to include these points, among other graphics objects, in the plot of a function. Here are some ways to do it: Partition[Riffle[vec, 0], 2] (Append[#, 0] &) /@ Partition[vec, 1] PadRight[#, 2] & /@ Partition[vec, 1] vec /. x_?NumericQ -> {x, 0} What is an especially simple way to do this that will be readily understandable by somebody relatively new to Mathematica -- especially somebody who may still be uncomfortable with employing pure functions, functional approaches, and pattern-matching? Answer vec = {2, 4, 7, 10, 13, 6}; {#, 0} & /@ vec {{2, 0}, {4, 0}, {7, 0}, {10, 0}, {13, 0}, {6, 0}} Thread[{vec, 0}] {{2, 0}, {4, 0}, {7, 0}, {10, 0}, {13, 0}, {6, 0}}

front end - How do I create annotations for functions?

In 10.3, Mathematica starts captioning symbol-names into foreign languages if your Interface preferences are set to have Mathematica in a foreign language. I poked around the Attributes , and viewed the Cell expression, but from the code I couldn't find any sign that this was happening at all (though it's obviously happening somehow). I want to be able to make this happen on my own functions: to be able to supply translations, for instance, or extremely short inline explanations. For example, if I made a little function toInt , I might want to attach a type annotation String->Integer . This could help offset the verbosity of Mathematica code by making the notebook interface that little bit more intelligent. One can see the translations available using WolframLanguageData : WolframLanguageData[Graph][ EntityProperty["WolframLanguageSymbol", "Translations"] ] How does Mathematica do the translation annotations, and how can I do it myself? Answer Karsten

notebooks - How to find pieces of code responsible for syntax errors?

Especially: How to find the piece of code responsible for a missing parenthesis problem caused by a misplaced SuperScriptBox For last 30 minutes (and I was lucky today, sometimes I spend 5 times as much time) I have been removing code little by little from my large one cell, (have to be one cell, it is Manipulate demo stylesheet) in order to find where the syntax error is (since Mathematica , with all its might and power, can't tell the user which line number the syntax error is located at). Each time I see the red line show up on the right side of the notebook, indicating a syntax error, I know that I will now waste another hour at least looking for the syntax error. Why is it that hard for Mathematica to tell the user where the syntax error is? I zoomed down to this little 5 character code, and I copy it to new notebook to examine it: So, there is a hidden bad character there. Sometimes, with my big fingers and my small keyboard (can't find big keyboards any more, everythi

programming - How to make a curve selectable from a scaned image and convert it to a list of coordinates

I have a scanned image (binary-ized): Is there any way to reduce one of these curved lines (full or dotted) to a series of its coordinates (e.g., sampling interval of 0.01 on x-axis)? I've read some similar examples: But my problem is slightly different: I have several curves in one image. I would like to isolate them one from another and make each curved selectable by a simple click so that, for the selected curve, a series of coordinates of its sampled points (e.g., interval of 0.01 on x-axis) can be returned. Like this: Answer I am not sure, if one can separate one curve out of the image. There is, however, another possibility to do what you want. It is possible to get the curve points out of the image. I am not sure, if I have already published here this answer. I checked but did not find it. Hence, I am publishing it. The task is fulfilled by a copyCurve function first described and then given below. The function copyCurve Description The function copyCurve enables one to

How to enhance a fuzzy image

First I am sorry if this question is duplicate. I am not familiar with image processing so I don't know how to search for answer. I have an images which were taken with good camera but the camera sometimes produce bad images I don't know why. I want to enhance some of these images but I don't know how. Here is one of those not good image: Any help is appreciated. Thank you

differential equations - Numerically Solving Helmholtz over the Rectangle - Why does this code only give eigenfunctions of the form $u_{m1}$

I have been following the method for numerically solving the Helmholtz equation in this example (the answer by User21) and have come across two problems. I have been implementing the method for a 2x1 rectangle domain. The code I have used is as follows: Needs["NDSolve`FEM`"] boundaryMesh = ToBoundaryMesh[Polygon[{{1, 1/2}, {1, -1/2}, {-1, -1/2}, {-1, 1/2}}]] boundaryMesh["Wireframe"] mesh = ToElementMesh[boundaryMesh, "MeshOrder" -> 1, "MaxCellMeasure" -> 0.001]; mesh["Wireframe"] k = 1/10; pde = D[u[t, x, y], t] - Laplacian[u[t, x, y], {x, y}] + k^2 u[t, x, y] == 0; \[CapitalGamma] = DirichletCondition[u[t, x, y] == 0, True]; nr = ToNumericalRegion[mesh]; {state} = NDSolve`ProcessEquations[{pde, \[CapitalGamma], u[0, x, y] == 0}, u, {t, 0, 1}, {x, y} \[Element] nr]; femdata = state["FiniteElementData"] initBCs = femdata["BoundaryConditionData"]; methodData = femdata["FEMMethodData"]; i

plotting - can the color in MeshStyle be specified by a ColorFunction, such as "SunsetColors" for example. If so, what is the correct syntax?

This is an example given in Help: Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, MeshStyle -> Gray] Could this be changed to something like Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, MeshStyle -> "SunsetColors"] The above line does not work, but is there a way to modify syntax so that "SunsetColors" can be used? Answer Here is the method you posted as an answer yourself, condensed by exploiting repetitious code. Module[{a, d, t, p, kx, ky, func, cf, plot1, plot2}, a = 1.42; d = a Sqrt[3]; t = 2.8; p = 25; func := t Sqrt[3 + 2 Cos[a kx] + 4 Cos[a/2 kx] Cos[d/2 ky]]; cf[1] = ColorData["SunsetColors", #3] &; cf[-1] = ColorData["SunsetColors", 1 - #3] &; plot1 = Plot3D[#3 func, {#, -2 Pi / a, 2 Pi / a}, {#2, -2 Pi / a, 2 Pi / a}, ColorFunction -> cf[#3], BoundaryStyle -> None, Mesh -> None, PlotPoints -> p] &; plot2 = ParametricPlot3D[ Table[{kx, ky, #3 func}, {#2, -2 Pi / a, 2 Pi / a, 1/2}], {#, -2 Pi / a

list manipulation - Bug in MovingMap (breaking change between version 10.1 and 10.0.2)?

The MovingMap window spec has been changed between version 10.1 and 10.0.2. Version 10.0.2 MovingMap[h, {a, b, c, d, e, f}, 2] (* {h[{a, b}], h[{b, c}], h[{c, d}], h[{d, e}], h[{e, f}]} *) Here we get a moving window of 2 items as expected. Version 10.1 MovingMap[h, {a, b, c, d, e, f}, 2] (* {h[{a, b, c}], h[{b, c, d}], h[{c, d, e}], h[{d, e, f}]} *) In 10.1 the same statement returns a moving window of 3 items. Is there a way to have a bug marked as urgent. I have a few functions in a package that I made in 10.0.2 that I am using in 10.1 that use MovingMap and direct uses scattered about in notebooks. I think all the other "moving" functions should be testing as well. Update on outcome The short story is that the change was accidentally omitted from 10.1 release notes which lead to it being interpreted as a bug (it is a breaking change but not a bug). Below in there is a response (unofficial) in one of the comments from a WRI employee that states WRI is looking into ho

numerical integration - Find lengths of contours in a ContourPlot

I am trying to find the lengths of different contours in the following plot: It is a complicated piecewise function evaluated on the unit disk. I am hoping there is an easy, generalized way to numerically approximate each of the contours' lengths. Essentially, I am looking for a way to solve for the length of a homogenous equation bound by a region. Given a function f(x,y) - f* == 0 on a region R , where f* is the value of the contour of interest, is there a way to find the length of the curve that satisfies that equation? For concreteness, the above is the ContourPlot of q[r_] := Piecewise[{{25/(0.1*1), r < 0.1}, {25/r, r >= 0.1}}] phi[r_, t_] := (Pi/2) + q[r]*t v[r_, t_] := q[r]*r*Cos[phi[r, t]] s[x_] := Piecewise[{{x = -1, x < 0}, {x = 1, x >= 0}}] f[x_,y_] := s[x]*v[Sqrt[x^2 + y^2],ArcTan[y/x]/q[Sqrt[x^2 + y^2]]] How does one numerically find the lengths of each of those contours? Answer How about pl = ContourPlot[f[x, y], {x, -1, 1}, {y, -1, 1}, RegionFunctio

programming - How does Needs["foo`"] find the file that defines context "foo`"?

The post's title says it all, but if more detail is needed: Suppose I have the following in some file /path/to/foo.m : Begin["foo`"]; hello = Function[{}, Print["Hello world!"]]; End[]; ...and in some other file, say, ./client.m , I put the following Needs["foo`"]; foo`hello[]; Then, when the Needs expression gets evaluated, I get the error Needs::nocont: Context foo` was not created when Needs was evaluated. I'm too surprised by this error, since I see no good way for Mathematica to find where foo` is defined. (BTW, putting /path/to in $Path does not change the results described above.) What else must I put in ./client.m , besides Needs["foo`"] , so that the expression foo`hello[] evaluates properly? EDIT: I should explain that the reason I'm using Begin instead of BeginPackage is that I want to enforce full qualified names (e.g. foo`hello , rather than plain hello ) as the only way to refer to imported functions. Answer Th

syntax - Splicing a list of arguments into a function with Sequence

Not sure if this has been asked, but I have a fairly simple operation that I don't know the syntax for. Say I have an array with some values, and a function f that accepts an arbitrary number of arguments. The following: array = {e,f}; f[a, b, c, d, array]; ...is functionally equivalent to: f[a, b, c, d, {e, f}]; OK, will Sequence help? Nope, this does the same thing: f[a, b, c, d, Sequence@array]; Essentially, I want to include e and f into the list of arguments, i.e. I want to know the syntax for telling Mathematica I want it to evaluate this: f[a, b, c, d, e, f]; How do I go about doing this? Answer Sequence means more or less "no head". What you want to do is to remove the head List from an inner list. Or, put in another way, you want to replace this head with "no head". The operation that changes one head to another is Apply . Therefore, what you really want is f[a, b, c, d, Sequence @@ array] where @@ stands for Apply .

How to obtain the exact solution of a partial differential equation?

I know that Mathematica can solve a PDE numerically, but I wonder if it is possible to obtain the exact solution. For example, consider the heat equation $$u_t = \kappa u_{xx} $$ Is it possible to solve it with a set of initial and boundary conditions to calculate the exact equation of $u$ $$u = f(x,t)$$ and $$u(x=0) = f(t)$$ I don't need numeral solution or the graph but the general equations. EXAMPLE One dimensional heat flow in an slab, one side is insulated and the other side at a constant flux of heat $$ u(x,0) = U\\ u_x(0,t) = 0\\ u_x(L,t) = T $$ The solution is available from the textbooks. I just wonder, if Mathematica can give us the solution, as we can slightly alter the conditions to find new solutions.

labeling - Align FrameLabel Right

I'd like to align a FrameLabel right. For example: Plot[L[z], {z, 0.32, 1}, PlotRange -> {All, All}, Frame -> True, GridLines -> Automatic, LabelStyle -> {Black, 19}, Axes -> False, FrameLabel -> {"Distance (nm)", "Potencial (Nm)"}] In this case the plot will have FrameLabels aligned to the center. Answer Plot[Exp[z], {z, 0.32, 1}, PlotRange -> {All, All}, Frame -> True, GridLines -> Automatic, LabelStyle -> {Black, 19}, Axes -> False, FrameLabel -> { Row[{Spacer@180, "Distance (nm)"}], Row[{Spacer@50, "Potencial (Nm)"}]}]

machine learning - How to use Mathematica to train a network Using out of core classification?

I see there is doc about how to train a network Using out of core image classification and this question .But the object is only image. I want to use a binary file as data( Sequence to Sequence case ),for example like this . data = Flatten@Table[{x, y} -> x*y, {x, -1, 1, .05}, {y, -1, 1, .05}]; mydata = Flatten[data /. {(a_ -> b_) -> {a, b}}]; BinaryWrite[file, mydata, "Real32", ByteOrdering -> -1]; Close[file]; Length of data:1681 The data looks like this: Usually,the size of data is very large,so it is only a example. I use this code: fileName = "C:\\Users\\xiaoz\\Downloads\\test_data_SE.dat"; file = OpenRead[fileName, BinaryFormat -> True]; net = NetChain[{32, Tanh, 1}, "Input" -> 2, "Output" -> "Scalar"]; size = FileByteCount[fileName]; read[file_, batchSize_] := If[StreamPosition[file] + batchSize*3(*length of data in one batch*)*4(*float data*)> size, SetStreamPosition[file, 0]; BinaryReadList[file, &qu

programming - How can I use Max[] in a function that is passed a list not find the max of the list

For most functions in Mathematica , passing them a list will call the function on each element of the list. For example: ExampleFunction1[x_] := x + 1 ExampleFunction1[{1, 2, 3}] (* {2, 3, 4} *) But things change when you use Max[] . For example if I have this function: ExampleFunction2[x_] := Max[x, 4] If I pass this a single number x , it will return either x or 4 , whichever is larger, but, as documented, if i pass it a list like this: ExampleFunction2[{1, 3, 7}] It will return 7. Instead I'd like it to return { 4, 4, 7} . How can I make my function so that Max uses an element of a list as its argument instead of the entire list?

core language - Pick bug? level 0 matching

A previous discussion of this issue ( Is there a bug in Pick? ) accepted that matching at level 0 is not a bug in Pick . Was that correct? I am not yet persuaded. Here is the documentation ( http://reference.wolfram.com/language/ref/Pick.html ): " Pick[list,sel,patt] picks out those elements of list for which the corresponding element of sel matches patt ." This clearly speaks of corresponding elements. It seems to me that either there is a documentation bug or there is an implementation bug. Why am I wrong? Furthermore, the documentation gives the obvious statement of intent, so I suspect an implementation bug. Here is (yet) another example that illustrates how bizarrely unexpected is the current behavior: x = Range[20] Pick[x, x/2, _Integer] (* works as expected *) Pick[x, x/2, Except[_Integer]] (* does not work as expected *) I find it almost impossible to believe that Pick was intended to cause this simple use of Except to fail by matching the entire list x/2 rat

simplifying expressions - Mathematica performs insufficient or too slow or too memory consuming simplification

Using Mathematica 10, Simplify[Sqrt[Sin[x]^6 ((a^2 + r[]^2)^2 - a^2 (q^2 + a^2 - 2 m r[] + r[]^2) Sin[x]^2)^2]/((a^2 + a^2 Cos[2 x] + 2 r[]^2)^2 (-a^2 q^2 + a^4 + 2 m a^2 r[] + 3 a^2 r[]^2 + 2 r[]^4 + a^2 Cos[2 x] (q^2 + a^2 - 2 m r[] + r[]^2))), Assumptions -> {(a^2 + r[]^2)^2 - a^2 (q^2 + a^2 - 2 m r[] + r[]^2) Sin[x]^2 > 0}] yields the weird expression: $$\begin{cases} \frac{\sin ^3(x)}{2 \left(a^2 \cos (2 x)+a^2+2r()^2\right)^2} & \sin (x)\geq 0 \\ -\frac{\sin ^3(x)}{2 \left(a^2 \cos (2 x)+a^2+2r()^2\right)^2} & \text{True} \\ \end{cases}.$$ If I add the assumption $0 \leq x \leq \pi$, then the result becomes: $$\begin{cases} \frac{\sin ^3(x)}{2 \left(a^2 \cos (2 x)+a^2+2r()^2\right)^2} & a^2 (a^2+q^2 -2 m r() +r^2) \sin^2(x)\leq (a^2 + r()^2)^2\\ -\frac{\sin ^3(x)}{2 \left(a^2 \cos (2 x)+a^2+2r()^2\right)^2} & \text{True} \\ \end{cases},$$ in which the first conditional is actually the first assumption! The correct result is of course the first wit

plotting - Making a presentable BarChart

I've been asked to reproduce a bar chart generated in Excel in Mathematica . The original Excel chart looks like this; My Mathematica version looks like this; There are a couple of things wrong that I'd like to fix; The BarChart and ListPlot overlay doesn't seem to match up. The ChartLabels seem to have disappeared on the BarChart . Is there a nice way to make the ticks on the left and right sides match up (like when the Excel chart matches 9 % on the left to 90 % on the right)? I can't get the box and line to center align to the text in the legend. Questions 1 and 2 are what I really need to fix, but 3 and 4 would be nice to have. Any help would be appreciated. Here's the code I used to generate my chart; purple = RGBColor[97/255, 16/255, 106/255]; orange = RGBColor[245/255, 132/255, 31/255]; labels = { "FY15 Q1/2", "FY15 Q3/4", "FY16 Q1/2", "FY16 Q3/4", "FY17 Q1/Q2", "FY17 Q3/Q4", "FY18