A13 ==== I am new with Mathematica, I have one question, I know that the sollution might be very easy, but I wasn't able to find it by now. I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 Maciej ==== Although it is not outstanding, I prefer to write your equation in the form: 9*x^2+4*x*y+6*y^2==400 In order to plot the ellipse you can use the package Graphics`ImplicitPlot` in this way: In[1]:= << Graphics`ImplicitPlot` In[2]:= ImplicitPlot[ 9*x^2 + 4*x*y + 6*y^2 == 400, {x, -7, 7}, PlotStyle -> RGBColor[1, 0, 0]]; Germ.87n Buitrago A. ----- Original Message ----- > 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > Maciej > ==== first this in not an ellipse. the ellipse generic formula is : (x^2)/(a^2)+(y^2)/(b^2) = 0. I guest that you want report a graph of the solution y of the equation: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 for x varying into a given range. As you can veryfing using: Solve[0.09 x^2 + 0.04 x y + 0.06 y^2 == 4, y] the solutins are two: {{y -> 8.333333333333334*(-0.04*x - 0.1414213562373095*Sqrt[48.00000000000001 + 0.*x - 1.*x^2])}, {y -> 8.333333333333334*(-0.04*x + 0.1414213562373095*Sqrt[48.00000000000001 + 0.*x - 1.*x^2])}} than you can construct a function: function1[x_] = 8.333333333333334*(-0.04*x - 0.1414213562373095*Sqrt[48.00000000000001 - *x^2])}, that is a real value only if (48.00000000000001 - *x^2)>0, i.e. if approximatively -6 True] the same for the other soluztion. good luck -u pimak ha scritto nel messaggio > I am new with Mathematica, I have one question, > I know that the sollution might be very easy, but I wasn't able to > find it by now. > I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > Maciej > Reply-To: murray@math.umass.edu ==== One way is: ContourPlot[0.09 x^2 + 0.04 x y + 0.06 y^2, {x, -10, 10}, {y, -10, 10}, Contours -> {4}, PlotPoints -> 50, ContourShading -> False]; > I am new with Mathematica, I have one question, > I know that the sollution might be very easy, but I wasn't able to > find it by now. > I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > Maciej > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 Reply-To: kuska@informatik.uni-leipzig.de ==== Needs[Graphics`ImplicitPlot`] ImplicitPlot[0.09 x^2 + 0.04 x y + 0.06 y^2 == 4, {x, -10, 10}, {y, -10, 10}] may help. Jens I am new with Mathematica, I have one question, > I know that the sollution might be very easy, but I wasn't able to > find it by now. > I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > Maciej ==== I pretend to know how many times the function f has to be evaluated when using NDSolve to solve a differential equation. I've tried : cont=0; f[x_]:=(cont++;x^2); NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number of funtion evaluations. How can I obtain it? ==== > I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? > you need to make sure that the function f[x] is evaluated only when it gets a numeric argument. Otherwise, Mathematica expands f[x] symbolically to the expression x^2 before NDSolve is called. Writing your code as follows will solve your problem: cont=0; f[x_?NumericQ]:=(cont++;x^2); NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] Eckhard Hennig ==== > I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? cont=0; f[x_?NumericQ]:=(cont++;x^2) NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] -> cont = 94 -Jim ==== Try the following: Clear[f] cont=0; f[x_?NumericQ]:=(cont++;x^2); NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] The problem you are encountering occurs because NDSolve evaluates it's inputs first, and so NDSolve is trying to solve the differential equation y''[x]+y[x]==x^2 instead of y''[x]+y[x]==f[x]. By restricting the definition of f to evaluate only when it's input is numeric, NDSolve will keep the f[x] in the differential equation. I've included a Clear[f] statement just in case the old definition of f was still there. Carl Woll Physics Dept U of Washington I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? > Reply-To: kuska@informatik.uni-leipzig.de ==== and after cont = 0; f[x_?NumericQ] := (cont++; x^2); NDSolve[{y''[x] + y[x] == f[x], y[0] == 1, y'[0] == 0}, y, {x, 0, 6}] cont is 93. Thats because *you* gave only a blank pattern for f[x_] and NDSolve[] evaluate it to compile the right hand sides or translate it to an internal function. So *your* function is only once when Mathematica can include it into it's internal function for the right hand sides. Jens I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? > ==== Fabio, f[x_ /; IntegerQ[Rationalize[x/(2Pi)]], y] := g[x] f[x_, y_] := h[x, y] f[# Pi, y] & /@ Range[10] {h[Pi, y], g[2*Pi], h[3*Pi, y], g[4*Pi], h[5*Pi, y], g[6*Pi], h[7*Pi, y], g[8*Pi], h[9*Pi, y], g[10*Pi]} f[2.0Pi, y] g[6.28319] f[3.5, y] h[3.5, y] f[4.01Pi, 5] h[12.5978, 5] You can use a second argument in Rationalize to control how small a rationalization error is allowed and there is always the question about what domain around 2nPi you want to include in the first definition. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ ==== yes, this is a comon problem. You can either do: y=If[x>1000, ToExpression[BigVariable][[x]],x] ] or, maybe more readable, declare at the begging of ThisPackage: bigvar := bigvar = ToExpression[OtherPackage`BigVariable]; and then y=If[x>1000, bigvar, x] (* ************************** *) Alternatively you can create .mx files which load much quicker than .m files. It would be really nice if WRI could investigate why loading larger .m files is so slow ( I suspect it has to do something with the speed of side effects like DownValues declarations etc., but I don't know ). Rolf Mertig Mertig Consulting http://www.mertig.com ================================== DeclareePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent the loading of a large file in routine cases. However, when ThisPackage` defines its functions, inside the Private` area, it includes a conditional call to BigVariable. It turns out that OtherPackage is loaded when that function is defined. I was wondering if there is a way to avoid this. Roughly speaking, here is the setting: BeginPackage[ OtherPackage` ] BigVariable::usage=example Begin[Private`] BigVariable=Table[x y,{x,1000},{y,1000}] End[ ] EndPackage[ ] BeginPackage[ ThisPackage` ] function::usage=example Begin[Private`] function[x_]:=Module[{y}, y=If[x>1000,BigVariable[[x]],x] ] End[ ] EndPackage[ ] I don't want OtherPakage to be loaded unless function[x] is called with x>1000 but it loads when function is defined. Any ideas? Nicholas ==== I was looking for a function that can convert numbers between bases. For example, going from Base 3 to Base 9, or from Base 16 to Base 8. It seems like I have to a few steps and then use BaseForm to convert to the desired end base. Is there a single command or simple function to do such conversions? For example, ConvertBase[from_, to_, num_] would convert from base to base 9 using the number num as the number to convert (it would best be allowed to let users input in that specific base since they'd be going from base 3 to base 9, for example so maybe num is needed at all). ==== Dear NG Mabye this is too simple, but I cant just figure it out I want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]] and R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= Dear NG > Mabye this is too simple, but I cant just figure it out I want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]] > and > R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= NIntegrate[R[InvFunction[y[t]]*Cos[y[t]], {y[t], 0, y[T]}] it works with a constant instead of R[t]. Hope you can help, and that the above is understandable. > Martin Skogstad ==== Martin, In a post a while ago, I introduced a function called NInverse which ought to be able to help you out. The message can be found at http://library.wolfram.com/mathgroup/archive/2001/Jun/msg00125.html The output of NInverse (in your case) is a function which given a value of y returns the corresponding value of t. In your case, you would use NInverse something like the following: NInverse[y, {t0,y0}, {yy, ymin, ymax}] You will probably get some error messages, but the answer should be okay. The function NInverse can be improved (witness the inclusion of yy above), and I will post an improved version sometime. Carl Woll Physics Dept U of Washington > Dear NG > Mabye this is too simple, but I cant just figure it out I want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]] > and > R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= NIntegrate[R[InvFunction[y[t]]*Cos[y[t]], {y[t], 0, y[T]}] it works with a constant instead of R[t]. Hope you can help, and that the above is understandable. > Martin Skogstad > ==== There is a very nice java applet at http://statman.stat.sc.edu/~west/javahtml/classes/ , in which you can include your own data by replacing what is in the Applet with your own, which gives you a real time histogram plot and lets you alter the bin width and see how this effects the histogram....it wasnt until I saw this that i understood the significance of choosing the bin width......jerry blimbaum -----Original Message----- http://www.mathstatica.com for details. Obviously, it is less expensive to write your own functions. Just recently in message Mark Fisher posted code that addresses the empirical CDF. However, in this code you may want to replace 1/n with 1/(n+1) or (j-0.5)/n depending on your application. Note, these will have no significant effect for large data sets. The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. ==== A while back someone asked if Mathematica could plot data one point at a time....most answers were no, with one exception, where someone showed how to use the same Graphic Cell repeatedly....here is some Mathematica, JLink program that will do just that... << JLink` InstallJava[CommandLine -> c:j2sdk1.4.1binjava.exe] (* or set command line to where your java.exe is *) UseFrontEndForRendering = False; createWindow[] := Module[{frame}, frame = JavaNew[com.wolfram.jlink.MathFrame, Drawing Sine Wave Animation One Point at a Time]; drawArea = JavaNew[com.wolfram.jlink.MathCanvas]; drawArea@setUsesFE[UseFrontEndForRendering]; drawArea@setSize[800, 600]; JavaBlock[frame@setLayout[JavaNew[java.awt.BorderLayout]]; frame@add[drawArea, ReturnAsJavaObject[BorderLayout`CENTER]]; frame@pack[]; points = Range[data // Length] frame@setSize[800, 600]; frame@setLocation[200, 200]; JavaShow[frame]]; frame ] data = Table[{x, Sin[x]}, {x, -0.0000000000001, 2 Pi, .1}]; frame[n_] := ListPlot[Take[data, {1, n}], PlotRange -> {{0, 2 Pi}, {-1.5, 1.5}}, PlotStyle -> {PointSize[.005], Hue[0]}, DisplayFunction -> Identity] drawPoints[ptNow_] := Show[frame[ptNow], AspectRatio -> Automatic]; points = Range[data // Length]; AnimationPlot[pt_List] := JavaBlock[ Block[{frm}, frm = createWindow[]; Map[(obj = drawPoints[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; Pause[0.0001];) &, pt]; ] ] AnimationPlot[points] jerry blimbaum NSWC panama city, fl ==== I never liked the function, but now I have need of it. I hope someone can help me see the way to implement it. For a class I am teaching I want to write a simple function that does a random search for a function's maxima. I feed the function N randomly generated inputs and look at the outputs. Provided N is large enough, the largest of the outputs I obtain should be near the function's maximum value. What I want to be able to do is to identify the input that gave me that largest output. Any ideas? My only idea is this: create a table of pairs {output, input{ and find the element of the table that has the largest first entry. This will give me the input I seek. Is there a slick way of doing this in mathematica? -- Jason Miller, Ph.D. Division of Mathematics and Computer Science Truman State University 100 East Normal St. Kirksville, MO 63501 http://vh216801.truman.edu 660.785.7430 ==== Here's one way: argMax::usage = argMax[f, domain] returns the element of domain for which f of that element is maximal -- breaks ties in favor of first occurrence.; SetAttributes[argMax, HoldFirst]; argMax[f_, dom_List] := Fold[If[f[#1]>=f[#2], #1, #2]&, First[dom], Rest[dom]] And here's another way (defining it in terms of tupleMax)... tupleMax::usage = tupleMax[list] returns the tuple that is lexicographically maximal.; tupleMax[l_List] := Fold[If[OrderedQ[{#1, #2}], #2, #1]&, First[l], Rest[l]] argMax[f_, dom_List] := tupleMax[{f[#],#}& /@ dom][[2]] --- / FROM Jason Miller AT 02.09.18 06:18 (Today) / --- > I never liked the function, but now I have need of it. I hope > someone can help me see the way to implement it. For a class I am teaching I want to write a simple function that does > a random search for a function's maxima. I feed the function N > randomly generated inputs and look at the outputs. Provided N is > large enough, the largest of the outputs I obtain should be near the > function's maximum value. What I want to be able to do is to identify the input that gave me > that largest output. Any ideas? My only idea is this: create a table of pairs {output, input{ and > find the element of the table that has the largest first entry. This > will give me the input I seek. Is there a slick way of doing this in > mathematica? -- -- -- -- -- -- -- -- -- -- -- -- Daniel Reeves http://ai.eecs.umich.edu/people/dreeves/ In science it often happens that scientists say, 'You know that's a really good argument; my position is mistaken,' and then they would actually change their minds and you never hear that old view from them again. They really do it. It doesn't happen as often as it should, because scientists are human and change is sometimes painful. But it happens every day. I cannot recall the last time something like that happened in politics or religion. -- Carl Sagan, 1987 CSICOP Keynote Address Reply-To: kuska@informatik.uni-leipzig.de ==== fun[x_, y_] := x^2 + y^2 RandomMin[n_Integer] := First[Sort[ {#, fun @@ #} & /@ Table[{Random[], Random[]}, {n}], Last[#1] < Last[#2] &]] should do it. Jens I never liked the function, but now I have need of it. I hope > someone can help me see the way to implement it. For a class I am teaching I want to write a simple function that does > a random search for a function's maxima. I feed the function N > randomly generated inputs and look at the outputs. Provided N is > large enough, the largest of the outputs I obtain should be near the > function's maximum value. What I want to be able to do is to identify the input that gave me > that largest output. Any ideas? My only idea is this: create a table of pairs {output, input{ and > find the element of the table that has the largest first entry. This > will give me the input I seek. Is there a slick way of doing this in > mathematica? -- > Jason Miller, Ph.D. > Division of Mathematics and Computer Science > Truman State University > 100 East Normal St. > Kirksville, MO 63501 > http://vh216801.truman.edu > 660.785.7430 Reply-To: murray@math.umass.edu ==== The same principles that allow particular cases for defining a function of a single variable would apply here, because Mathematica applies particular rules before it applies general ones. For example: f[0, y_] := 0 f[2 Pi, y_] := y - 2 f[4 Pi, y_] := y - 4 f[x_, y_] := x^2 + y^3 This will do exactly what it looks like it does! If you have a general family of particular cases, say at all even integral multiples of Pi, then you could use something like the following in place of the first three lines above: f[k_ Pi, y_] := y - k /; IntegerQ[k] && EvenQ[k] There are variants as to where to place the condition IntegerQ[k] && EvenQ[k], for example: f[k_ Pi , y_] /; IntegerQ[k] && EvenQ[k] := y - k f[k_ Pi /; IntegerQ[k] && EvenQ[k], y_] := y - k > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 ==== >>and has a different expression for all the other values of y. Do you mean all the other values of x? You can't expect to make yourself understood to Mathematica, if you don't say what you mean. Mathematica can't guess, like we can. If that's what you meant, it's really easy: f[0 | N[0], y_] := y f[2*Pi | N[2*Pi], y_] := y^2 f[4*Pi | 4.*Pi, y_] := y^3 f[x_, y_] := y^4 If the first three of those expressions are supposed to be the same, you can substitute f[0 | N[0] | 2*Pi | N[2*Pi] | 4*Pi | 4.*Pi, y_] := y^3 Bobby Treat -----Original Message----- Fabio Reply-To: kuska@informatik.uni-leipzig.de ==== a) you must change the fonts, because the Mathematica symbols are designed to fit to Times/Helvetica/Courier and not to Computer Modern ! Mixing Computer Modern and the Mathematica fonts look not very nice because Comuter Modern has smaler strokes. You need atleast wrisym.sty, i.e. usepackage[monospacemath]{wrisym} but this will switch the main document font to Times and the mono-space font to courier. With Mathematica 4.2 you can use Adobe-Garamond and Janson as document fonts too, with usepackage[monospacemath,garamond]{wrisym} but this are commercial fonts and you have to buy it from Adobe. b) If you like the narrow monotype fonts similar to Computer Modern you can use the CMTT fonts, now included in Mathematica 4.2 Just use the package option usepackage[cmtt]{wrisym} c) I have a TeX frontend that use only the wrisym package and a preprocessor. It run fine with the most style files But you have to use TeX notebooks that are essential TeX files with mathinput environments. The TeX frontend send the contents of the mathinput environments to the kernel and paste the output into the final TeX file. It also does some fancy formating with the Mathematica input and replace -> with Rule, :> with RuleDelayed .. You can have the program and the style files if you like. Jens Dear all, I want to include some Mathematica code in some lecture notes I am writing. > For that purpose, I use the LaTeX style provided with Mathematica. It seems > to be working fine when I produce a document that is just Mathematica code. The problem - as expected - is that when I include the Mathematica code as > a part of a larger document, there are > (1) clashes with existing packages > (2) some LaTeX elements, such as the equations, start to use the > Mathematica fonts too. My objective would be to typeset a document in > standard LaTeX, where only the Mathematica code has the Mathematica feeling. Does anyone know of any style available that is completely seperated from > all other LaTeX definitions? Best Kyriakos _____+**+____+**+___+**+__+**+_ Kyriakos Chourdakis > Lecturer in Financial Economics URL: http://www.qmw.ac.uk/~te9001 > tel: (++44) (+20) 7882 5086 > Dept of Economics > University of London, QM > London E1 4NS > U.K. Reply-To: kuska@informatik.uni-leipzig.de ==== does help you ? Jens > I often run into this difficulty: when designing a program, say as a > module, and testing it for various inputs, I get wrong answers. What to > do? I use a method that works for me but may not be the best available. > I want to show my method and then ask a question about how it can be > imporved. (Oh yes, I abandoned Trace a long time ago!) myFunction[f_] := Module[ {L1,L2,L3}, L1 = ... ; > L2 = ... ; > l3 = ... ; > final step ] To see what went wrong, I use (* *) selectively as follows: Stage 1 myFunction[f_] := Module[ {L1,L2,L3}, L1 = ... (*; > L2 = ... ; > L3 = ... ; > final step *) ] Thus I see if L1 worked as expected. The next step is to put (* after L2 > and see if this works. I continue this til the bitter end and I usually > find my errors. My question; The process of moving (* *) step by step through the > program is quite tedious when the code has lots more lines. What I would > like is a meta-program which (like FoldList) does this job for me. The > output of this meta-program is the list of outputs of each line in the > module, probably best printed as a column. > This sounds like Trace but my problem with Trace is it is terribly > difficult to read. For the not-so-subtle programming I do, the only thing > I need is what expression is returned line by line. Any advice? All remarks are appreciated! Jack ==== I've enhanced the code for PartialEvaluation (see my post, which I incorrectly attaced to someone else's reply). It is somewhat more flexible now and does more error checking. It finds the rule in DownValues that matches f[args] (allowing for more than one rule in DownValues); it allows the user to specify the position of the main CompoundExpression; and it allows the user to specify an expression that gets appended to the truncated CompoundExpression (and hence evaluated and returned). The package is just a bit too large to post here. It can be downloaded from my web site at http://www.markfisher.net/~mefisher/mma/mathematica.html Nevertheless, I can give an outline of the code here (absent the error checking stuff). PartialEvaluation[f[args], n, expr]: (* get the DownValues and turn them off *) dv = DownValues[f]; DownValues[f] = {}; (* find the rule that matches *) matches = Position[MatchQ[f[args], #]& /@ dv[[All, 1]], True]; match = dv[[ matches[[1, 1]] ]]; (* find the main CompoundExpression *) ppos = Position[match, HoldPattern[CompoundExpression[__]]]; pos = First[Sort[ppos]]; (* extract, truncate, append to, and reinsert it *) held = Extract[match, pos, Hold]; held = ReplacePart[held, Sequence, {1, 0}]; held = Take[held, n]; held = Join[held, Hold[expr]]; held = ReplacePart[Hold[Evaluate[held]], CompoundExpression, {1, 0}]; match = ReplacePart[match, held, pos, 1]; (* apply the modified rule and restore DownValues *) result = f[args] /. match; DownValues[f] = dv; result --Mark I often run into this difficulty: when designing a program, say as a > module, and testing it for various inputs, I get wrong answers. What to > do? I use a method that works for me but may not be the best available. > I want to show my method and then ask a question about how it can be > imporved. (Oh yes, I abandoned Trace a long time ago!) myFunction[f_] := Module[ {L1,L2,L3}, L1 = ... ; > L2 = ... ; > l3 = ... ; > final step ] To see what went wrong, I use (* *) selectively as follows: Stage 1 myFunction[f_] := Module[ {L1,L2,L3}, L1 = ... (*; > L2 = ... ; > L3 = ... ; > final step *) ] Thus I see if L1 worked as expected. The next step is to put (* after L2 > and see if this works. I continue this til the bitter end and I usually > find my errors. My question; The process of moving (* *) step by step through the > program is quite tedious when the code has lots more lines. What I would > like is a meta-program which (like FoldList) does this job for me. The > output of this meta-program is the list of outputs of each line in the > module, probably best printed as a column. > This sounds like Trace but my problem with Trace is it is terribly > difficult to read. For the not-so-subtle programming I do, the only thing > I need is what expression is returned line by line. Any advice? All remarks are appreciated! Jack Reply-To: kuska@informatik.uni-leipzig.de ==== BeginPackage[ OtherPackage` ] BigVariable::usage=example Begin[`Private`] BigVariable=Table[x y,{x,1000},{y,1000}] End[ ] EndPackage[ ] Print[Loading ...]; and BeginPackage[ ThisPackage` ] function::usage=example Begin[`Private`] function[x_]:=Module[{y}, y=If[x>1000, Needs[OtherPackage`]; OtherPackage`BigVariable[[x]], x] ] End[ ] EndPackage[ ] should do that. Jens DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent > the loading of a large file in routine cases. However, when ThisPackage` > defines its functions, inside the Private` area, it includes a conditional > call to BigVariable. It turns out that OtherPackage is loaded when that > function is defined. I was wondering if there is a way to avoid this. > Roughly speaking, here is the setting: BeginPackage[ OtherPackage` ] > BigVariable::usage=example > Begin[Private`] > BigVariable=Table[x y,{x,1000},{y,1000}] > End[ ] > EndPackage[ ] BeginPackage[ ThisPackage` ] > function::usage=example > Begin[Private`] > function[x_]:=Module[{y}, > y=If[x>1000,BigVariable[[x]],x] ] > End[ ] > EndPackage[ ] I don't want OtherPakage to be loaded unless function[x] is called with > x>1000 but it loads when function is defined. Any ideas? > Nicholas ==== Dynamic programming might help: replace the line defining BigVariable with BigVariable:=BigVariable=Table[x y,{x,1000},{y,1000}] Then the table will not be calculated unless it is needed. (See the section on Functions that Remember Values They Have Found, 2.4.9 in the Mathematica Book). John Jowett > DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent > the loading of a large file in routine cases. However, when ThisPackage` > defines its functions, inside the Private` area, it includes a conditional > call to BigVariable. It turns out that OtherPackage is loaded when that > function is defined. I was wondering if there is a way to avoid this. > Roughly speaking, here is the setting: BeginPackage[ OtherPackage` ] > BigVariable::usage=example > Begin[Private`] > BigVariable=Table[x y,{x,1000},{y,1000}] > End[ ] > EndPackage[ ] BeginPackage[ ThisPackage` ] > function::usage=example > Begin[Private`] > function[x_]:=Module[{y}, > y=If[x>1000,BigVariable[[x]],x] ] > End[ ] > EndPackage[ ] > I don't want OtherPakage to be loaded unless function[x] is called with > x>1000 but it loads when function is defined. Any ideas? Nicholas > Reply-To: kuska@informatik.uni-leipzig.de ==== Clear[f] f[0, _] := q f[Pi, _] := p f[2Pi, _] := r f[x_, y_] := x^2*y^2 ??? Jens I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio There were some typos in my last message. It should have read: Let the known values of the function at x={0,2Pi,4Pi} be {f0,f2,f4}. Your conditions can be met by f(x,y)=x(x-2Pi)(x-4Pi)g(y)+h(x), where {h(0),h(2Pi),h(4Pi)}={f0,f2,f4}. An h(x) can be found by quadratic interpolation: h[x]= a + bx + cx^2; Solve[{a==f0,a+2Pi b +(2Pi)^2 c==f2, a+4Pi b+(4Pi)^2 c==f4},{a,b,c}] {{b -> -(3*f0 - 4*f2 + f4)/(4*Pi), c -> -(-f0 + 2*f2 - f4)/(8*Pi^2), a -> f0}} ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio Let the known values of the function at x={0,2Pi,4Pi} be {f0,f2,f4}. Your conditions can be met by f(x,y)=x(x-2Pi)(x-4Pi)g(y)+h(x), where {h(0),h(2Pi),h(4Pi)}={f0,f2,f4}. An h(x) can be found by quadratic interpolation: h[x]= a + bx + cx^2; Solve[{a==f0,a+2Pi b +(2Pi)^2+(2Pi)^2 c==f2, a+4Pi b+(4Pi)^2 c==f4] {{b -> -(3*f0 - 4*f2 + f4)/(4*Pi), c -> -(-f0 + 2*f2 - f4)/(8*Pi^2), a -> f0}} Maurice ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio Something like this? In[1]:= f[x_,y_] := If[Mod[x,2*Pi] === 0, Exp[x], Sin[y]+x] In[2]:= f[4*Pi, y] 4 Pi Out[2]= E In[3]:= f[1, y] Out[3]= 1 + Sin[y] -- Bhuvanesh, Wolfram Research. ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio > f[0, y_] := 5 f[2 Pi, y_] := 7 f[4 Pi, y_] := -3 f[x_ /; x < 0, y_] := x y f[x_ /; 0 < x < 2 Pi, y_] := x + y f[x_ /; 2Pi < x < 4 Pi, y_] := x - y f[x_ /; 4Pi < x, y_] := 2x y ==== >-----Original Message----- >Sent: Monday, September 16, 2002 6:34 AM >I have quite an easy and annoying problem with mathematica: >I need to define a function f(x,y) which takes some values for >x=0,2pi,4pi (indepently of y) and has a different expression for all >the other values of y. This is easily done for one-dimensional >functions but I am in serious troubles for my two-dimensional problem: >any suggestion? >Fabio It's difficult to guess what you wanted to attain and what your problems were. Perhaps this example might help you: In[11]:= f[x_, _] /; Mod[x, 2Pi] == 0 := x/(2Pi) In[12]:= f[x_, y_] := x + y In[13]:= epsilon = $MachineEpsilon Out[13]= 2.220446049250313*^-16 In[14]:= f[6Pi(1 + epsilon Sin[#]), #] & /@ Range[0, 4Pi, Pi 10^-1] Out[14]= {3, 3., 19.4779, 19.792, 20.1062, 20.4204, 20.7345, 21.0487, 21.3628, 3., 3, 22.3053, 22.6195, 22.9336, 23.2478, 23.5619, 23.8761, 24.1903, 24.5044, 24.8186, 3, 3., 25.7611, 26.0752, 26.3894, 26.7035, 27.0177, 27.3319, 27.646, 3., 3, 28.5885, 28.9027, 29.2168, 29.531, 29.8451, 30.1593, 30.4734, 30.7876, 31.1018, 3} Look close at the values returned (compare with epsilon Sin[Range[0, 4Pi, Pi 10^-1]]), also to recognize the dangers of such a definition. -- Hartmut ==== How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f How can I do that? Please suggest. Raj ==== Well, you can just solve for h. However, in this case there isn't a symbolic solution. How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f > How can I do that? Please suggest. Raj > Reply-To: kuska@informatik.uni-leipzig.de ==== Solve[ f=Exp[-h](a*h+b*h^2),h] will not help you but you can try to invert the series expansion as long as the function is monoton ser = Series[Exp[-h](a*h + b*h^2), {h, 0, 4}]; InverseSeries[ser, f] Jens > How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f How can I do that? Please suggest. Raj ==== I don't have any idea about how to solve next problem. Back space key when I am in the front end don't work correctly. It advances instead of go back and there is pointer mark of the mouse looks like a hand instead of an arrow, and this don't work fine too. Configuration one? How can I solve this? Note: This problem seems to appear just in my workspace i mean this not happen for other users. Cesar. __________________________________________________ Do you Yahoo!? Yahoo! News - Today's headlines http://news.yahoo.com ==== > I don't have any idea about how to solve next problem. Back space key when I am in the front end don't work > correctly. It advances instead of go back and there is > pointer mark of the mouse looks like a hand instead > of an arrow, and this don't work fine too. > Configuration one? How can I solve this? > Note: This problem seems to appear just in my > workspace > i mean this not happen for other users. Cesar. > __________________________________________________ > Do you Yahoo!? > Yahoo! News - Today's headlines > http://news.yahoo.com > Pressing the 'Num'-Key maybe solves your problem: If you switch off the 'Num Lock' your 'hand pointer mark' should turn into an 'arrow pointer mark' and you can place the cursor in a notebook. You get more details on -- Rainer Gruber ==== this thing. Here is what I'm using now: In[1]:= a=ReadList[197-tst.txt,Word,RecordLists->True, WordSeparators->None]; In[2]:= flds={{25,31}, {32,39},{40,46},{47,54},{55,62},{63,70},{71,78},{79,86},{87, 94},{95,102},{103,110}}; Define this function: In[3]:= f[x_]:=ToExpression[StringTake[x[[1]],#]]&/@flds Now, map this function onto a: In[8]:= f/@a Out[8]= {{5935.8,5946.66,27.06,-1281.9,-229.,321.,317.,367.,-115.,126.,146.},{5935.8 .... ************ The data is now in a matrix of numbers and each variable is in a column. Now I just transpose this to get each variable in a row for easy access (apparently Mathematica has no way to directly access a column in a matrix, you gotta transpose I think) Rob > I've got to extract some numbers from a file that are in lines of text. Since the line contents are not numbers, I presume I must pull the line out as a string. Here I start by pulling out just one line: inFile = OpenRead[197-tst.txt] > y = ReadList[inFile, String, 1, RecordLists -> True] > Close[inFile]; This appears to pull in a line. Now I want to take characters 25 to 110 to get just the stuff I want: > y1=StringTake[y ,{25,110}]; Here's the output. StringTake doesn't seem to work. > It doesn't take loading another package as far > as I can tell from the help. I'm thinking that it doesn't work because it's trying to work on a list > rather than a string. I've tried Flatten, and other stuff to try to get to just a string and not a list but > nothing has worked so far. I'm a long way from getting to those numbers in there but heck, I > can't even get to the string. Can anyone point me in the right direction? > ==== > The data is now in a matrix of numbers and each variable is in a column. > Now I just transpose this to get each variable in a row for easy access > (apparently Mathematica has no way to directly access a column in a matrix, > you gotta transpose I think) You can use All: In[1]:= mat = {{a,b,c},{d,e,f}}; In[2]:= mat[[All,2]] Out[2]= {b, e} -- Bhuvanesh, Wolfram Research. ==== Help! After using SetOptions[Graphics3D, ...] I am trying to set the default options of Graphics3D back to what they were when I started up Mathematica. I cannot find a command to do this. Is this possible? ==== o = Options[Graphics3D]; (* save the original options *) SetOptions[Graphics3D, ...]; (* mess with them *) SetOptions[Graphics3D, Sequence@@o]; (* restore them *) --- / FROM David Sagan AT 02.09.18 06:29 (Today) / --- > Help! After using SetOptions[Graphics3D, ...] I am trying to set the default > options of Graphics3D back to what they were when I started up > Mathematica. I cannot find a command to do this. Is this possible? > -- -- -- -- -- -- -- -- -- -- -- -- Daniel Reeves http://ai.eecs.umich.edu/people/dreeves/ The idea of programming in a low level language like C will seem as specialized and esoteric as programming in microcode or assembler seems today. -- Stephen Wolfram, creator of Mathematica Reply-To: kuska@informatik.uni-leipzig.de ==== Hmm, oldOptions=Options[Graphics3D]; SetOptions[Graphics3D,Boxed->False] (* do something with it *) SetOptions[Graphics3D, Sequence @@ oldOptions] works fine. Jens Help! After using SetOptions[Graphics3D, ...] I am trying to set the default > options of Graphics3D back to what they were when I started up > Mathematica. I cannot find a command to do this. Is this possible? > ==== This code is almost identical to yours in principle, yet 30% faster: (compared with the code in your notebook, not the code in the post > below) ClearAll[emptyTree, treeInsert]; > emptyTree = {}; treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] /; SameQ[tree[[2]], elem] := tree > treeInsert[tree_, elem_] /; OrderedQ[{tree[[2]], elem}] := > {First[tree], tree[[2]], treeInsert[Last[tree], elem]} > treeInsert[tree_, elem_] := {treeInsert[First[tree], elem], tree[[2]], > Last[tree]} Here's an even simpler version, same speed: ClearAll[emptyTree, treeInsert]; > emptyTree = {}; treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] := Which[ > SameQ[tree[[2]], elem], tree, OrderedQ[{tree[[2]], elem}], > {First@tree, tree[[2]], treeInsert[Last@tree, elem]}, > True, {treeInsert[First@tree, elem], tree[[2]], Last@tree}] I had tried variations on this but they all seemed ever so slightly slower. Might be version an OS dependent. > I see one obvious advantage of your algorithm over Husain's and my > earlier code; though I'm not sure it explains its better behavior. That > is, while my algorithm made pattern matching more burdensome, yours > virtually eliminated it. Also, the biggest improvement I've seen comes simply from replacing Null > with anything else in Husain's code. Again, that seems to suggest that > time spent on pattern matching is the problem. All the algorithms do > approximately the same real work on the tree structure. I really like how Flatten changes your tree into a sorted list. Very > nice! Goes by the name of tree sort. Using Flatten is basically a shortcut for walking the tree left-to-right. > Bobby Treat It seems I did not look hard enough at the original post or the follow-ups. In point of fact, regarding speed, there IS no obvious advantage of my code over that first version. The advantage is there, of course, as timing checks indicate. But it is quite far from obvious. The reason is related to the (rare) need for Update. It is pointed out in the manual that infinite evaluation is not in fact possible (no surprise thus far). A consequence is that Mathematica requires internal optimization features to keep reevaluation to a minimum. Update may be required in cases where such optimizations are overzealous. What we have in the case of this example is, roughly, the opposite. The code that determines need for reevaluation is simply not working sufficiently well. It does make the correct determination, but only after looking over the entire structure that is being evaluated. As we have a structure growing linearly in the number of iterations, and it gets mostly traversed each iteration, the algorithmic complexity becomes at least O(n^2). Not a disaster unless the appropriate complexity is smaller, which was the case for this example. This is not a bug insofar as it is a (regretably) necessary consequence of Mathematica evaluation semantics. The problems it can cause are all the same quite undesirable. We've made some inroads on this problem by enlarging substantially the class of expressions for which reevaluation may be quickly short-circuited, with the idea of fixing all but the most pathological of examples. The status of that work is unfortunately not known to me at present, though I'll try to find out about it. Daniel Lichtblau Wolfram Research ==== Daniel, I'd say your algorithm (as an ALGORITHM) is precisely the same as Husain's. The implementation is different, but the logical steps are the same (except perhaps for <= vs. <), and so is the logical structure of the tree produced. Even the storage method is pretty much the same. Using {} instead of Null and List instead of 'node', and putting values in the middle position, doesn't add up to a change that could affect algorithmic complexity. Even the fact that Flatten gives a sorted List with your implementation is something you get for free, and the advantage comes only when it's time to output a sorted list. It has nothing to do with the work of building the tree. Algorithmic complexity (absent hidden factors under the kernel's control) is precisely the same for your solution and Husain's (mine too, I think). The speed differences we're seeing have to do with nuances of the kernel, pattern matching costs, etc. Our three nearly equivalent algorithms simply incur different hidden costs. That's the case with many of the problems that turn into speed wars among us. We compare implementation speed (including hidden costs), not pure algorithmic complexity. Compiled code or packed arrays often make all the difference, and it usually happens in the background where we can't see it. As you've hinted below, the vagaries of Update can make a linear algorithm quadratic, but may NOT so plague a slightly different implementation of the very same algorithm. So... I'm suggesting we might want to be careful when we leap to conclusions about algorithmic complexity based on a few timed experiments. Bobby Treat -----Original Message----- > ClearAll[emptyTree, treeInsert]; > emptyTree = {}; treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] /; SameQ[tree[[2]], elem] := tree > treeInsert[tree_, elem_] /; OrderedQ[{tree[[2]], elem}] := > {First[tree], tree[[2]], treeInsert[Last[tree], elem]} > treeInsert[tree_, elem_] := {treeInsert[First[tree], elem], tree[[2]], > Last[tree]} Here's an even simpler version, same speed: ClearAll[emptyTree, treeInsert]; > emptyTree = {}; treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] := Which[ > SameQ[tree[[2]], elem], tree, OrderedQ[{tree[[2]], elem}], > {First@tree, tree[[2]], treeInsert[Last@tree, elem]}, > True, {treeInsert[First@tree, elem], tree[[2]], Last@tree}] I had tried variations on this but they all seemed ever so slightly slower. Might be version an OS dependent. > I see one obvious advantage of your algorithm over Husain's and my > earlier code; though I'm not sure it explains its better behavior. That > is, while my algorithm made pattern matching more burdensome, yours > virtually eliminated it. Also, the biggest improvement I've seen comes simply from replacing Null > with anything else in Husain's code. Again, that seems to suggest that > time spent on pattern matching is the problem. All the algorithms do > approximately the same real work on the tree structure. I really like how Flatten changes your tree into a sorted list. Very > nice! Goes by the name of tree sort. Using Flatten is basically a shortcut for walking the tree left-to-right. > Bobby Treat It seems I did not look hard enough at the original post or the follow-ups. In point of fact, regarding speed, there IS no obvious advantage of my code over that first version. The advantage is there, of course, as timing checks indicate. But it is quite far from obvious. The reason is related to the (rare) need for Update. It is pointed out in the manual that infinite evaluation is not in fact possible (no surprise thus far). A consequence is that Mathematica requires internal optimization features to keep reevaluation to a minimum. Update may be required in cases where such optimizations are overzealous. What we have in the case of this example is, roughly, the opposite. The code that determines need for reevaluation is simply not working sufficiently well. It does make the correct determination, but only after looking over the entire structure that is being evaluated. As we have a structure growing linearly in the number of iterations, and it gets mostly traversed each iteration, the algorithmic complexity becomes at least O(n^2). Not a disaster unless the appropriate complexity is smaller, which was the case for this example. This is not a bug insofar as it is a (regretably) necessary consequence of Mathematica evaluation semantics. The problems it can cause are all the same quite undesirable. We've made some inroads on this problem by enlarging substantially the class of expressions for which reevaluation may be quickly short-circuited, with the idea of fixing all but the most pathological of examples. The status of that work is unfortunately not known to me at present, though I'll try to find out about it. Daniel Lichtblau Wolfram Research ==== I'm curious, why the built-in boolean functions And and Or aren't commutative? Attributes/@{Or,And}//ColumnForm {Flat, HoldAll, OneIdentity, Protected} {Flat, HoldAll, OneIdentity, Protected} However, the arithmetical functions are Orderless: Attributes/@{Plus,Times}//ColumnForm {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} ------------------- Evgeni Trifonov Vladivostok, Russia ==== Evgeni, Note that both And and Or can return a value without evaluating all of their arguments. For example, if the first argument to And is False, there is no reason to look at the other arguments. Suppose a user knows that one of the arguments is usually false, and so would like to look at that argument before any of the others, to avoid unneeded computations of the other arguments. He would put that argument first. If Mathematica turned around and sorted the arguments (which is what happens when a function is orderless), then that argument might end up being evaluated last. If the arguments take a significant amount of time to compute, then sorting first may cause the function to take much longer to evaluate. At any rate, if the above is not a concern for you, you may always change the attributes of And and Or to anything you want. Carl Woll Physics Dept U of Washington ----- Original Message ----- > However, the arithmetical functions are Orderless: Attributes/@{Plus,Times}//ColumnForm {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} > {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} ------------------- > Evgeni Trifonov > Vladivostok, Russia > ==== I have defined two functions (Math 4.1) In[1]:= integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t]; In[2]:= integrate[Exp[(a_.)*tau], t_]:=(E^(a*t)-1)/a/; FreeQ[a,t]&&FreeQ[a,tau]; when I applied these functions the solution is different if the coefficient is the letter d or lower (solution fine) or f or higher (solution wrong) . Here is an example: Using letter f In[3]:=integrate[f Exp[-0.8316*tau], t] Out[3]:=integrate[f, t]/E^(0.8316*tau) (*wrong*) Using letter a (the solution is rigth In[4]:=integrate[a Exp[-0.8316*tau], t] Out[4]:=-1.20250*a*(-1 + E^(-0.8316*t)) What it wrong? Guillermo Sanchez --------------------------------------------- This message was sent using Endymion MailMan. ==== Neither of your solutions are wrong according to your rules. Lets step through them In[3]:=integrate[f Exp[-0.8316*tau], t] lexographical (sp) order as In[3]:=integrate[Exp[-0.8316*tau] f, t] It then applies rule 1: integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t] Well, The term Exp[-0.8316*tau] contains no t, so according to your rule it is equal to Exp[-0.8316*tau] integrate[f, t] At this point none of your rules apply, so the kernel stops. When you use a instead of f the ordering of the constant and the exponential are reversed, and you get the behaviour that you actually desired. A simple fix is to replace the condition in rule 1 by FreeQ[c,t]&&FreeQ[c,tau] You may however want to think carefully about exactly what you want your function integrate to do. For example, with the rules given, the variable t and the variable tau seem to be playing the same role. Erich > I have defined two functions (Math 4.1) > In[1]:= integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t]; > In[2]:= integrate[Exp[(a_.)*tau], t_]:=(E^(a*t)-1)/a/; > FreeQ[a,t]&&FreeQ[a,tau]; when I applied these functions the solution is different if the coefficient is > the letter d or lower (solution fine) or f or higher (solution wrong) . Here is > an example: Using letter f > In[3]:=integrate[f Exp[-0.8316*tau], t] Out[3]:=integrate[f, t]/E^(0.8316*tau) (*wrong*) Using letter a (the solution is rigth In[4]:=integrate[a Exp[-0.8316*tau], t] Out[4]:=-1.20250*a*(-1 + E^(-0.8316*t)) What it wrong? Guillermo > Sanchez --------------------------------------------- > This message was sent using Endymion MailMan. ==== << Graphics`ImplicitPlot` does the job. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de -----UrsprÌ.b9ngliche Nachricht----- Gesendet: Mittwoch, 18. September 2002 08:09 An: mathgroup@smc.vnet.net Betreff: Drawing an ellipse I am new with Mathematica, I have one question, I know that the sollution might be very easy, but I wasn't able to find it by now. I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 Maciej ==== Solve[eqn, var] and InverseFunction are designed to do what you want, in principle. Try Solve[(a*h+b*h^2) == f, h] For your eqn, however, it is impossible to solve for h since h appears as a factor in a sum *and* as an exponent. Try Solve[Exp[-h]*(a*h+b*h^2) == f, h] and study Mathematica's message. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de -----UrsprÌ.b9ngliche Nachricht----- Gesendet: Mittwoch, 18. September 2002 08:10 An: mathgroup@smc.vnet.net Betreff: Invert a function How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f How can I do that? Please suggest. Raj ==== > Map[(obj = drawMembrane[#]; > drawArea@setMathCommand[obj]; > drawArea@repaintNow[]; > Pause[.0001];) &, t ] This is the exact code you use? Maybe I am missing something here, but you seem to pass only the String obj to the setMathCommand method, not the content of the obj variable; > public class My_DisplayGraphicsViaJava { > public void displayGraphics(String cmds[]) { > for (int i = 0; i < cmds.length-1; i++) > drawArea.setMathCommand(cmds[i]); > drawArea.repaintNow(); > Thread.sleep(200);} } er... this won't work; you are using the drawArea variable, without ever declaring or assigning something to it! pff... hm... you could try this: import com.wolfram.jlink.MathCanvas; public class My_DisplayGraphicsViaJava { public static void displayGraphics(String cmds[], MathCanvas drawArea){ for (int i = 0; i < cmds.length-1; i++){ drawArea.setMathCommand(cmds[i]); drawArea.repaintNow(); Thread.sleep(200); } } } save this to a file called My_DisplayGraphicsViaJava.java and compile it. Put the class file in a directory that is in your CLASSPATH (or look up how the CLASSPATH works in J/Link 2.0 in the J/Link documentation, its properly explained there); If all that has worked, load the class: LoadJavaClass[My_DisplayGraphicsViaJava]; then use the static method displayGraphics, by passing it the String array and the drawArea variablen (which is the MathCanvas object, you have instantiated in your Mathematica Notebook): My_DisplayGraphicsViaJava`displayGraphics[obj, drawArea]; obj being the String array (or string List in M_) that holds your Graphics Expressions (or what you want to show); > But needless to say this dont work....LoadJavaClass responds by saying Class > not Found.....so what should I do to correct this? Also , on the java > routine, was i supposed to add: Extends MathFrame, etc....how will my > java routine know what drawArea.setMathCommand is, etc..... > am I also supposed to compile my java routine? Yes! ... use the Java code I proposed above, that should at least compile properly; Place the compiled class file in a directory on your CLASSPATH (consult J/Link docu if you don't know about CLASSPATH) and then try the Mathematica code again. I hope this was not too confusing; I don't have a working Mathematica here, so I can't verify, if my proposed code would really work; there migth be typos/errors in my code. murphee ==== I am trying to write an animation using JLink.....basically as follows...(using Mathematica 4.1, JLink 2.01 and java 1.4.1)... frm = createWindow[]; (* basically to create a MathFrame and a drawArea = MathCanvas *) Here is my drawing routine.... Map[(obj = drawMembrane[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; Pause[.0001];) &, t ] t = time list ={0,.25,etc}.... and drawMembrane is a function that uses the time value to make a graphics plot......unfortunately, this routine draws the next time plot very slowly, plus I also notice that without the Pause[] statement, Mathematica only draws the graph for the final time value... Following an example in the JLink documentation, I have written the following java routine....which I saved in the same dir as MathFrame, etc.... public class My_DisplayGraphicsViaJava { public void displayGraphics(String cmds[]) { // declare String Array for Graphics Objects for (int i = 0; i < cmds.length-1; i++) drawArea.setMathCommand(cmds[i]); drawArea.repaintNow(); Thread.sleep(200);} } and then in Mathematica I have LoadJavaClass[My_DisplayGraphicsViaJava]; My_DisplayGraphicsViaJava`displayGraphics[obj]; (* where obj is the array of Graphics plots created *) But needless to say this dont work....LoadJavaClass responds by saying Class not Found.....so what should I do to correct this? Also , on the java routine, was i supposed to add: Extends MathFrame, etc....how will my java routine know what drawArea.setMathCommand is, etc.....am I also supposed to compile my java routine? thanks....jerry blimbaum NSWC panama city, fl ==== Dear colleagues, I'm trying to plot the next exponential function Plot[Exp[1/(Abs[x-1]-Abs[x-2])],Range] If the Range is positive there aren«t problems. However if the Range is negative Mathematica plots a strange beast... Have anyone found anything of this sort? I would apreciate to know how to resolve this problem. Juan Egea Garcia Bullas - Murcia - Espa.96a ==== The function you are plotting is constant for negative x. You might want to specify a plotrange, such as PlotRange->{0,2}, or Mathematica may try to zoom in on the line and show you a picture of numerical noise. Erich > Dear colleagues, I'm trying to plot the next exponential function Plot[Exp[1/(Abs[x-1]-Abs[x-2])],Range] If the Range is positive there aren«t problems. However if the Range is > negative Mathematica plots a strange beast... Have anyone found anything of this sort? I would apreciate to know how to > resolve this problem. Juan Egea Garcia > Bullas - Murcia - Espa.96a > ==== I need to solve algebraic-differential-equations (some of index 1, maybe some of higher index as well) from within Mathematica 4.2. Is there an implementation of numerical (like DASSL) or symbolic algorithms capable of doing that around? I know that some numerical software systems which may have DASSL-routines that do what I want. Has anybody suggestions on which of these systems is easy to interface with Mathematica? Is there a C++ library that contains such routines and can be interfaced with Mathematica? Yours, Reinhard Oldenburg ==== > I need to solve algebraic-differential-equations > (some of index 1, maybe some of higher index as well) > from within Mathematica 4.2. > Is there an implementation of numerical (like DASSL) > or symbolic algorithms capable of doing that around? I know that some numerical software systems which > may have DASSL-routines that do what > I want. Has anybody suggestions on which of these > systems is easy to interface with Mathematica? > Is there a C++ library that contains such routines and can be > interfaced with Mathematica? Reinhard, have you tried the NDAESolve package that comes with the circuit analysis toolbox Analog Insydes? You can get a free evaluation version of Analog Insydes from www.analog-insydes.de. Eckhard Hennig ==== Dear Colleagues, I intend to make an animation in which ball A rolls down on an inclined plane from the left whilst ball B - starting from the same height - rolls down Cosh[t]'s path from the right. x-axis is time t, y-axis is height h. Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my means. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de ==== Matthias, The simplest way to get the equation of motion is to set up the Lagrangian. Let's assume a 1 kg mass. Then the kinetic energy is KE = Simplify[(1/2)*(x'[t]^2 + D[Cosh[x[t]],t]^2)] and the potential energy is PE = 9.8*Cosh[x[t]] The Lagrangian is L = KE - PE and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, I intend to make an animation in which ball A rolls down on an inclined plane from the left whilst ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. x-axis is time t, y-axis is height h. Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de ==== Having noticed your statement ... BEYOND MY MEANS I thing you aren't yet familiar with Lagrangian formalism. It's quite easy to derive a general equation of motion for a point mass, subjected to gravity and to moving on a curve f = y(x) (i.e. f = Cosh[#]&). 1) I'll leave re-deriving equation to you, here is what I've got (just copy paste it).: !(getEq[ f_] := [IndentingNewLine](x'')[ t] + (x')[t]^2 (2 (f')[x[t]] (f'')[x[t]])/(1 + (f' )[x[t]]^2) + (g (f')[x[t]])/(1 + (f')[x[t]]^2) == 0 /. g -> 1) 2) Next, you integrate it .: getSol[f_, x0_] := Module[{tStop}, NDSolve[{getEq[f], x[0] == x0, x'[0] == 0} , x , {t, 0, 10} , MaxStepSize -> 1/100 , StoppingTest :> If[x0 < 0, x > 0, x < 0] ] // First ] 3) Here follows animation code, specially for linear versus cosh case, apply my initial conditions (below) makeDuo[f_, g_, x0_, fpt_] := Module[{ solf = getSol[f, x0], solg = getSol[g, x0], tf, tg, maxT, minT }, tf = solf[[1, 2, 1, 1, 2]]; tg = solg[[1, 2, 1, 1, 2]]; maxT = Max[{tf, tg}]; minT = Min[{tf, tg}]; Do[ Plot[{f@x, g@x} , {x, 0, x0} , AspectRatio -> Automatic , Frame -> True , Axes -> False , Epilog -> { AbsolutePointSize[10], Hue[0], Point[{x[t], f@x[t]} /. solf], Hue[.6], Point[{x[t], g@x[t]} /. solg] } ] , {t, 0, minT, minT/fpt} ] ] 4) My initial conditions. In my opinion, you weren't true on this. Saying STARTING FROM THE SAME HEIGHT is not enough - you should specify x as well, thus specifing starting POINT and not just height y. makeDuo[(Cosh[1.] - 1) # &, Cosh[#] - 1 &, 1, 23] Feel free to modify the code, it should be easy. bye, Borut | Dear Colleagues, | | I intend to make an animation in which | | ball A rolls down on an inclined plane from the left whilst | | ball B - starting from the same height - rolls down Cosh[t]'s path from the | right. | | x-axis is time t, y-axis is height h. | | Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my | means. | | | Matthias Bode | Sal. Oppenheim jr. & Cie. KGaA | Koenigsberger Strasse 29 | D-60487 Frankfurt am Main | GERMANY | Mobile: +49(0)172 6 74 95 77 | Internet: http://www.oppenheim.de | | ==== As I derived a generalization for a 3D parameterized curve yesterday, I'd noticed a mistake in my equation posted below, a factor '2' in expression involving x'[t]^2, should be '1'. Since this forum is of an alt. type, I've published the whole notebook at http://www2.arnes.si/~gljpoljane22/math/FallingCurve3D.nb Bye, Borut p.s. A 'fill-the-gap' riddle for those interested in physics lore. Richard Feynman once said: Science is like _ _ _, sometimes something useful comes out, but that is not the reason why we are doing it. | ... | 1) I'll leave re-deriving equation to you, here is what I've got (just copy | paste it).: | | !(getEq[ | f_] := [IndentingNewLine](x'')[ | t] + (x')[t]^2 (2 (f')[x[t]] (f'')[x[t]])/(1 + | (f' | )[x[t]]^2) + (g (f')[x[t]])/(1 + (f')[x[t]]^2) == 0 /. g -> | 1) | ... ==== David, There is no command such as RestoreDefaults. But you can do the following: saveGraphics3DOptions = Options[Graphics3D]; SetOptions[Graphics3D, Boxed -> False]; (say) Make your plots. SetOptions[Graphics3D, Sequence @@ saveGraphics3DOptions]; The example in the Help for SetOptions shows a similar example. My own personal preference would be to not change the Graphics3D options, but to add the option change to the plot itself. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== I have the following code and am trying to include a legend. The BarChart appears, but with no legend. I have followed the 'help files', but I think I'm missing something. In my code, SortTime and SessTime are value pairs. Photog is a string array containing labels. /* *Begin code here */ ShowLegend[BarChart[SortTime, SessTime, BarSpacing -> -.3,, BarGroupSpacing -> .5, BarLabels -> Photog, BarStyle -> {RGBColor[1, 0, 0], RGBColor[0.5, 0.5, 1]}, PlotLabel -> Photographer Time , DefaultFont -> {Helvetica, 9}], {{{RGBColor[1, 0, 0], Sort Time }, {RGBColor[0.5, 0.5, 1], Session Time }}, LegendLabel -> Mean Time}] pete ==== How's this: maxima[f_, x_List] := Last@Sort@({f[#], #} & /@ x) maxima[Sin,Range[0,2Pi,0.1]] {0.999574,1.6} That gives you both f[x] and x at the maximum. Bobby Treat -----Original Message----- that largest output. Any ideas? My only idea is this: create a table of pairs {output, input{ and find the element of the table that has the largest first entry. This will give me the input I seek. Is there a slick way of doing this in mathematica? -- Jason Miller, Ph.D. Division of Mathematics and Computer Science Truman State University 100 East Normal St. Kirksville, MO 63501 http://vh216801.truman.edu 660.785.7430 ==== want base 12 numbers, for instance, stored in -- a List of digits? A character string? A list of digits, highest power to lowest, is easy to handle: ClearAll[convertBase] convertBase[(from_Integer)? (#1 > 1 & ), (to_Integer)?(#1 > 1 & ), n:{_Integer..}] /; Max[n] < from := from], to] convertBase[5, 3, {1, 2}] {2, 1} Bobby Treat -----Original Message----- example, ConvertBase[from_, to_, num_] would convert from base to base 9 using the number num as the number to convert (it would best be allowed to let users input in that specific base since they'd be going from base 3 to base 9, for example so maybe num is needed at all). ==== This came up some time ago. Can't remember exactly what my reply was but I discovered later that it is because the number lock is on. Turn it off and the hand will disappear. May even fix the back space trouble. Yas > I don't have any idea about how to solve next problem. Back space key when I am in the front end don't work > correctly. It advances instead of go back and there is > pointer mark of the mouse looks like a hand instead > of an arrow, and this don't work fine too. > Configuration one? How can I solve this? > Note: This problem seems to appear just in my > workspace > i mean this not happen for other users. Cesar. > __________________________________________________ > Do you Yahoo!? > Yahoo! News - Today's headlines > http://news.yahoo.com ==== I believe that's not the adjacency matrix Thomas asked for. It doesn't have zeroes on the diagonal (it isn't square) and it doesn't have ones to indicate that two actors are associated with the same event. Instead, it shows connections between actors and events, which is actually more useful, as I'll demonstrate. (In addition -- though it doesn't really matter -- Jens-Peer switched the 'actors' and 'events' nomenclature within the function.) If you multiply it by its transpose, you get something else that's useful: lst = {{1, A}, {1, B}, {2, B}, {3, C}, {3, D}, {1, D}, {1, C}}; AdjacenceMatrix[lst : {{_, _} ..}] := Module[{actors, events, adj}, {actors, events} = Union /@ Transpose[lst]; adj = Table[0, {Length[actors]}, {Length[events]}]; Scan[(Part[adj, Sequence @@ #] = 1) &, lst /. MapIndexed[Rule[#1, First[#2]] &, events]]; adj] MatrixForm[a = AdjacenceMatrix[lst]] MatrixForm[b = a.Transpose[a]] Matrix 'b' records how many events two actors have in common. On the diagonal, it shows the total number of events each actor is connected to. It's easy to put zeroes on the diagonal: MatrixForm[c = b (1 - IdentityMatrix[Length[b]])] To get the originally intended incidence matrix, this works: d = c /. {_?Positive -> 1} However, I think matrices 'a' and 'b' are actually more useful, and 'a' easily leads to all the others. Bobby -----Original Message----- AdjacenceMatrix[lst : {{_, _} ..}] := Module[ {actors,events adj}, {events, actors} = Union /@ Transpose[lst]; adj = Table[0, {Length[events]}, {Length[actors]}]; Scan[(Part[adj, Sequence @@ #] = 1) &, lst /. MapIndexed[Rule[#1, First[#2]] &, actors]]; adj ] you get In[]:=AdjacenceMatrix[lst] Out[]={{1, 1, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 1}} Jens I need to create an adjacency matrix from my data, which is currently in > the form of a .txt file and is basically a two column incidence list. > For example: 1 A > 1 B > 2 B > 3 C > . . > . . > . . > m n Where 1 to m represent actors and A to n represent events. My goal is to > have an (m x m) matrix where cell i,j equals 1 if two actors are > incident to the same event (in the sample above, 1 and 2 are both > incident to B) and 0 otherwise (w/ zeros on the diagonal). I'm new to Mathmatica, and so I'm on the steep part of the learning > curve ... All I've been able to figure out so far is how to get my > incidence list into the program using Import[filename.txt]. But then > what? How do I convert to the adjacency matrix? I've found the > ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I can't > seem to get it to work ... > Tom ********************************************** > Thomas P. Moliterno > Graduate School of Management > University of California, Irvine > tmoliter@uci.edu > ********************************************** ==== Maybe this will help. I had to do some guessing, and I fabricated my own R function (r). I never start user-defined symbols with capital letters. ClearAll[r] t = Pi/2.; r = Interpolation[{#, Abs@Cos@#} & /@ Range[0, N@t, Pi/100.]]; y[z_] := NIntegrate[r[x]^4, {x, 0, z}] Timing[yInverse = Interpolation[{y[#], #} & /@ Range[0, N@t, Pi/100.]];] {0.030999999999998806*Second, Null} a = NIntegrate[r[yInverse[z]*Cos[z]], {z, 0, y[t]}]/y[t] 0.9249048118568042 Bobby Treat -----Original Message----- a = (1/y[T])* NIntegrate[R[InvFunction[y[t]]*Cos[y[t]], {y[t], 0, y[T]}] it works with a constant instead of R[t]. Hope you can help, and that the above is understandable. Martin Skogstad ==== << Graphics`ImplicitPlot` eqn = 0.09*x^2 + 0.04*x*y + 0.06*y^2 == 4; maxX = 1.1*Sqrt[4/0.09]; ImplicitPlot[eqn, {x, -maxX, maxX}]; You could also use ParametricPlot: polarEqn = eqn /. {x -> r Sin[t], y -> r Cos[t]} radius[t_] = r /. Last@Solve[polarEqn, r] ParametricPlot[radius[x]{Cos[x], Sin[x]}, {x, 0, 2Pi}, AspectRatio -> 1]; I tried and failed with InequalityGraphics: << Graphics`InequalityGraphics` InequalityPlot[{LessEqual @@ eqn}, {x, -xMax, xMax}, {y, -yMax, yMax}] InequalityPlot::region:The region defined by [LeftSkeleton]1[RightSkeleton] could not be broken down into cylinders. InequalityPlot[ 0.09*x^2 + 0.04*x*y + 0.06*y^2 <= 4, {x, -xMax, xMax}, {y, -yMax, yMax}] Plot can be used very neatly, if you first figure out the true extent of the x-values: positiveX[y_] = x /. Last@Solve[eqn, x] Solve[positiveX'[y] == 0] xMax = First@(positiveX[y] /. %) Plot[Evaluate[y /. Solve[eqn, y]], {x, -xMax, xMax}, AspectRatio -> 1]; Bobby Treat -----Original Message----- ==== That function isn't easily inverted and, in fact, has no inverse unless you limit the range of h. In this plot, for instance, you see that the same f[h] values are taken on for two different values of h: Plot[f@h /. {a -> 3, b -> 0.2}, {h, 0, 10}] The peak of the graph depends on the parameters a and b, so the domain of an inverse (if it exists) also depends on a and b. That's exactly the kind of situation Solve can't handle. For specific a, b and y, FindRoot can find h for you: FindRoot[Evaluate[f[h] == 1 /. {a -> 3, b -> 0.2}], {h, 2}] {h -> 1.799292219454869} FindRoot[Evaluate[f[h] == 1 /. {a -> 3, b -> 0.2}], {h, 0.5}] {h -> 0.5654110956582447} Bobby Treat -----Original Message----- ==== I'd say the applet demonstrates that histograms are useless unless we choose a pretty small bin-width. Choosing a bin-width of significant size that doesn't yield a misleading histogram is an unlikely accident. Bobby -----Original Message----- understood the significance of choosing the bin width......jerry blimbaum -----Original Message----- very nice package that does all of the above and more is mathStatica. See http://www.mathstatica.com for details. Obviously, it is less expensive to write your own functions. Just recently in message Mark Fisher posted code that addresses the empirical CDF. However, in this code you may want to replace 1/n with 1/(n+1) or (j-0.5)/n depending on your application. Note, these will have no significant effect for large data sets. The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. ==== > I'm curious, why the built-in boolean functions And and Or > aren't commutative? The on-line help explains why. (Look up And or Or and then link A.4.2.) You are assured that the argments of And or Or are evaluated left to right, stopping on the first False (for And) or True (for Or). Tom Burton ==== True, but in this case, excitement means being misled far too often. I've never favored histograms much, except when there are lots of bars and little apparent noise. Otherwise, unless you're very lucky, a histogram doesn't even locate the mode well. Bobby Treat -----Original Message----- Bobby -----Original Message----- blimbaum -----Original Message----- very nice package that does all of the above and more is mathStatica. See http://www.mathstatica.com for details. Obviously, it is less expensive to write your own functions. Just recently in message Mark Fisher posted code that addresses the empirical CDF. However, in this code you may want to replace 1/n with 1/(n+1) or (j-0.5)/n depending on your application. Note, these will have no significant effect for large data sets. The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. ==== Could someone calculate the number Pi to 67,108,864 (2^26) decimal places I made the calculation in another program and would like to verify its ==== > Could someone calculate the number Pi to 67,108,864 (2^26) decimal places > I made the calculation in another program and would like to verify its Does it really matter what program is used to verify it? If not, here's the digits (computed with the fastest pi crunching program for a PC): 33863220896223409803 ==== >I am trying to write an animation using JLink.....basically as >follows...(using Mathematica 4.1, JLink 2.01 and java 1.4.1)... > >frm = createWindow[]; (* basically to create a MathFrame and a drawArea >= MathCanvas *) > >Here is my drawing routine.... Map[(obj = drawMembrane[#]; >drawArea@setMathCommand[obj]; > drawArea@repaintNow[]; > Pause[.0001];) &, t ] > >t = time list ={0,.25,etc}.... and drawMembrane is a function that uses the >time value to make a graphics plot......unfortunately, this routine draws >the next time plot very slowly, plus I also notice that without the Pause[] >statement, Mathematica only draws the graph for the final time value... Jerry, You did a nice job with this one-frame-at-a-time plot. (I'm replying here to this message and your previous one where you presented the full code.) The main reason that it is slow drawing the frames is that the Pause[] function only works with integer second intervals. If you say Pause[.0001] it pauses for a whole second, which inserts a 1-second delay between each frame. If I take out the Pause, I get about 5 frames per second on my laptop (for your Sin plot). This still seems slow to me, but it turns out that Java is just slow at taking GIF data and making it into pixels to be displayed. That step consumes virtually all the time for the animation. If you make the image smaller, the animation runs much faster. Try making your window size 400 x 300 instead of 800 x 600. At that size, the animation runs at a good speed on my machine. If you want to insert a delay between frames, you need to use Java instead of calling Pause[]: LoadJavaClass[java.lang.Thread]; Map[(obj = drawMembrane[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; (* Add a 100 ms delay *) Thread`sleep[100];) &, t ] You said that without the Pause[] you only get the last frame drawn, but that shouldn't have any effect. Perhaps you took out the call to repaintNow() along with the Pause? >Following an example in the JLink documentation, I have written the >following java routine....which I saved in the same dir as MathFrame, >etc.... >public class My_DisplayGraphicsViaJava { > public void displayGraphics(String cmds[]) { // declare String Array >for Graphics Objects > for (int i = 0; i < cmds.length-1; i++) > drawArea.setMathCommand(cmds[i]); > drawArea.repaintNow(); > Thread.sleep(200);} } >and then in Mathematica I have LoadJavaClass[My_DisplayGraphicsViaJava]; >My_DisplayGraphicsViaJava`displayGraphics[obj]; (* where obj is the >array of Graphics plots created *) >But needless to say this dont work....LoadJavaClass responds by saying Class >not Found.....so what should I do to correct this? Also , on the java >routine, was i supposed to add: Extends MathFrame, etc....how will my >java routine know what drawArea.setMathCommand is, etc.....am I also >supposed to compile my java routine? You will definitely need to compile any Java classes you write! But writing this in Java won't change anything because the delay is in Java itself, not in J/Link or the MathLink communication. This Java class would need a lot of work before it would compile. You would need to either create drawArea in the Java class rather than in Mathematica code, or pass it as an argument to displayGraphics() (which needs to be static, by the way). Anyway, there is no point in thinking about any of that, since this displayGraphics() method just duplicates functionality that you have already (much more conveniently) scripted in Mathematica code. One final general note for J/Link programmers: It's OK to create Java names with underscores in them, but you have to remember how they are handled in Mathematica. When you refer to a Java name in Mathematica code as a string, you keep the underscore: LoadJavaClass[My_DisplayGraphicsViaJava]; But when a name appears as a symbol in Mathematica, J/Link maps it to a U because _ is not legal in a symbol name: MyUDisplayGraphicsViaJava`displayGraphics[....] It's often easiest to just avoid using _ in the names of Java classes and methods that you write for use with Mathematica. Todd Gayley Wolfram Research ==== >-----Original Message----- >Sent: Wednesday, September 18, 2002 8:09 AM >I am new with Mathematica, I have one question, >I know that the sollution might be very easy, but I wasn't able to >find it by now. >I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 >Maciej > Two methods: (1) solve for explit functions y = f[x] and plot those: In[2]:= eqn = 0.09 x^2 + 0.04 x y + 0.06 y^2 == 4 ... just for convenience; In[5]:= sols = Solve[eqn, y] In[6]:= y /. sols ...these are the two functions for y expressed by x. To find the minimum and maximum values for x, we spot the discriminant, and solve for x: In[12]:= {xmin, xmax} = x /. Solve[ Cases[y /. sols[[1]], Sqrt[disc_] :> disc, Infinity] == 0, x] ...now we may use Plot: In[18]:= Plot[Evaluate[y /. sols], {x, xmin, xmax}, AspectRatio -> Automatic] (2) guess approximate values for xmin, xmax and let Mathematica do all that work: In[1]:= << Graphics`ImplicitPlot` ...load the package In[19]:= ImplicitPlot[eqn, {x, -7, 7}] ...done. -- hw ==== b = 2; r = 4; n = 10101111 p = Reverse[Characters[n]] {1, 1, 1, 1, 0, 1, 0, 1} z = Reverse[Partition[p, r]] {{0, 1, 0, 1}, {1, 1, 1, 1}} (* this is okay *) b = 2; r = 3; z = Reverse[Partition[p, r]] {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be {{0,1,0},{1,0,1},{1,1,1}}*) What I want is a function that takes a string as input, parses each character, partitions that to whatever length I want and Prepends zeros to the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). ==== > b = 2; r = 4; > n = 10101111 > p = Reverse[Characters[n]] > {1, 1, 1, 1, 0, 1, 0, 1} > z = Reverse[Partition[p, r]] > {{0, 1, 0, 1}, {1, 1, 1, 1}} (* this is okay *) > b = 2; r = 3; > z = Reverse[Partition[p, r]] > {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be > {{0,1,0},{1,0,1},{1,1,1}}*) What I want is a function that takes a string as input, parses each > character, partitions that to whatever length I want and Prepends zeros to > the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). z = Reverse[Partition[p, r, r, {1,1}, 0] pads 0 on the right before partitioning. This doesn't completely do what you want because when you reverse, those digits are still on the right in the first element (i.e., they are appended instead of prepended. To have them prepended, just add z[[1]] = RotateRight[z[[1]], r Length[z] - Length[p]]; and z will have what you want. Here is an example with Range (easier to see what is happening) In[1]:= p = Range[8]; b = 2; r = 3; In[2]:= z = Reverse[Partition[p, r, r, {1, 1}, 0]] Out[2]= {{7, 8, 0}, {4, 5, 6}, {1, 2, 3}} In[3]:= z[[1]] = RotateRight[z[[1]], r Length[z] - Length[p]]; In[4]:= z Out[4]= {{0, 7, 8}, {4, 5, 6}, {1, 2, 3}} Rob Knapp > ==== Has anyone had any luck getting Mathematica 4.2 to work on a Sun running Solaris 6? I get the following error message when starting Mathematica: ./Mathematica ld.so.1: ./Mathematica: fatal: librt.so.1: open failed: No such file or directory Killed But math works. Any thoughts on this would be appreciated - even if it's just Solaris 6 sucks - Reinstall with Solaris 8/9. I'd rather not go to the trouble of reinstalling the box unless absolutely necessary (It is a 270mhz Ultra 5) -- Alex Dawson 08 9380 1587 School of Electrical, Electronic and Computer Engineering Systems Administrator http://www.ee.uwa.edu.au/~alex ==== > Has anyone had any luck getting Mathematica 4.2 to work > on a Sun running Solaris 6? I get the following error message when starting Mathematica: ./Mathematica > ld.so.1: ./Mathematica: fatal: librt.so.1: open failed: No such file or > directory > Killed But math works. Any thoughts on this would be appreciated - even if it's just > Solaris 6 sucks - Reinstall with Solaris 8/9. I'd rather not go to the > trouble of reinstalling the box unless absolutely necessary (It is a > 270mhz Ultra 5) I'd be tempted to run 'ldd' and see what libraries it needs. On my Solaris 9 box, with Mathematica 4.2 I see: wren /usr/local/stow/Mathematica-4.2/SystemFiles/FrontEnd/Binaries/Solaris % ldd ../Mathematica libXt.so.4 => /usr/lib/libXt.so.4 libXext.so.0 => /usr/lib/libXext.so.0 libXmu.so.4 => /usr/lib/libXmu.so.4 libX11.so.4 => /usr/lib/libX11.so.4 libnsl.so.1 => /usr/lib/libnsl.so.1 libsocket.so.1 => /usr/lib/libsocket.so.1 libc.so.1 => /usr/lib/libc.so.1 libucb.so.1 => /usr/ucblib/libucb.so.1 librt.so.1 => /usr/lib/librt.so.1 libpthread.so.1 => /usr/lib/libpthread.so.1 libSM.so.6 => /usr/lib/libSM.so.6 libICE.so.6 => /usr/lib/libICE.so.6 libm.so.1 => /usr/lib/libm.so.1 libdl.so.1 => /usr/lib/libdl.so.1 libmp.so.2 => /usr/lib/libmp.so.2 libelf.so.1 => /usr/lib/libelf.so.1 libaio.so.1 => /usr/lib/libaio.so.1 libmd5.so.1 => /usr/lib/libmd5.so.1 /usr/platform/SUNW,Ultra-60/lib/libc_psr.so.1 libthread.so.1 => /usr/lib/libthread.so.1 /usr/platform/SUNW,Ultra-60/lib/libmd5_psr.so.1 You should be able to find the libraries it's using, and hopefully it might just be looking in the wrong place, in which case you may be able to create a symbolic link. However, if Solaris 2.6 is not supported (I don't know if it is) it is quite possible it wants a library you don't have, in which case you are stuck unless you re-install a later OS. -- Dr. David Kirkby, Senior Research Fellow, Department of Medical Physics, University College London, 11-20 Capper St, London, WC1E 6JA. Internal telephone: ext 46408 ==== One of these days the company I work for will buy one Mathematica 4.2 versions of the product. window manager. Our Windows systems are running on top of VMWare in Windows XP Professional. In testing using an evaluation version I found that the VMWare/XP version is performing pretty well so that wouldn't be an issue. My main concern (and probably the grounds on which we will base our decision) is the quality of the front-end. The Windows frontend works flawlessly; however, in test-driving earlier versions of Mathematica (3.0 satisfactorily. I didn't spend much time to hunt down the source of the problem, but it is probable that some X key-mapping was wrong making, for example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the Windows frontend. to full satisfaction? I'd be willing to spend a couple of hours to fix some settings, but only if I'm sure it could be done. The bottom line is that I I not if that would mean putting up with a quircky front-end. Sidney Cadot ==== > One of these days the company I work for will buy one Mathematica 4.2 > versions of the product. window manager. Our Windows systems are running on top of VMWare in Windows > XP Professional. > In testing using an evaluation version I found that the VMWare/XP version is > performing pretty well so that wouldn't be an issue. My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. to full satisfaction? I'd be willing to spend a couple of hours to fix some > settings, but only if I'm sure it could be done. The bottom line is that I I > not if that would mean putting up with a quircky front-end. For what it is worth, I have no problems with the front end under Solaris - another varient of Unix. -- Dr. David Kirkby PhD, web page: http://www.david-kirkby.co.uk Amateur radio callsign: G8WRB ==== > One of these days the company I work for will buy one Mathematica 4.2 > Windows versions of the product. window manager. Our Windows systems are running on top of VMWare in > Windows XP Professional. > In testing using an evaluation version I found that the VMWare/XP version > is performing pretty well so that wouldn't be an issue. My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. working to full satisfaction? I'd be willing to spend a couple of hours > to fix some settings, but only if I'm sure it could be done. The bottom > VMWare/Windows, but not if that would mean putting up with a quircky > front-end. For what it is worth, I have no problems with the front end under Solaris > - another varient of Unix. I sincerely wish WRI were more relaxed about allowing people to use the same license on the same hardware, but with a different OS. My understanding is that I would have to buy two licenses if I wanted to switch back and forth That's how open source is paid for. Not everybody has the same amount of spare blood in their veins, or willingness to spill it. For those who release of Mathematica, it would be nice to have a dual boot option. Perhaps it's simply a support issue. It would potentially cause the same customer to require more support if he were switching back and forth between OSs. http://public.globalsymmetry.com/proprietary/com/wri/ch05.html http://66.92.149.152/proprietary/com/wri/ch05.html I still have some tweaks to add to this, such as M-k -> C-k, but it at least demonstrates that (all) things aren't cast in stone. STH ==== Sidney, (or other Unix) for some years so perhaps my experience could help with your decision. Most of the time I run on Windows (2000, not yet XP) because: 1. The Front End is more stable. 2. The Front End is more comfortable in the sense that the keys for deleting, copying, pasting etc. are the ones my fingers expect them to be. 3. Command completion via Ctrl-k, which I use all the time, does not work 4. Generally speaking it takes more mouse clicks and keystrokes to do things I think these are general differences between the user interfaces on these operating systems rather than something specific to the Mathematica implementations. I have tried to overcome them at various time without success. Since I switched from Windows 95 to Windows NT several years ago, 2. I need to have access to certain files created on that system by other people. 3. I want to run long calculations on additional CPUs, leaving my desktop computer free for other things. You can do this between Windows machines kernel via Mathlink. This is very simple and more reliable and robust than Front End and it is easy, say, to transfer input or output betwen systems within a single Front End. I should add that in our lab we can access the the additional convenience of being able to save a notebook from the Windows Front End in the same directory as other files the kernel may be working with. You may not have this option and, of course, you need Mathematica on both systems. These are my personal opinions based on practical experience, I really do not want to enter into any controversy about operating systems. John Jowett One of these days the company I work for will buy one Mathematica 4.2 Windows > versions of the product. window manager. Our Windows systems are running on top of VMWare in Windows > XP Professional. > In testing using an evaluation version I found that the VMWare/XP version is > performing pretty well so that wouldn't be an issue. My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. > working > to full satisfaction? I'd be willing to spend a couple of hours to fix some > settings, but only if I'm sure it could be done. The bottom line is that I I but > not if that would mean putting up with a quircky front-end. > Sidney Cadot > ==== One of these days the company I work for will buy one Mathematica 4.2 > Windows versions of the product. The Redmond chaos code is IMHO no system at all (SCNR). I have only one problem with my Mathematica 4.0 for students, which is that the Export function does not work for gif and other graphics formats. I have posted a question about this into this group but nobody has answered, so I guess there is no fix for that, but on the other hand 4.2 is much newer and should work. > My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. I have no problem concerning the frontend. One has only to adjust the font settings (if you need it, I can send you a pdf file explaining how). -- Hendrik van Hees Fakult.8at f.9fr Physik http://theory.gsi.de/~vanhees/ D-33615 Bielefeld ==== > What I want is a function that takes a string as input, parses each > character, partitions that to whatever length I want and Prepends zeros to > the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). Although you can't see it in your particular example, I think your two Reverse functions would lead to reversed partitions, so I got rid of them. Then it's a matter of following directions for Partition in Help. The only issue is computing kL. The following way is a bit complicated. Perhaps someone will post a simpler way. n = 10101111; r = 3; p = Characters[n]; kL = r + 1 - Mod[Length[p], r, 1]; kR = r; z = Partition[p, r, r, {kL, kR}, 0] Tom Burton ==== Although And and Or don't have to evaluate all their arguments, I find that this is useless in many situations I run into. For instance, I might have a long list 'boolList' of Boolean expressions and I want to know if ANY of them are False, so I calculate And@@boolList In this situation, ALL the expressions in 'boolList' are calculated, even though the first may be False. Here's an example in which I overcome that: boolList = Hold[Print@#; PrimeQ@#] & /@ Range[3, 1000, 2]; ReleaseHold[And @@ boolList] 3 5 7 9 False Bobby Treat -----Original Message----- argument before any of the others, to avoid unneeded computations of the other arguments. He would put that argument first. If Mathematica turned around and sorted the arguments (which is what happens when a function is orderless), then that argument might end up being evaluated last. If the arguments take a significant amount of time to compute, then sorting first may cause the function to take much longer to evaluate. At any rate, if the above is not a concern for you, you may always change the attributes of And and Or to anything you want. Carl Woll Physics Dept U of Washington ----- Original Message ----- > However, the arithmetical functions are Orderless: Attributes/@{Plus,Times}//ColumnForm {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} > {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} ------------------- > Evgeni Trifonov > Vladivostok, Russia > ==== Maybe this will work for you: groupDigits[n_String, k_Integer] := Partition[ PadLeft[Characters[n], k Ceiling[StringLength[n]/k], 0], k] Bobby Treat -----Original Message----- {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be {{0,1,0},{1,0,1},{1,1,1}}*) What I want is a function that takes a string as input, parses each character, partitions that to whatever length I want and Prepends zeros to the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). ==== After I load a package using < b = 2; r = 4; > n = 10101111 > p = Reverse[Characters[n]] > {1, 1, 1, 1, 0, 1, 0, 1} > z = Reverse[Partition[p, r]] > {{0, 1, 0, 1}, {1, 1, 1, 1}} (* this is okay *) > b = 2; r = 3; > z = Reverse[Partition[p, r]] > {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be > {{0,1,0},{1,0,1},{1,1,1}}*) What I want is a function that takes a string as input, parses each > character, partitions that to whatever length I want and Prepends zeros to > the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). ==== Dear Group, It is a pleasure write to you again. I have three questions to ask. Alexandre Costa Question One: The below code is working fine but I think there are more elegant ways of doing so. Any suggestions are VERY WELCOME. << DiscreteMath`Permutations` individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] CutPosition = 3 ; CutLength = 4 ; CutSequence = Take[Drop[individual1, CutPosition], CutLength] SonOne = individual2; Do[ If[MemberQ[SonOne, CutSequence[[i]]], SonOne = Delete[SonOne, Position[SonOne, CutSequence[[i]]]]], {i, 1, CutLength}]; SonOne SonOne = RotateLeft[SonOne, 1] Do[SonOne = Insert[SonOne, Reverse[CutSequence][[i]], CutPosition + 1], {i, 1, CutLength}] SonOne Question Two: How can I change points properties (such as Size and Color) for the plot below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, {6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] Question Three: Why the Goto statement below is not working? q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] Reply-To: murray@math.umass.edu ==== I presume packagename is a context name, e.g., Graphics`Colors` . Then evaluating the expression Names[packagename*] containing the wildcard symbol * will probably do what you want. It may tell you more than you want to know unless the package was decently written. By decently I mean that names not needing to be known to the outside world have been enclosed within a Private context within the package's context. > After I load a package using > < the source file? -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 ==== Jose, I generally use the Needs statement to load a package. It avoids double loading and all the error messages that result. Say Needs[Graphics`Graphics`] Then to obtain information on the routines in the package just use... ?Graphics`Graphics`* names in the package. If you click on any of the names you obtain the usage message for the name. (On earlier Mathematica versions you only obtain a list of the names and you have to use ?name to obtain the usage message.) More link. If you click on that it will bring you to the relevant Help page. (Private packages may not have that feature.) David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator Reply-To: ==== Maybe there's a faster way -- I hope so! -- but here's my answer: n = 2^26 Timing[RealDigits[N[Pi - 3, n], 10, 20, 19 - n]] 67108864 {15027.922*Second, {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, 4, 0, 9, 8, 0, 3}, -67108844}} hrMinSec[15027.922] {4*hours, 10*minutes, 27.92200000000048*seconds} Bobby Treat -----Original Message----- ==== Could you tell me the CPU you used and its speed etc...i am curious, other programs out there. > Maybe there's a faster way -- I hope so! -- but here's my answer: n = 2^26 > Timing[RealDigits[N[Pi - 3, n], 10, 20, 19 - n]] 67108864 > {15027.922*Second, > {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, 4, 0, 9, 8, 0, 3}, > -67108844}} hrMinSec[15027.922] > {4*hours, 10*minutes, 27.92200000000048*seconds} Bobby Treat -----Original Message----- > 4 for me? Could someone calculate the number Pi to 67,108,864 (2^26) decimal > places > I made the calculation in another program and would like to verify its > ==== > Could you tell me the CPU you used and its speed etc...i am curious, > other programs out there. I used one processor of a dual 1GH Mac and got the same answer with the following speed: 4.2 for Mac OS X (June 4, 2002) oldmax = $MaxPrecision 6 1. 10 $MaxPrecision = Infinity Infinity With[{n = 2^26}, Timing[ pd = RealDigits[N[Pi, n + 1], 10, 20, 19 - n]; ]] {28794.1 Second, Null} MaxMemoryUsed[] 512055204 pd {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, 4, 0, 9, 8, 0, 3}, -67108844} Tom Burton -- ==== So would it take about the same amont of time for the complete printout of digits? Of course it would take a few additional seconds to format the output... Or does Mathematica take alot less time when it truncates the output? > Could you tell me the CPU you used and its speed etc...i am curious, > other programs out there. I used one processor of a dual 1GH Mac and got the same answer with the > following speed: 4.2 for Mac OS X (June 4, 2002) > oldmax = $MaxPrecision > 6 > 1. 10 > $MaxPrecision = Infinity > Infinity > With[{n = 2^26}, Timing[ > pd = RealDigits[N[Pi, n + 1], 10, 20, > 19 - n]; ]] > {28794.1 Second, Null} > MaxMemoryUsed[] > 512055204 > pd > {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, > > 4, 0, 9, 8, 0, 3}, -67108844} Tom Burton ==== Here's an answer to Question 1: individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] cutPosition = 3; cutLength = 4; cutSequence = Take[Drop[individual1, cutPosition], cutLength] sonOne = Complement[individual2, cutSequence] sonOne = RotateLeft[sonOne, 1] sonOne = Join[Take[sonOne, cutLength - 1], cutSequence, Drop[sonOne, cutLength - 1]] Bobby Treat -----Original Message----- << DiscreteMath`Permutations` individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] CutPosition = 3 ; CutLength = 4 ; CutSequence = Take[Drop[individual1, CutPosition], CutLength] SonOne = individual2; Do[ If[MemberQ[SonOne, CutSequence[[i]]], SonOne = Delete[SonOne, Position[SonOne, CutSequence[[i]]]]], {i, 1, CutLength}]; SonOne SonOne = RotateLeft[SonOne, 1] Do[SonOne = Insert[SonOne, Reverse[CutSequence][[i]], CutPosition + 1], {i, 1, CutLength}] SonOne Question Two: How can I change points properties (such as Size and Color) for the plot below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, {6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] Question Three: Why the Goto statement below is not working? q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] ==== I would like to build my Mathematica notebooks in manner which allows me to carry out two overlapping purposes: 1) prototype an algorithm completely within Mathematica, 2) use Mathematica as a partial evaluator to splice derived expressions into a C language version of the algorithm ( with the aid of the Format package from MathSource). The key complication in doing this is that for the Mathematica prototype I want everything to be evaluated, while for splicing I want the results from some of the functions to be retained as data in temporary variables. A first step towards these purposes is simple: write my component functions so they operate on lists (the natural form of the prototype data), then provide lists of arrays for arguments which I would like to supply as data in the resulting C language output forms. An example: -------------------------------------------------- In[1]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[2]:= f[x_,y_] := {y, 1}.t[x] In[3]:= f[{1,2,3,4},2] Out[3]= 3 In[4]:= f[Array[x,4],2] Out[4]= -x[1] + x[2] + 2 (-x[3] + x[4]) In[5]:= CAssign[fcnval, f[Array[x,4],2], AssignToArray->{x}] Out[5]//OutputForm= fcnval=-x[1]+x[2]+2.*(-x[3]+x[4]); -------------------------------------------------- For various reasons, however, I would like certain expressions of my symbolic derivation to be treated as data for the C language version. In the above example, for instance, I would like the array that function t produces to be a data array. The modification of the above example: -------------------------------------------------- In[6]:= tc[x_] := Array[tt,2] In[7]:= fc[x_,y_] := {y, 1}.tc[x] In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, fc[Array[x,4],2], AssignToArray->{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; -------------------------------------------------- But I don't want to carry around two versions of everything, nor do I really want to thread all of the supporting functions through my definitions in order to choose the correct function for the purpose I would rather define the C language alternatives only for functions like t and tc in the example, with f using the appropriate one depending on some evaluation flag that I set at the highest level. For example, it would be nice to be able to sprinkle in the C language alternatives with a construct like In[10]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[11]:= DefineTemporaryForm[t[x_]] := Array[tt,Length[x]/2] then be able to write In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, UseTemporaryForm[f[Array[x,4],2]], AssignToArray- >{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; I would appreciate any pointers on a good, clean and hopefully simple way to do this within Mathematica! Alex ==== I've been using Mathematica 4.1 on Win98 as a word processor for math-related documents, but often people that need to see the documents don't have Mathematica, and for whatever reason on my computer the HTML saves don't work at all. I'd like to export to PDF format. I can export images to PDF format no problem using, for example Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], and I can export cells correctly to GIF, JPEG, and WMF formats (probably more, those are the only ones I tested) using, for example Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy As->Cell Expression)...> ]] When I change the filename to a .PDF and evaluate the cell, the program displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf ' message as if a file was created, but no file is created anywhere with any name that I could find with Start->Find->[All files and folders created in the previous day]. Is there a limitation to PDF exporting I don't know about? Do I need to upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I need a faster computer? A patch? Something else? ==== I recently communicated with technical support about precisely this issue. Here's their reply: ``PDF and AI export use psrender, which is a MathLink program that interfaces with the kernel. Since the kernel has no knowledge of how cells are formatted, export cannot generate PDF and AI for cells, just Graphics. Note that this is contrary to the documentation, which says: ``All graphics formats in Export can handle any type of 2D or 3D Mathematica graphics. ... They can also handle Notebook and Cell objects. --- Selwyn Hollis > I've been using Mathematica 4.1 on Win98 as a word processor for > math-related documents, but often people that need to see the documents > don't have Mathematica, and for whatever reason on my computer the HTML > saves don't work at all. I'd like to export to PDF format. I can export > images to PDF format no problem using, for example > Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], > and I can export cells correctly to GIF, JPEG, and WMF formats (probably > more, those are the only ones I tested) using, for example > Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy > As->Cell Expression)...> ]] > When I change the filename to a .PDF and evaluate the cell, the program > displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf > ' message as if a file was created, but no file is created anywhere with any > name that I could find with Start->Find->[All files and folders created in > the previous day]. > Is there a limitation to PDF exporting I don't know about? Do I need to > upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I > need a faster computer? A patch? Something else? > ==== Here's a smoother animation, taking into account the period and cutting the step size in half (without using more frames): Do[Show[curve, Graphics[Disk[{ xx[t], Cosh[xx[t]]}, 0.035]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes -> None], {t, 0, 2.3, 0.05}] SelectionMove[EvaluationNotebook[], All, GeneratedCell] FrontEndTokenExecute[OpenCloseGroup] FrontEndTokenExecute[SelectionAnimate] Bobby Treat -----Original Message----- and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, I intend to make an animation in which ball A rolls down on an inclined plane from the left whilst ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. x-axis is time t, y-axis is height h. Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de ==== I would like to build my Mathematica notebooks in manner which allows me to carry out two overlapping purposes: 1) prototype an algorithm completely within Mathematica, 2) use Mathematica as a partial evaluator to splice derived expressions into a C language version of the algorithm (with the aid of the Format package from MathSource). The key complication in doing this is that for the Mathematica prototype I want everything to be evaluated, while for splicing I want the results from some of the functions to be retained as data in temporary variables. A first step towards these purposes is simple: write my component functions so they operate on lists (the natural form of the prototype data), then provide lists of arrays for arguments which I would like to supply as data in the resulting C language output forms. An example: -------------------------------------------------- In[1]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[2]:= f[x_,y_] := {y, 1}.t[x] In[3]:= f[{1,2,3,4},2] Out[3]= 3 In[4]:= f[Array[x,4],2] Out[4]= -x[1] + x[2] + 2 (-x[3] + x[4]) In[5]:= CAssign[fcnval, f[Array[x,4],2], AssignToArray->{x}] Out[5]//OutputForm= fcnval=-x[1]+x[2]+2.*(-x[3]+x[4]); -------------------------------------------------- For various reasons, however, I would like certain expressions of my symbolic derivation to be treated as data for the C language version. In the above example, for instance, I would like the array that function t produces to be a data array. The modification of the above example: -------------------------------------------------- In[6]:= tc[x_] := Array[tt,2] In[7]:= fc[x_,y_] := {y, 1}.tc[x] In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, fc[Array[x,4],2], AssignToArray->{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; -------------------------------------------------- But I don't want to carry around two versions of everything, nor do I really want to thread all of the supporting functions through my definitions in order to choose the correct function for the purpose I would rather define the C language alternatives only for functions like t and tc in the example, with f using the appropriate one depending on some evaluation flag that I set at the highest level. For example, it would be nice to be able to sprinkle in the C language alternatives with a construct like In[10]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[11]:= DefineTemporaryForm[t[x_]] := Array[tt,Length[x]/2] then be able to write In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, UseTemporaryForm[f[Array[x,4],2]], AssignToArray->{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; I would appreciate any pointers on a good, clean and hopefully simple way to do this within Mathematica! Alex ==== To find out what loaded contexts are related to the package, use: Contexts[Integrate`*] {Integrate`,Integrate`Elliptic`} To see the symbols exported by the context, execute: Names[Integrate`*] {(* too many to list here *)} Names[Integrate`*`*] {Integrate`Elliptic`Elliptic} To find out what context a symbol comes from: Context[Integrate] System` Bobby Treat -----Original Message----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator Reply-To: ==== Oops! That should be individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] cutPosition = 3; cutLength = 4; cutSequence = Take[Drop[individual1, cutPosition], cutLength] sonOne = DeleteCases[individual2, _?(MemberQ[cutSequence, #] &)] sonOne = RotateLeft[sonOne, 1] sonOne = Join[Take[ sonOne, cutLength - 1], cutSequence, Drop[sonOne, cutLength - 1]] Complement returns a sorted result, and you didn't want that. Bobby Treat -----Original Message----- sonOne = Join[Take[sonOne, cutLength - 1], cutSequence, Drop[sonOne, cutLength - 1]] Bobby Treat -----Original Message----- << DiscreteMath`Permutations` individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] CutPosition = 3 ; CutLength = 4 ; CutSequence = Take[Drop[individual1, CutPosition], CutLength] SonOne = individual2; Do[ If[MemberQ[SonOne, CutSequence[[i]]], SonOne = Delete[SonOne, Position[SonOne, CutSequence[[i]]]]], {i, 1, CutLength}]; SonOne SonOne = RotateLeft[SonOne, 1] Do[SonOne = Insert[SonOne, Reverse[CutSequence][[i]], CutPosition + 1], {i, 1, CutLength}] SonOne Question Two: How can I change points properties (such as Size and Color) for the plot below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, {6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] Question Three: Why the Goto statement below is not working? q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] ==== I would appreciate help with these problems: 1. I'm plotting several thousand points, which I can do either with something like this (this is a test): w = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; x = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; y = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; z = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; dw = Graphics[{PointSize[0.01], RGBColor[ 1, 0, 0], w}]; dx = Graphics[{PointSize[0.01], RGBColor[.8, .8, .8], x}]; dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; Show[dw, dx, dy, dz, AspectRatio -> Automatic, PlotRange -> {{0, 1}, {0, 1}}, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026], This gives me dots in 4 colors for distinguishing different kinds of points in my real application. This works fine but needs the Point structure. Or, I can do (this is for one kind of point), t = Table[{Random[], Random[]}, {i, 1, 1024}]; ListPlot[t, AspectRatio -> Automatic, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026] ]; which seems simpler and may fit into the rest of the program more easily. 1. How do I get the RGBColor Rule or the equivalent into the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. How do I get ListPlot to put down 4 plots superimposed? Or can't I? 3. In either case, I need to make the whole plot area about twice as big. That is, it now occupies about a 4 square. To see details better in my real plot, and because with 16k points the small plot just looks almost like a solid blur, I want to make it more like 8 square, or as big as will fit the screen (without changing the plot range or anything else). There must be a scale factor somewhere. ==== Steve, You could try something like this: Needs[Graphics`Colors`] Clear[t]; Do[t[i] = Table[{Random[], Random[]}, {i, 1, 1024}], {i, 4}]; Show[Graphics[ {PointSize[0.005], RoyalBlue, Point /@ t[1], OrangeRed, Point /@ t[2], SpringGreen, Point /@ t[3], CadmiumLemon, Point /@ t[4]}], AspectRatio -> Automatic, Frame -> True, PlotRegion -> {{0.02, 0.96}, {0, 1}}, Background -> IvoryBlack, ImageSize -> 700]; The overall size of the plot can be controlled with the ImageSize option. ListPlot is more a hindrance than a help - throw it in the ash can. Just Map Point onto the lists of point coordinates. Give the color before each set of points. I adjusted the PlotRegion to obtain some black margin on all sides of the frame. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; Show[dw, dx, dy, dz, AspectRatio -> Automatic, PlotRange -> {{0, 1}, {0, 1}}, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026], This gives me dots in 4 colors for distinguishing different kinds of points in my real application. This works fine but needs the Point structure. Or, I can do (this is for one kind of point), t = Table[{Random[], Random[]}, {i, 1, 1024}]; ListPlot[t, AspectRatio -> Automatic, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026] ]; which seems simpler and may fit into the rest of the program more easily. 1. How do I get the RGBColor Rule or the equivalent into the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. How do I get ListPlot to put down 4 plots superimposed? Or can't I? 3. In either case, I need to make the whole plot area about twice as big. That is, it now occupies about a 4 square. To see details better in my real plot, and because with 16k points the small plot just looks almost like a solid blur, I want to make it more like 8 square, or as big as will fit the screen (without changing the plot range or anything else). There must be a scale factor somewhere. ==== Bobby, Your ODE is different from both mine and Borut's. You do however get the same as mine with your approach, if you differentiate the total energy rather than the Lagrangian. KE = Simplify[(x'[t]^2 + D[f[x[t]], t]^2)/2]; PE = g*f[x[t]]; totalE = KE + PE; treat = D[totalE, t] == 0 x''[t] - (x''[t] /. First[Solve[treat, x''[t]]]//Apart) == 0 Borut's ODE differs only in his factor of 2 in the first-order term. I suspect that might have been a typo... Borut? By the way, some nice animations of mechanical systems (some based on the same sort of approach) can be seen here: http://www.math.armstrong.edu/faculty/hollis/DEmovies/ --Selwyn > The two of you derived slightly different ODE's. I think Selwyn's is > correct, but I only had one physics course, 30 years ago. Here's a notebook expression showing how Selwyn's approach can be used > to derive the ODE for y[t] = f[x[t]], with arbitrary f. It shows that > solution in a form that is easily compared with Borut's ODE, and then it > shows my own solution (same as Borut's, by a slightly simpler method). Bobby Treat > KE = Simplify[(x'[t]^2 + D[f[x[t]], t]^2)/2]; > PE = g*f[x[t]]; > L = KE - PE; > treat = D[L, t] == 0 > ==== I've modified Selwyn's solution to make it more general. In particular, the height can be specified (up to about 35 meters). The differential equation is solved for t=0 to 5 first. The quarter-period is computed by finding a zero; then the differential equation is solved again for t=0 to the quarter-period, and the solution is extended using reflection and periodicity. This yields a higher-precision solution. Then I graph the solution, with a stepsize equal to period/40, from t=0 to 'period', labeling each frame with the values of t, x[t], and y[t]. Using a step size that divides period/4 guarantees the lowest point is reached ON a frame when appropriate. Here's the solution as a notebook expression: Notebook[{ Cell[CellGroupData[{ Cell[Borut L's solution:, Subsubtitle], Cell[TextData[StyleBox[Having noticed your statement ... BEYOND MY MEANS I thing you aren't yetnfamiliar with Lagrangian formalism. It's quite easy to derive a generalnequation of motion for a point mass, subjected to gravity and to moving on ancurve f = y(x) (i.e. f = Cosh[#]&).nn1) I'll leave re-deriving equation to you, here is what I've got (just copynpaste it).:, FontFamily->Courier New, FontSize->10, CharacterEncoding->WindowsANSI]], Text], Cell[BoxData[ RowBox[{selwyn, =, RowBox[{First, [, RowBox[{ RowBox[{ RowBox[{ RowBox[{x, ''}], [, t, ]}], /., RowBox[{Solve, [, RowBox[{diffeq, ,, RowBox[{ RowBox[{x, ''}], [, t, ]}]}], ]}]}], //, Simplify}], ]}]}]], Input], Cell[BoxData[ RowBox[{borut, =, RowBox[{First, [, RowBox[{ RowBox[{ RowBox[{x, ''}], [, t, ]}], /., RowBox[{Solve, [, RowBox[{ RowBox[{getEq, [, Cosh, ]}], ,, RowBox[{ RowBox[{x, ''}], [, t, ]}]}], ]}]}], ]}]}]], Input], Cell[BoxData[ RowBox[{ RowBox[{getEq, [, f_, ]}], :=, [IndentingNewLine], RowBox[{Simplify, [, RowBox[{ RowBox[{ RowBox[{ RowBox[{x, ''}], [, t, ]}], +, RowBox[{ SuperscriptBox[ RowBox[{ RowBox[{x, '}], [, t, ]}], 2], , FractionBox[ RowBox[{2, , RowBo