A4 ====it works with any graphicsNotebookWrite[SelectedNotebook[], GridBox[{Cell[GraphicsData[PostScript, DisplayString[#, MPS]], Graphics] & /@ {leftGraphics, rightGraphics}}]] Jens> (1) Is there a way in Mathematica 4.2 to put two separate gifs into a> single, cell side by side (with some intervening space), without> having to combine them in some graphics program Ŝrst?> In particular, Iıd like to do that within a text cell.> Even in a new Input cell, if I Ŝrst create a GridBox (via Inut>Create> Table/Matrix/Palette) and then try to insert the Ŝrst gif (via> Edit>Insert Object>Create from File ....), Mathematica promptly> crashes. (Mathematica 4.2 under Windows 2000.)> I just donıt see how to get anything other than a single gif into a> cell.> (2) Is there a way to cause a gif imported into a Mathematica 4.2> notebook to become a hyperlink -- so that when the user clicks on the> gif the hyperlinkıs target is summoned?> (My aim in all this is to use Mathematica to create web pages with> high mathematical content -- saving the notebook as HTML+MathML --> without having to do any extensive editing of the resulting .xml and> related Ŝles. That way as the source Mathematica notebook changes, I> would need only to re-export without further tinkering with the .xml> Ŝle, etc.)> --> Murray Eisenberg Internet: murray@math.umass.edu> Mathematics & Statistics Dept. Voice: 413-545-2859 (W)> University of Massachusetts 413-549-1020 (H)Reply-To: kuska@informatik.uni-leipzig.de====set the PlotRange explicit PlotRange->{{0,largeX},Automatic} Jens> I am using MultipleListPlot to plot a range of 2D graphs and have found that> the last graph, which has a much greater (by a factor of 4) x range than the> others does not plot completely but is truncated in the x direction. By> removing the Frame, I can see the points where these lie outside the Frame> but these are not joined etc. How do I get over this?> -> Malcolm WoodruffReply-To: kuska@informatik.uni-leipzig.de====what may be in the *.m Ŝles? Mathematica commands ? thatyou can load into the kernel ? Makr all your input cells in the notebook as initialization,save it as an *.m Ŝle, add a Quit[] as the last commandto the *.m Ŝle and run it withmath << yourJustGeneratedMFile JensRegardds> Probably a rather simple question: what is the easiest way to open a> notebook, execute it, then quit, from the command line? I would like to be> able to do this from a MakeŜle.> SidneyReply-To: kuska@informatik.uni-leipzig.de====do you realy think that1.07577/( 1+7.12336*10^-7 (1. + z)^2 )with the z inside is numerical ? or do you meanF[z_?NumericQ]: = NIntegrate[f[y,z], {y, 0, InŜnity}] Jens> Iıve this problem with NIntegrate:> **********************************************> In[1]=f[y_,z_]: = (y^4/( (1+(8.44*10^-4)^2 * (1+z)^2 y^2) (Exp[z]+1) )> In[2]=F[z_]: = NIntegrate[f[y,z], {z, 0, InŜnity}> **********************************************> Mathematica 4.0 says:> ************************************************************* ***************> *> NIntegrate: : inum : Integrand 1.07577/( 1+7.12336*10^-7 (1. + z)^2 ) is not> numerical at {y}={1.}.> ************************************************************* ***************> **> What is it??> --> Rob_jack====>> do you realy think that>> 1.07577/( 1+7.12336*10^-7 (1. + z)^2 )>> with the z inside is numerical ? or do you mean>> F[z_?NumericQ]: = NIntegrate[f[y,z], {y, 0, InŜnity}]>Iım a newbie, bat I mean:*************************In[1]= NumericQ[z]Out[1]=False*************************BTW, z is a real number.--Rob_jackReply-To: kuska@informatik.uni-leipzig.de====not with Mathematica 4.2. But the problem can be the page widththat may be used to convert the Cell[], if you can you shoulduse the Graphics[]/Graphics3D[] .. inside the Cell orthe PostScript string in the GraphicsData[] Jens> The following is a button that will export a selected graphic as a JPEG,> ButtonBox[JPEG,> ButtonFunction :>> Module[{sel},> SelectionMove[InputNotebook[], All, Cell];> sel = NotebookRead[InputNotebook[]];> If[Head[sel] === Cell,> If[!ValueQ[dpi], dpi = Automatic];> ImageSize -> Automatic, ImageResolution -> dpi,> ConversionOptions -> {Quality -> 75}]]],> ButtonEvaluator -> Automatic, Active -> True]//DisplayForm> It works Ŝne as long as the graphic is no wider than about 330 pixels.> If the graphic is wider than 330 pixels, then the size of exported> graphic is correct, but everything on the right beyond the Ŝrst 330> pixels is blank. There seems to be no problem with the height though.> Any ideas on how to Ŝx or get around this problem?> ---> Selwyn Hollis====>-----Original Message----->Sent: Wednesday, September 11, 2002 9:28 AM>>A commonly used symbol for the Floor function is a square >bracket with the>upper indents removed. Is this symbol part of Mathematicaıs >built-in symbols? I>think not, so then, can it be constructed by hand.>>Jack>>Jack, yes it is already built-in! Bring up the palette with menu: File > Palettes> CompleteCharachters; there is a section Operators > General, where youıllŜnd what you want.Alternatively type Œescı l f Œescı Œescı r f Œescı, orinstead of the esc-sequence use the corresponding mark-ups. For output tryTraditionalForm. If you donıt like that for all of your output, you may justadd a formatting rule for Floor:In[7]:= Unprotect[Floor]In[8]:=Floor /: MakeBoxes[Floor[expr_], StandardForm] := RowBox[{[LeftFloor], MakeBoxes[expr, StandardForm], [RightFloor]}]In[9]:= Protect[Floor]In[11]:= Floor /@ ([Pi] + [Lambda])Out[11]= 3 + [LeftFloor][Lambda][RightFloor]Same thing with Ceiling, BTW.--HartmutReply-To: jmt@dxdydz.net====mathematica -primaryModiŜerMask etcsee man mathematica for other (very useful) options> PS: One more quick one: Why does the front end act funny when I have the> Your X server is set up so that the NumLock key is mapped to Mod2. I> learned by accident that Mod2 is actually quite useful. Mod2-click on a> cell selects all cells of that type in the current notebook. This is an> easy way to delete all the graphics cells and output cells in a notebook to> reduce Ŝle size. An annoying aspect is that Mod2-click means press> NumLock, click, then press NumLock again to turn it off. You should be able> to map a different key to Mod2 using xmodmap. Remapping modiŜer keys in X> is awfully annoying, though. I recommend xkeycaps> (http://www.jwz.org/xkeycaps/).> Reply-To: kuska@informatik.uni-leipzig.de====no because the PostScript creation know nothingabout the notebook frontend. Mathematica does itsgraphics in PostScript since version 1.0 but the notebook frontend was introduced in version 2.x andthe actual typsetting/markup format was introducedin version 3.0. Jens> Is it possible to conŜgure a style sheet so that functions or data shown in> graphs are coloured (colored :)) in working but black in printing...without> actually re-executing the function that created the graphics?> thanks> Mike====>-----Original Message----->Sent: Wednesday, September 11, 2002 9:28 AM>Is it possible to conŜgure a style sheet so that functions or >data shown in>graphs are coloured (colored :)) in working but black in >printing...without>actually re-executing the function that created the graphics?>>thanks>>Mike>>Mike, if for some reason you canıt conŜgure your color printer when printing, youmay rerender your graphics in Mathematica with different options, suchavoiding costly recalculation. You may either use something special, asin...In[1]:=ContourPlot[Sin[x]^2 Sin[y]^2, {x, 0, Pi}, {y, 0, Pi}, ColorFunction -> Hue, ContourStyle -> GrayLevel[1], PlotPoints -> 100]Out[1]=[SkeletonIndicator]ContourGraphics[ SkeletonIndicator]In[2]:=Show[%, ColorFunction -> (GrayLevel[1 - #] &)]...using a B/W color function. Or in general you may use the optionColorOutput:In[3]:=Plot3D[Sin[x]^2 Sin[y]^2, {x, 0, Pi}, {y, 0, Pi}]Out[3]=[SkeletonIndicator]SurfaceGraphics[ SkeletonIndicator]...In[5]:=Show[%%, ColorOutput -> GrayLevel]--Hartmut====> This graphs f from 0 to 8 Pi on a logarithmic horizontal scale:>> f[x_] := 1 + Abs[Sin[x]/x]> Plot[f@Exp@x, {x, 0, Log[8Pi]}, PlotRange -> All];The graph itself is indeed what is desired, but the labelling of the x-axisis then incorrect for a logarithmic scale. For example, regardless of thescale used, any proper graph must show that the Ŝrst minimum occurs atx = Pi. But the method you suggest makes it seem that it occurs at approx.1.14 (precisely Log[Pi]).David> -----Original Message----->Reply-To: kuska@informatik.uni-leipzig.de====Needs[Graphics`Graphics`] LogPlot[Exp[-x],{x,0,10}]?? Jens> ====Iım trying to write a fast empirical cummulative distribution function(CDF). Empirical CDFs are step functions that can be expressed interms of a Which statement. For example, given the list ofobservations {1, 2, 3},f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}and f is continuous from the right.When the number of observations is large, the Which statementevaluates fairly slowly (even if it has been Compiled). SinceInterpolationFunction evaluates so much faster in general, Iıve triedto use Interpolation with InterpolationOrder -> 0. The problem is thatthe resulting InterpolatingFunction doesnıt behave the way (I think)it ought to. For example, letg = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->0]Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.In addition, g is continuous from the left rather than from the right.Obviously I am not aware of the considerations that went intodetermining the behavior of InterpolationFunction whenInterpolationOrder -> 0.So I have two questions: (1) Does anyone have any opinions about how InterpolatingFunctionought to behave with InterpolationOrder -> 0?(2) Does anyone have a faster way to evaluate an empirical CDF than acompiled Which function?By the way, hereıs my current version:CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := Block[{x}, Compile[{{x, _Real}}, Evaluate[ Which @@ Flatten[ Append[ Transpose[{ Thread[x < Sort[list]], Range[0, 1 - 1/#, 1/#] & @ Length[list] }], {True, 1}]] ]]]--Mark====Daniel Lichtblau made two suggestions that allow one to useInterpolation the way I wanted. First, to make the resulting functionright-continuous, change the sign twice. Second, to make the end pointreturn the correct value, add an extra (phantom) observation (with anextra (irrelevant) value). (The phantom observation is made at thehigh end because of the sign reversals.) Hereıs the code I cooked upbased on his suggestions:MakeEmpiricalCDF::usage = MakeEmpiricalCDF[list] returns a functionthat evaluates the empirical CDF given the observations in the list.The function is deŜned on the entire real line.MakeEmpiricalCDF[list_?(VectorQ[#, NumericQ]&)] := Module[{n, s, a, r, idata}, n = Length[list]; s = Sort[list]; a = Append[s, s[[-1]] + 1]; (* phantom obs. *) r = Range[1/n, 1 + 1/n, 1/n]; (* phantom value 1 + 1/n *) idata = Last /@ Split[Transpose[{-a, r}], #1[[1]] == #2[[1]]&]; (* -a is the Ŝrst sign change *) Block[{x}, Function @@ {x, Which @@ { x < s[[ 1]], 0., x > s[[-1]], 1., True, Interpolation[idata, InterpolationOrder -> 0][-x] (* -x is the second sign change *) }}] ]The construction Last /@ Split[ ... ] accounts for duplicate values.Here are two examples. Needs[Statistics`ContinuousDistributions`]list1 = RandomArray[NormalDistribution[0, 1], 100];f1 = MakeEmpiricalCDF[list1];Plot[f1[x], {x, -4, 4}]list2 = Table[Random[Integer, {1, 10}], {10}];f2 = MakeEmpiricalCDF[list2];Plot[f2[x], {x, 0, 11}]--Mark> Iım trying to write a fast empirical cummulative distribution function> (CDF). Empirical CDFs are step functions that can be expressed in> terms of a Which statement. For example, given the list of> observations {1, 2, 3},> f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&> is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}> and f is continuous from the right.> When the number of observations is large, the Which statement> evaluates fairly slowly (even if it has been Compiled). Since> InterpolationFunction evaluates so much faster in general, Iıve tried> to use Interpolation with InterpolationOrder -> 0. The problem is that> the resulting InterpolatingFunction doesnıt behave the way (I think)> it ought to. For example, let> g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->> 0]> Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.> In addition, g is continuous from the left rather than from the right.> Obviously I am not aware of the considerations that went into> determining the behavior of InterpolationFunction when> InterpolationOrder -> 0.> So I have two questions: > (1) Does anyone have any opinions about how InterpolatingFunction> ought to behave with InterpolationOrder -> 0?> (2) Does anyone have a faster way to evaluate an empirical CDF than a> compiled Which function?> By the way, hereıs my current version:> CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]> --Mark==== I am new to numerical computing. I have a equation dQ/dz = exp(-i*4*a^2*z - i*pi/4)*f(z,t)/sqrt(4*pi*z) where z is the position range from 0 to 10, t is the time range from0 to 10 f(z,t) = integration of exp(i*(t-t1-z)^2/z)*g(t1) from t1=-100 to100 g(t1) = d^3 sech(t1) / dt^3 I would like to solve Q(z,t), however, I am a new to mathematica.Can anyone help me?====I know that there is an input form. I want the output to have the sameform rather than look like Floor[x]. Sorry,Jack>> A commonly used symbol for the Floor function is a square bracket with the> upper indents removed. Is this symbol part of Mathematicaıs built-in symbols? I> think not, so then, can it be constructed by hand.>> Jack>>Reply-To: kuska@informatik.uni-leipzig.de====doesMakeBoxes[Floor[x_], fmt_:StandardForm] := RowBox[{[LeftFloor], ToBoxes[x, fmt], [RightFloor]}]help you ? Jens> I know that there is an input form. I want the output to have the same> form rather than look like Floor[x]. Sorry,> Jack>> A commonly used symbol for the Floor function is a square bracket with the> upper indents removed. Is this symbol part of Mathematicaıs built-in symbols? I> think not, so then, can it be constructed by hand.>> Jack>>====Recent threads about word processing and typesetting have got me dreaming again...Wouldnıt it be nice if someone developed a package that provided a function like this: DisplayTeX[ some TeX code ]which would cause the kernel to generate PostScript for the typeset text, to be displayed by the front end?I doubt that WRI will ever consider this, but surely thereıs someone out there whoıs both a TeXpert and a Mathematica guru who can do it. No doubt thereıs money to be made.Probably just a pipe dream...---Selwyn HollisReply-To: kuska@informatik.uni-leipzig.de====you mean the inverse of TeXForm[] ?For what ? A TeXpert && Mathematica guru && MathLink experthas a TeX frontend, that translate a TeXNotebook(that is a TeX Ŝle with some Mathematica Input/Output environments) and send the input cells to a kerneland insert the output into the Ŝnal TeX Ŝle ...The most of the remaining work like creating hyperlinksto references and Ŝgures is done my LaTeX and pdfLaTeX,with help of CTAN and some macros one generate almost everylayout *and* I have more than 20 books about TeX/LaTeX (including Don Knuths excelent manuals) but I have nota single book about the Mathematica Frontend.The way is not to teach TeX to the frontend, the way isto teach TeX a bit Mathematica.And a TeXpert will never switch from his beloved TeXto the Frontend and itıs typesetting -- thatıs whyhe is a TeXpert. Jens> Recent threads about word processing and typesetting have got me> dreaming again...> Wouldnıt it be nice if someone developed a package that provided a> function like this:> DisplayTeX[ some TeX code ]> which would cause the kernel to generate PostScript for the typeset> text, to be displayed by the front end?> I doubt that WRI will ever consider this, but surely thereıs someone out> there whoıs both a TeXpert and a Mathematica guru who can do it. No> doubt thereıs money to be made.> Probably just a pipe dream...> ---> Selwyn Hollis====> you mean the inverse of TeXForm[] ?> For what ? A TeXpert && Mathematica guru && MathLink expert> has a TeX frontend, that translate a TeXNotebook> (that is a TeX Ŝle with some Mathematica Input/Output > environments) and send the input cells to a kernel> and insert the output into the Ŝnal TeX Ŝle ...Congratulations to you if you can do that and if youıre happy with it. Iıd prefer life to be a bit simpler. The point is that many users of Mathematica already have sufŜcient knowledge of TeX/LaTeX to typeset very complicated mathematics and get excellent results with little or no grief. To achieve even close to the same quality with Mathematica alone can require ten times the effort and a hundred times the grief.---Selwyn> The most of the remaining work like creating hyperlinks> to references and Ŝgures is done my LaTeX and pdfLaTeX,> with help of CTAN and some macros one generate almost every> layout *and* I have more than 20 books about TeX/LaTeX > (including Don Knuths excelent manuals) but I have not> a single book about the Mathematica Frontend.> The way is not to teach TeX to the frontend, the way is> to teach TeX a bit Mathematica.> And a TeXpert will never switch from his beloved TeX> to the Frontend and itıs typesetting -- thatıs why> he is a TeXpert.> Jens>>Recent threads about word processing and typesetting have got me>>dreaming again...>>Wouldnıt it be nice if someone developed a package that provided a>>function like this:>> DisplayTeX[ some TeX code ]>>which would cause the kernel to generate PostScript for the typeset>>text, to be displayed by the front end?>>I doubt that WRI will ever consider this, but surely thereıs someone out>>there whoıs both a TeXpert and a Mathematica guru who can do it. No>>doubt thereıs money to be made.>>Probably just a pipe dream...>>--->>Selwyn Hollis> ====Mike,I donıt think so. Style sheets do not control the styles used within anoutput graphics cell. I think you will have to set the plot style as astatement in the notebook, change it and re-evaluate for printing. Thismight not be all that inconvenient because you probably wonıt be printingthat often.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator====Dear MathGroup,To plot FrameTicks outward with the same style as the Frame, I useExtendGraphics in the following way.Needs[ExtendGraphics`Ticks`];tf[min_,max_] := TickFunction[min, max, MajorStyle -> {Thickness[0.003]}, MajorLength - > {0, 0.01}, MinorStyle -> {Thickness[0.003]},MinorLength -> {0, 0.005}]Plot [-2.4 (x+6) (x-8), {x, -6.2, 9.2}, FrameTicks -> {tf, tf, None, None},AspectRatio -> 18/25, Frame -> True, DefaultFont -> {Helvetica-Bold, 12},Axes -> None,FrameStyle -> Thickness[0.003], FrameLabel -> {x, y, None, None},PlotStyle -> Thickness[0.006],ImageSize -> 504];(instead of the same Plot statement with FrameTicks -> {Automatic,Automatic, None, None})This arrangement of major and minor ticks is clearly unacceptable. Theminor ticks do not divide intervals of adjacent labelled major ticks into equal parts.Are there other solutions? I have noticed that some major statistical(plotting) programs donıt do minor ticks at all.Tom AldenbergRIVMBilthovenNetherlands====I need to create an adjacency matrix from my data, which is currently inthe form of a .txt Ŝle 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 tohave an (m x m) matrix where cell i,j equals 1 if two actors areincident to the same event (in the sample above, 1 and 2 are bothincident 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 learningcurve ... All Iıve been able to Ŝgure out so far is how to get myincidence list into the program using Import[Ŝlename.txt]. But thenwhat? How do I convert to the adjacency matrix? Iıve found theToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I canıtseem to get it to work ... Tom**********************************************Thomas P. MoliternoGraduate School of ManagementUniversity of California, Irvinetmoliter@uci.edu*************************************** *******Reply-To: kuska@informatik.uni-leipzig.de====with In[]:=lst = {{1, A},{1, B},{2 , B},{3, C}, {3, D}, {1, D}};and In[]:=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 getIn[]:=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 Ŝle 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 Ŝgure out so far is how to get my> incidence list into the program using Import[Ŝlename.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> **********************************************====>Probably a rather simple question: what is the easiest way to open a>notebook, execute it, then quit, from the command line? I would like to be>able to do this from a MakeŜle.actually, this is not as simple as it should be and one needs theextremely useful JLink to really manipulate Notebooks from the similar under MacOSX and even Windows. Maybe others can try this.=================================================Execute this in the FrontEnd to create a test notebook, then quit the FrontEnd completely:NotebookSave[NotebookPut[Notebook[{Cell[, Input],Cell[Integrate[Log[1 - x]^2/(1 + x), {x, 0, 1}], Input]}]],/tmp/test.nb](* **************************** *)Next, create a Ŝle t.m :[rolf@uranus tmp]$ cat t.mnb = /tmp/test.nb;(* ***************************** *)<, Input],Cell[NotebookSave[en, Interactive -> False], Input]}]];SelectionMove[m, All, Notebook];SelectionEvaluate[m];];Pause[1];(* **************************************** *)Now you can run it like this in the background:[rolf@uranus tmp]$ math < t.m > t.out &This will open /tmp/test.nb , evaluate it and save it under thesame name.(* ******************************* *)Maybe there is an easier and cleaner way, but the problem here is that the kernel and the FrontEnd are really two different programs, i.e., the kernel is not waiting until the FrontEnd Ŝnished certain tasks (like NotebookSave), i.e., think of it as threads. Therefore I used the trick with a second steering notebook.(One usually has similar problems when writing more intricate buttons.)If you are not, e.g. you work remotely at a Unix-box without anvirtual frame buffer (Xvfb), like in webMathematica. ask Wolfram Tech Support.Rolf MertigMertig ConsultingEfŜcient Softwarehttp://www.mertig.com====> Iım curious about the different efŜciencies of Export vs. Put; Import vs.> Get.> Eg. Saving a list called c with approx. 16,000 elements, each element> being a three element list of reals.> Export[ac.dat,c] takes forever and consumes heaps of kernel memory> c>>ac.dat all done in an instant (relatively speaking) and without the> transient burst of kernel memory usage.> Ditto Import and Get. Can anyone explain this?The comparison is that of apples and oranges.Get[] and Put[] deal with reading and writing Mathematica expressions inInputForm syntax. They are implemented in C, so they are fairly fast, andthe target format is human readable. However the output might not bereadily parsable by other computer programs. The functions may be usedwith Mathematica expressions of all kinds. In the event that humanreadability and platform independence are not important, one can useDumpSave[] in lieu of Put[].Export[] and Import[] for the cases you describe are using the Table target format. They are implemented in top-level Mathematica code, so they are not as fast as Get[] and Put[]. The target is a regularly formatted array of data, so not all Mathematica expressions are appropriate for this kind of conversion. In the case of Export[], the expression is formatted completely in memory using TableForm[] before being saved out to Ŝle. In the case of Import[], there are a number of heuristics that are applied to each Ŝeld to determine whether the Ŝeld should be converted to a number or a string. This should explain why they are slower and require more memory.If you are dealing with a large collection of machine precision numbers, then neither of these approaches may be suitable for your purposes. You might be better off using the free add-on FastBinaryFiles, which is available up on MathSource at this URL:readable by C programs.-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc.====> A commonly used symbol for the Floor function is a square bracket with> the upper indents removed. Is this symbol part of Mathematicaıs> built-in symbols? I think not, so then, can it be constructed by> hand.Is this what youıre describing?In[1]:= [LeftFloor]x[RightFloor]Out[1]= Floor[x]This notation is documented in Section A.2.6 of _The Mathematica Book_ (Fourth Edition).-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc.====Jack,Check pages 959 and 960 in Section 3.10.4 of The Mathematica Book. You canuse LeftFloor and RightFloor as bracketing operators, which in turn areintrepreted as Floor.[LeftFloor] 3.2 [RightFloor]3These can also be entered as esc-lf-esc and esc-rf-esc.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator====It turns out that Mathematica does have the ŝoor symbols! Use esc l f escfor the left ŝoor and esc r f esc for the right ŝoor. In fact, if you typein esc l f esc a esc r f esc Mathematica will interpret the input asFloor[a].Carl WollPhysics DeptU of Washington>> A commonly used symbol for the Floor function is a square bracket with the> upper indents removed. Is this symbol part of Mathematicaıs built-insymbols? I> think not, so then, can it be constructed by hand.>> Jack>>====> A commonly used symbol for the Floor function is a square bracket with> the upper indents removed. Is this symbol part of Mathematicaıs built-in> symbols?Sure. Just look for Floor in A.10 Listing of Major Built-In MathematicaObjects! For example, you can use [LeftFloor] and [RightFloor] to getthe symbols you want.DavidReply-To: kuska@informatik.uni-leipzig.de====what may [LeftFloor] and [RightFloor]show on screen ? Itıs easy to Ŝnd in thecomplete characters palette | Operators | General Jens> A commonly used symbol for the Floor function is a square bracket with the> upper indents removed. Is this symbol part of Mathematicaıs built-in symbols? I> think not, so then, can it be constructed by hand.> Jack====> A commonly used symbol for the Floor function is a square bracket with the> upper indents removed. Is this symbol part of Mathematicaıs built-in symbols? I> think not, so then, can it be constructed by hand.> Jack[LeftFloor] and [RightFloor] can be used for this.Look at Chapter Advanced Mathematics/Mathematical and Other Notations/Operators.Yours, Alexander-- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern /====Hugh Goyder and David Park gave a most elegant function to Ŝnd two vectorsthat are orthogonal to one vector in 3D. The key to coming up with theelegant solution is an understanding of Mathematicaıs NullSpace function.We can easily make the version from Hugh and David much more general withthe version below.-------------OrthogonalUnitVectors[vect__?VectorQ]:= #/Sqrt[#.#]&/@NullSpace[{vect}]-------------The version above will give a set of unit orthogonal vectors if given anynumber of vectors in any dimension. So besides giving it a 3D vector we can give it the following: OrthogonalUnitVectors[{2,1,0,-1,1}] or OrthogonalUnitVectors[{0,1,0,1/2,1},{1,0,-1,1/2}]------------ But the short version above isnıt very robust.(1) Clear[x,y,z];NullSpace[{{x,y,z}}] returns two vectors orthogonal to {x,y,z}, but the two vectorsNullSpace returns arenıt orthogonal to each other. So (OrthogonalUnitVectors) should only work with numeric vectors.(2) We should ensure all the vectors have the same dimension and length >1.I give a less concise version below that corrects these problems.------------OrthogonalUnitVectors[vect__?(VectorQ[#, NumericQ]&)]/; (SameQ@@Length/@{vect})&&(Length[First[{vect}]]>1):= #/Sqrt[#.#]&/@NullSpace[{vect}]-------------- Ted Ersek Get Mathematica tips, tricks from http://www.verbeia.com/mathematica/tips/Tricks.html====I have installed 128 MB RAM extra in my computer. I had 64 before, so now Ihave 3 times as much.I expected some calculations that took very long before, to be executed inless time. To the contrary, my computer still goes to the hard drive fromemory for its calculations, and Mathematica stops with an out of memorymessage.Windows is recognizing this new memory. I dont know if Mathematica is. Howcan I Ŝnd out about this?Julio====> It seems there is an error in the BinCounts function of Mathematicaıs> standard < returns one more than the expected number of histogram bins. An example> of this is shown in the notebook code below where the comment in the> last notebook cell explicitly describes the problem. If anyone can> explain this behavior it would be appreciated, otherwise Wolfram> Research should be made aware of this feature of the function when it> is called as: BinCounts[{x1, x2, ...}, {xmin, xmax, dx}]A developer of Mathematicaıs Standard Packages has requested that thisresponse be posted to the forum:[begin developerıs comments]Note that if you donıt apply N when computing datBinWidth, you will alwaysget the expected number of bins; i.e., datBinWidth = (datMax -datMin)/datBins (assuming datMax and datMin are also exact numbers).Given input {xmin, xmax, dx}, BinCounts determines the number of bins tobe computed via Ceiling[(xmax - xmin)/dx]. For numericalized values, itıspossible for dx to end up such that the Ceiling forces an additional binto be added; presumably, itıs better to have too many rather than too fewbins -- for example, if the dx was deliberately given such that the xmaxis not at an integer bin boundary... If you use exact values for binbounds and increment, then there will be no problem.[end developerıs comments]--User Interface Programmer paulh@wolfram.comWolfram Research, Inc.====I would like to create a 3D chart from an ASCII Ŝle using Mathematica3.0. Can anyone give me some help?====You might want to tell us how to Ŝnd A.10.Anyway, itıs easier to simply go to Floor in the help browser (inversion 4.2, anyway).Bobby Treat-----Original Message-----David====I doubt thereıs any money to be made here. Lots of people have createdvery valuable additions to Mathematica, but theyıre all being givenaway, so far as I can tell. Itıs too bad, too.And here we are, giving away our time. Sigh...Bobby-----Original Message-----there whoıs both a TeXpert and a Mathematica guru who can do it. No doubt thereıs money to be made.Probably just a pipe dream...---Selwyn Hollis====OK, I give up; how would I Ŝnd Chapter AdvancedMathematics/Mathematical and Other Notations/Operators in the HelpBrowser?Bobby Treat-----Original Message-----> think not, so then, can it be constructed by hand.> Jack[LeftFloor] and [RightFloor] can be used for this.Look at Chapter Advanced Mathematics/Mathematical and Other Notations/Operators.Yours, Alexander-- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern /====> You might want to tell us how to Ŝnd A.10.Open your fourth edition of _The Mathematica Book_ to page 1065. Thatıs where part 10 of the Appendix starts. > Anyway, itıs easier to simply go to Floor in the help browser (in> version 4.2, anyway).I suppose youıre right. But I -- call me old-fashioned if you wish -- prefer to use the book.David ====Iıll assume you have the information in a matrix like x:TableForm[x = {{1, A }, {1, B }, {2, B}, {3, D}, {4, D}, {5, C}}]First Ŝnd the highest actor number (or use what youıve inputelsewhere):m = Last[Union[x[[All,1]]]]5DeŜne the incidence function:f[x_, a_, b_] /; a == b := 0f[x_, a_, b_] := If[{} $B!b(B Intersection[Cases[x, {a, y_} -> y], Cases[x, {b, y_} -> y]],1, 0]Hereıs the incidence matrix:Array[f[x, #1, #2] &, {m, m}]{{0, 1, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}}Once you have the incidence function, the only reason to store theincidence matrix is to avoid computing over again the same answers, andthat can be accomplished in other ways. If you wonıt have other xmatrices, itıs convenient to deŜne f this way:f[a_, b_] /; a == b := f[a, b] = 0f[a_, b_] /; a < b := f[a, b] = If[{} $B!b(B Intersection[Cases[x, {a, y_} -> y], Cases[x, {b, y_} ->y]], 1, 0]f[a_, b_] := f[b, a]Array[f, {m, m}]{{0, 1, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, {0,0, 0, 0, 0}}Whenever you would want the {j,k} element of the adjacency matrix, justuse f[j,k] instead. Each pair is computed only once. In this version,Iıve taken advantage of the symmetry of the problem, too, to cut thework in half.Bobby Treat-----Original Message-----. .. .m nWhere 1 to m represent actors and A to n represent events. My goal is tohave an (m x m) matrix where cell i,j equals 1 if two actors areincident to the same event (in the sample above, 1 and 2 are bothincident 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 learningcurve ... All Iıve been able to Ŝgure out so far is how to get myincidence list into the program using Import[Ŝlename.txt]. But thenwhat? How do I convert to the adjacency matrix? Iıve found theToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I canıtseem to get it to work ...Tom**********************************************Thomas P. MoliternoGraduate School of ManagementUniversity of California, Irvinetmoliter@uci.edu*************************************** *******====Well, I donıt know how fast, but it is fairly simple, anyway. Suppose youhave a series of values s for which you wish to obtain the edf.In[1]:=s = Table[Random[Integer, {0, 3}], {10}]Out[1]={2,2,1,2,0,0,1,1,1,3}If no speciŜcation is made about their position on the x-axis, we assumethat they correspond to the integers from 1 to 10. What we have then is thecollection of pairsIn[2]:=porig = Transpose[{Range[10], s}]Out[2]={{1, 2}, {2, 2}, {3, 1}, {4, 2}, {5, 0}, {6, 0}, {7, 1}, {8, 1}, {9, 1}, {10, 3}}The edf gives, for each x, the proportion of points in s that are less thanor equal to x, for all x. We obtain these proportions through the cumulativesumsIn[3]:=N[CumulativeSums[s]/Plus @@ s]Out[3]={ 0.153846,0.307692,0.384615,0.538462,0.538462,0.538462,0.615385 ,0.692308,0.769231,1.}so that for each of the pairs (x, y) below, y gives the proportion of pointsin s that are less than or equal to x:In[4]:=cumporig = Transpose[{Range[10], N[CumulativeSums[s]/Plus @@ s]}]Out[4]={{1, 0.15384615384615385}, {2, 0.3076923076923077}, {3, 0.38461538461538464}, {4, 0.5384615384615384}, {5, 0.5384615384615384}, {6, 0.5384615384615384}, {7, 0.6153846153846154}, {8, 0.6923076923076923}, {9, 0.7692307692307693}, {10, 1.}}Now shift the x values one unit to the left, by dropping the last value andprepending 0 to them:In[5]:=ps = Transpose[{Prepend[Drop[Range[1, 10], -1], 0], CumulativeSums[s]/Plus @@ s}]Out[5]={{0, 2/13}, {1, 4/13}, {2, 5/13}, {3, 7/13}, {4, 7/13}, {5, 7/13}, {6, 8/13}, {7, 9/13}, {8, 10/13}, {9, 1}}Then use Interpolation on this shifted set of points:In[6]:=ips=Interpolation[ps,InterpolationOrder[Rule]0] Out[6]=InterpolatingFunction[{{0,9}},<>]ips[x-1] is the edf you are looking for, as you may check by plotting it anddisplaying in the same graph together with the ListPlot of cumporig above.Tomas GarzaMexico City----- Original Message -----> and f is continuous from the right.>> When the number of observations is large, the Which statement> evaluates fairly slowly (even if it has been Compiled). Since> InterpolationFunction evaluates so much faster in general, Iıve tried> to use Interpolation with InterpolationOrder -> 0. The problem is that> the resulting InterpolatingFunction doesnıt behave the way (I think)> it ought to. For example, let>> g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->> 0]>> Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.> In addition, g is continuous from the left rather than from the right.>> Obviously I am not aware of the considerations that went into> determining the behavior of InterpolationFunction when> InterpolationOrder -> 0.>> So I have two questions:>> (1) Does anyone have any opinions about how InterpolatingFunction> ought to behave with InterpolationOrder -> 0?>> (2) Does anyone have a faster way to evaluate an empirical CDF than a> compiled Which function?>> By the way, hereıs my current version:>> CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]>> --Mark>>====I have no opinion on the behavior associated with InterpolationOrder->0,except that it should be DOCUMENTED, but isnıt.Meanwhile, try this:lst = {{1, 1/3}, {2, 2/3}, {3, 1}}; ClearAll[empiricalCDF]empiricalCDF[{x_List, y_List}] := Compile[ {{z, _Real}}, Evaluate[ Which @@ Flatten[ Transpose[ {(z < #1 & ) /@ x, y}]]]]empiricalCDF[v:{{_, _}..}] := empiricalCDF[v] = empiricalCDF[ ({Join[#1[[1]], {InŜnity}], Join[{0}, #1[[ 2]]]} & )[Transpose[ lst]]]empiricalCDF[lst]Plot[empiricalCDF[lst][x], {x, 1, 3}];I split the work into two deŜnitions for readability. If you evaluate:?empiricalCDFafter doing the plot above, youıll see that empiricalCDF[{{1, 1/3}, {2,2/3}, {3, 1}}] has been compiled and saved for later use, and that ittakes precedence over the SetDelayed rules listed after it. Hence, thecompilation only occurs once for each list.As written, your CompileEmpiricalCDF would be compiled all over againevery time itıs used -- for each and every point you plot -- so ofcourse itıs slow. There are other problems, too. For instance, thepatternlist_?(VectorQ[#, NumericQ] &)makes no sense at all. Maybe you meantlist_?And[VectorQ[#],NumericQ[#]]&Bobby Treat-----Original Message-----evaluates fairly slowly (even if it has been Compiled). SinceInterpolationFunction evaluates so much faster in general, Iıve triedto use Interpolation with InterpolationOrder -> 0. The problem is thatthe resulting InterpolatingFunction doesnıt behave the way (I think)it ought to. For example, letg = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->0]Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.In addition, g is continuous from the left rather than from the right.Obviously I am not aware of the considerations that went intodetermining the behavior of InterpolationFunction whenInterpolationOrder -> 0.So I have two questions: (1) Does anyone have any opinions about how InterpolatingFunctionought to behave with InterpolationOrder -> 0?(2) Does anyone have a faster way to evaluate an empirical CDF than acompiled Which function?By the way, hereıs my current version:CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := Block[{x}, Compile[{{x, _Real}}, Evaluate[ Which @@ Flatten[ Append[ Transpose[{ Thread[x < Sort[list]], Range[0, 1 - 1/#, 1/#] & @ Length[list] }], {True, 1}]] ]]]--Mark====Try deleting ...Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nb> Your machine information and OS EXACTLY matches mine (except that mypageŜle> is NOT on a separate physical drive -- perhaps this is a clue as to whereto start),> and I had no problem building the help Ŝle. Hence, as you say, thismust> be a problem for Wolfram to address. Perhaps, someone from WRI willenlighten> us via this newsgroup.> ....Terry>> I too have been unable to get the help browser functioning. I have> exactly the same problem. When trying to open the help browser it gets> to the point where it says scanning index Ŝle and freezes. I tried> all the suggestions in the faq and the links provided here to no> avail. Iım running Winows 2000 with service pack 3. I have 512mb of> memory with a 768mb pageŜle on a separate drive, so I donıt think> thatıs an issue. Mathematica 4.1 ran just Ŝne on this setup, so> judging by the number of other people affected by this, Iıd say itıs> some kind of bug with 4.2. Hopefully Wolfram will address this with> either a link that will provide a Ŝx that actually works, or a patch.>>What is your operating system? How much memory do you have in yourmachine?>Also, how big is your pageŜle? Sounds to me like the rebuild ran out>of room to do its thing in.>> I just installed Mathematica 4.2, and had no problem rebuildingthe help index.>Subsequently, I ahd no problem using the Help browser either.>Hope that helps!>....Terry>>>>Iıd start with the following FAQ.>>>http://support.wolfram.com/mathematica/interface/ helpbrowser/howrebuildindex.html>>>>-Dale>> Sorry that i failed say it immediately in a Ŝrst place, but ofcourse>> i did try it FAQ at Ŝrst, and both tried to delete cache and rebuild>> index, but results where the same - whenever i try to invoke help>> browser (or rebuild index, for that matter), mathematica stops>> responding (i did read your answer to the same question asked>> a week ago before - actually that is why i turned to the FAQ).>====>Try deleting ...>Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nb >====Simplify:5nth sqrt (3)/sqrt (6)5nth Sqrt(3)------------ Sqrt(6)1st.. is this the correct notation for use on a computer2nd.. how is the solution solved, step by step please.Reply-To: kuska@informatik.uni-leipzig.de====> Simplify:> 5nth sqrt (3)/sqrt (6)> 5nth Sqrt(3)> ------------> Sqrt(6)> 1st.. is this the correct notation for use on a computerNo. May be you mean3^(1/5)/Sqrt[6]??> 2nd.. how is the solution solved, step by step please.3^(1/5)/Sqrt[6] // FullSimplify Jens====I want to make a list of all symbols in the Global context, as inNames[Global`*]and compute a ByteCount for each symbolıs OwnValues -- withoutevaluating the symbols.It seems possible in principle, but I havenıt found a way.Bobby TreatReply-To: kuska@informatik.uni-leipzig.de====whats wrong withToExpression[#, StandardForm, Hold] & /@ Names[Global`*] /. Hold[a_] :> ByteCount[OwnValues[a]] Jens> I want to make a list of all symbols in the Global context, as in> Names[Global`*]> and compute a ByteCount for each symbolıs OwnValues -- without> evaluating the symbols.> It seems possible in principle, but I havenıt found a way.> Bobby Treat====with the following Java comands you can execute any Mathematica commands:ml.putFunction(EnterTextPacket, 1);ml.put(string);See JLinkUserGuide p. 164.Hermann Schmitt----- Original Message ----- > Iıve checked the documentation on Wolfram, but did not Ŝnd the Œhookı > for ReadList from java. Any help would be appreciated. thanks.> Pete> ====Dear Mark,I suggest trying the following code before you putfurther energy in speeding up your functions. Mycode is very short and seems to be fast in my Ŝrsttest with a random array of 100000 integers.cdf[li_List]:= FoldList[#1+Length[#2]&, 0.0, Split[Sort[li]]]/Length[li]t=Table[Random[Integer,{1,1000}],{ 100000}];Timing[cdf[t];]{0.44 Second,Null}Probably the speed could be increased further generatinga compiled version. But this would require additionalprogramming effort. Then you had to write a function whichcounts the number ofequal data Œby handı while scanning through the data list. Johannes> Iım trying to write a fast empirical cummulative distribution function> (CDF). Empirical CDFs are step functions that can be expressed in> terms of a Which statement. For example, given the list of> observations {1, 2, 3},> f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&> is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}> and f is continuous from the right.> When the number of observations is large, the Which statement> evaluates fairly slowly (even if it has been Compiled). Since> InterpolationFunction evaluates so much faster in general, Iıve tried> to use Interpolation with InterpolationOrder -> 0. The problem is that> the resulting InterpolatingFunction doesnıt behave the way (I think)> it ought to. For example, let> g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->> 0]> Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.> In addition, g is continuous from the left rather than from the right.> Obviously I am not aware of the considerations that went into> determining the behavior of InterpolationFunction when> InterpolationOrder -> 0.> So I have two questions: > (1) Does anyone have any opinions about how InterpolatingFunction> ought to behave with InterpolationOrder -> 0?> (2) Does anyone have a faster way to evaluate an empirical CDF than a> compiled Which function?> By the way, hereıs my current version:> CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]> --Mark> <><><><><><><><><><><><>Johannes LudsteckEconomics DepartmentUniversity of RegensburgUniversitaetsstrasse 3193053 Regensburg====>-----Original Message----->Sent: Wednesday, September 11, 2002 7:28 PM>Dear MathGroup,>>To plot FrameTicks outward with the same style as the Frame, I use>ExtendGraphics in the following way.>>Needs[ExtendGraphics`Ticks`];>>tf[min_,max_] := TickFunction[min, max, MajorStyle ->{Thickness[0.003]},> MajorLength - > {0, 0.01}, MinorStyle -> {Thickness[0.003]},>MinorLength -> {0, 0.005}]>>Plot [-2.4 (x+6) (x-8), {x, -6.2, 9.2}, FrameTicks -> {tf, tf, >None, None},>AspectRatio -> 18/25, Frame -> True, DefaultFont ->{Helvetica-Bold, 12},>Axes -> None,>FrameStyle -> Thickness[0.003], FrameLabel -> {x, y, None, None},>PlotStyle -> Thickness[0.006],>ImageSize -> 504];>>(instead of the same Plot statement with FrameTicks -> {Automatic,>Automatic, None, None})>>This arrangement of major and minor ticks is clearly unacceptable. The>minor ticks do not divide> intervals of adjacent labelled major ticks into equal parts.>>Are there other solutions? I have noticed that some major statistical>(plotting) programs donıt do minor ticks at all.>>Tom Aldenberg>RIVM>Bilthoven>Netherlands>>Several alternatives (if the default ticks of Plot, Show that is, wouldnıtdo):(1) generate the ticks explicitly (to get control over supplied min, maxvalues for TickFunction):yticks = tf[-40., 120.]xticks = tf[-6.2, 9.2]Plot[-2.4 (x + 6) (x - 8), {x, -6.2, 9.2}, FrameTicks -> {xticks, yticks, None, None}, ...](2) try the Option TickNumbers, e.g.tf[min_, max_] := TickFunction[min, max, MajorStyle -> {Thickness[0.005]}, MajorLength -> {0, 0.01}, MinorStyle -> {Thickness[0.003]}, MinorLength -> {0, 0.005}, TickNumbers -> {5, 25}]gives an acceptable result, or TickNumbers -> {6, 18};with TickNumbers -> {8, 8} youıll have no minor ticks.(3) redeŜne the tick functionıs helperBegin[ExtendGraphics`Ticks`Private`]?? TickPositionTickPosition[ min, max, num] returns a list of at most num nicely roundedpositions between min and max. These can be used for tick mark positions.TickPosition[x0_Real, x1_Real, (num_Integer)?Positive] := Block[{dist, scale, min, max, i, delta, space}, space = {1., 2., 2.5, 5., 10.}; dist = (x1 - x0)/num; scale = 10.^Floor[Log[10, dist]]; dist = dist/scale; If[dist < 1., dist *= 10.; scale /= 10.]; If[dist >= 10., dist /= 10.; scale *= 10.]; delta = First[Select[space, #1 >= dist & ]]*scale; min = Ceiling[x0/delta]*delta; Table[Floor[x/delta + 0.5]*delta, {x, min, x1, delta}]]End[]There are some things to play with: space, scale, the deŜnition for delta,to get at more nicely rounded positions; or rewrite completely.(4) for best control, deŜne the ticks all by yourself, e.g. yticks1 = Table[{t, t, {0, 0.01`}, {Thickness[0.003`]}} , {t, -25, 100, 25}]yticks2 = DeleteCases[ Table[{t, , {0, 0.005`}, {Thickness[0.003`]}} , {t, -25, 100, 12.5}], {t_, __} /; Mod[t, 25] == 0]xticks = Join[xticks1, xticks2]xticks1 = Table[{t, t, {0, 0.01`}, {Thickness[0.003`]}} , {t, -5, 7.5, 2.5}]xticks2 = DeleteCases[ Table[{t, , {0, 0.005`}, {Thickness[0.003`]}} , {t, -7.5, 8.5, 1.25}], {t_, __} /; Mod[t, 2.5] == 0]yticks = Join[yticks1, yticks2]--Hartmut Wolf====> I need to create an adjacency matrix from my data, which is currently in> the form of a .txt Ŝle and is basically a two column incidence list.> For example: > 1 A > 1 B > 2 B > 3 C > . . > . . > . . > m n Past the following notebook into Mathematica.Tom BurtonNotebook[{Cell[CellGroupData[{Cell[Preparing an adjacency matrix,Section],Cell[,Text],Cell[CellGroupData[{Cell[Introduction,Subsection], Cell[, Text]}, Open]],Cell[CellGroupData[{Cell[The structure of a graph,Subsection],Cell[, Text],Cell[BoxData[ (<, Text],Cell[BoxData[ (bb = Graph[{{{1, 2}}},{{{(-1. ), 0}}, {{1. , 0}}}])], Input],Cell[BoxData[(ToAdjacencyMatrix[aa])], Input],Cell[BoxData[(ToAdjacencyMatrix[bb])], Input]}, Open]],Cell[CellGroupData[{Cell[Example of a list of actor-event pairs,Subsection],Cell[BoxData[ (data = {{1, }, {4, }, {3,}, {1, }, {1, }, {3, }, {2, }, {2,}})], Input],Cell[,Text],Cell[BoxData[ (d = Max[data[([All, 1])]])], Input]},Open ]],Cell[CellGroupData[{Cell[Getting the list of edges,Subsection],Cell[TextData[{ Given the list of actors and actions,this is most of the work. Iıll do it in baby steps, as I would like to seewere I new to , StyleBox[Mathematica, FontSlant->Italic], . Itcould be done more directly.}], Text],Cell[Put events Ŝrst.,Text],Cell[BoxData[ (data2 = Reverse /@ data)],Input],Cell[Group by event, with increasing actors within each event.,Text],Cell[BoxData[ (data3 = Sort[data2])],Input],Cell[BoxData[ (data4 = Split[data3, First[#1] == First[#2]&])], Input],Cell[Remove isolated pairs., Text],Cell[BoxData[(data5 = DeleteCases[data4, {{_, _}}])], Input],Cell[Drop theactions., Text],Cell[BoxData[ (data6 = data5[LeftDoubleBracket]All, All, 2[RightDoubleBracket])],Input],Cell[, Text],Cell[BoxData[ (data7 = (KSubsets[#, 2]&) /@ data6)], Input],Cell[Collect edges into one list,Text],Cell[BoxData[ (data8 = Flatten[data7, 1])],Input],Cell[and remove duplicates, Text],Cell[BoxData[(onedir = Union[data8])], Input]}, Open]],Cell[CellGroupData[{Cell[Adjacency matrix via a list of edges usingMapAt, Subsection],Cell[Convert to directed edges,Text],Cell[BoxData[ (bothdir = Join[onedir, Reverse /@ onedir])],Input],Cell[,Text],Cell[BoxData[ (emptymat = Table[0, {d}, {d}])],Input],Cell[BoxData[ (adjmat = MapAt[1 &, emptymat, bothdir])],Input]}, Open ]],Cell[CellGroupData[{Cell[Adjacency matric viaToAdjacencyMatrix, Subsection],Cell[Construct a set of vertices fordisplay, Text],Cell[BoxData[ (verts = Table[{Cos[2 [Pi]j/d], Sin[2 [Pi] j/d]}, {j, d}])],Input],Cell[, Text],Cell[BoxData[ (g = Graph[List /@ onedir,N[List /@ verts]])], Input],Cell[Check our handiwork:,Text],Cell[BoxData[ (InputForm[g])], Input],Cell[BoxData[((ShowGraph[g];))], Input],Cell[BoxData[(ToAdjacencyMatrix[g])], Input]}, Open ]]}, Open]]},ScreenRectangle->{{43, 1152},{0, 746}},WindowSize->{565, 624},WindowMargins->{{243, Automatic}, {48,Automatic}}]====I have a notebook that will become a web page. I want to have a logo GIF atthe top.My Ŝrst thought was that I could drag and drop a GIF into a cell in thenotebook, but that does not work.I can Import a GIF and Show it. This creates an input cell, the GIF, and anoutput cell. I donıt want the input cell and the output cell to show whenthe HTML code is created.How can I do this?Tom Compton====Instead of using Legend in plots with multiple series is there a wayto have arrows with a text at the end identifying the differentseries? The reason Iıd like this is that the legend is a bit Œbulkyılooking and Iıd want something tidier.I know there is an Arrow package but I think youıd need to manuallyenter each start and end point of each arrow - is there a simplecommand to do this?Also - is there a way to adjust the legend font size? I.e. make itsmall so that it doesnıt interfere with data series. _ | thankyouReply-To: kuska@informatik.uni-leipzig.de====Needs[Graphics`Arrow`]Plot [{Sin[x], Cos[x]}, {x, 0, 2Pi}, Epilog -> {{GrayLevel[0.9], Rectangle[{3.75, 0.25}, {5.2, 0.9}]}, Arrow[{4, 0.75}, {2, Sin[2]}], Text[Sin[x], {4, 0.75}, {-1, 0}], Arrow[{4, 0.5}, {2, Cos[2]}], Text[Cos[x], {4, 0.5}, {-1, 0}]}] Jens> Instead of using Legend in plots with multiple series is there a way> to have arrows with a text at the end identifying the different> series? The reason Iıd like this is that the legend is a bit Œbulkyı> looking and Iıd want something tidier.> I know there is an Arrow package but I think youıd need to manually> enter each start and end point of each arrow - is there a simple> command to do this?> Also - is there a way to adjust the legend font size? I.e. make it> small so that it doesnıt interfere with data series.> _> |> > > > > thankyou====>-----Original Message----->Iım trying to write a fast empirical cummulative distribution function>(CDF). Empirical CDFs are step functions that can be expressed in>terms of a Which statement. For example, given the list of>observations {1, 2, 3},>>f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&>>is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}>and f is continuous from the right.>>When the number of observations is large, the Which statement>evaluates fairly slowly (even if it has been Compiled). Since>InterpolationFunction evaluates so much faster in general, Iıve tried>to use Interpolation with InterpolationOrder -> 0. The problem is that>the resulting InterpolatingFunction doesnıt behave the way (I think)>it ought to. For example, let>>g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->>0]>>Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.>In addition, g is continuous from the left rather than from the right.>>Obviously I am not aware of the considerations that went into>determining the behavior of InterpolationFunction when>InterpolationOrder -> 0.>>So I have two questions: >>(1) Does anyone have any opinions about how InterpolatingFunction>ought to behave with InterpolationOrder -> 0?>>(2) Does anyone have a faster way to evaluate an empirical CDF than a>compiled Which function?>>By the way, hereıs my current version:>>CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]>>--Mark>Mark,as to (1) I donıt know, but following your observation, and regarding ff = CompileEmpiricalCDF[{1, 2, 3}]Plot[ff[x], {x, 0, 4}, PlotRange -> {All, {0, 1}}]as a correct CDF, we get something quite similar withobs = {1, 2, 3}t = With[{n = Length[obs]}, Transpose[{Append[obs, Last[obs] + 1], Range[0, 1, 1/n]}]]g = Interpolation[t, InterpolationOrder -> 0]Off[InterpolatingFunction::dmval]Plot[g[x], {x, -1, 5}, PlotRange -> All]See that all values are shifted by one place, zero must be deŜned and onepoint added to the right.Now, comparingff /@ ({0, 1, 2, 3, 4}){0., 0.333333, 0.666667, 1., 1.}g /@ ({0, 1, 2, 3, 4}){0, 1/3, 1/3, 2/3, 1}We get something wrong for g, but forg /@ ({0, 1, 2, 3, 4} + 2$MachineEpsilon){0, 1/3, 2/3, 1, 1}obviously is all right. So we ran into problems of numerical precision. Now,what is the sense of the CDF at the point of jump? None Iıd say, at somepoint above the jump it must count for the fraction of all events below inrespect to over all. And this is done within the limits of numericalprecision. Conceptionally the CDF is function used to integrate as aStieltjes Integral, so only interpretations in this contex are possible, andyou have to look at the limit from above (within the conŜnes of numericalprecision), all ok, I think.To dig up a bigger sample:<< Statistics`ContinuousDistributions`gdist = GammaDistribution[3, 1]cdfunction = CDF[gdist, x]pTheory = Plot[cdfunction, {x, 0, 10}, PlotStyle -> Hue[.7]]data = RandomArray[gdist, 1000];t = With[{n = Length[data], obs = Sort[data]}, Transpose[{Append[obs, Last[obs] + 1], Range[0, 1, 1/n]}]];g = Interpolation[t, InterpolationOrder -> 0]pExperiment = Plot[g[x], {x, 0, 10}, PlotPoints -> 200]Show[pExperiment, pTheory]Nice comparison!ff = CompileEmpiricalCDF[Sort[data]];pExperiment2 = Plot[ff[x], {x, 0, 10}, PlotStyle -> {Hue[.4, 1, .5], Thickness[.003]}, PlotPoints -> 200]Show[pTheory, pExperiment2, pExperiment]I couldnıt see any differences between pExperiment and pExperiment2enlarged.Timings:rx = Table[Random[Real, {0, 10}], {10000}];(s1 = g /@ rx); // Timing{1.082 Second, Null}(s2 = ff /@ rx); // Timing{28.39 Second, Null}s1 == s2True So, I think, with deliberate use, your observation can be well exploited as(2)!--Hartmut Wolf====First of all, Import is not really meant for this sort of situation; it is better to use ReadList. Suppose your Ŝle is:1 A1 B2 B3 C4 B5 D5 E6 F7 Aand its name is adj.txt. Here is one way you can deal with this case. First, read in the Ŝle:In[1]:=ss=ReadList[adj.txt,{Number,Word}]Out[1]={{1,A},{1 ,B},{2,B},{3,C},{4,B},{5,D},{5,E},{6,F},{7,A}}Next, Ŝnd how many actors there are:In[2]:=l=Length[Union[First[Transpose[ss]]]]Out[2]= 7Construct the adjacency matrix:In[3]:=Table[If[Intersection[Cases[ss,{i,x_}->x,{1}], Cases[ss,{j,x_}->x,{1}]]=!={},1,0](1-KroneckerDelta[i,j]),{i, l},{j,l}]//MatrixFormOut[3]//MatrixForm=0 1 0 1 0 0 11 0 0 1 0 0 00 0 0 0 0 0 01 1 0 0 0 0 00 0 0 0 0 0 00 0 0 0 0 0 01 0 0 0 0 0 0The function ToAdjacencyMatrix form the Combinatorica package constructs the adjacency matrix from a graph, so it has no direct application to your problem.Andrzej KozlowskiToyama International UniversityJAPAN> I need to create an adjacency matrix from my data, which is currently > in> the form of a .txt Ŝle 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 Ŝgure out so far is how to get my> incidence list into the program using Import[Ŝlename.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> **********************************************>====When I click on The Mathematica Book, I see no chapters, no chapteralready fully expanded and there were chapter numbers next to thechapter names.Anyway, what is Floor doing in a chapter on Advanced Mathematics? Whyisnıt there a chapter on notation? I suppose thatıs why an unexpandedIf you Go To notation or notations, thereıs no link to Mathematicaland Other Notations. notation and notations yield different links,too. Very strange.As for looking for LeftFloor -- that makes sense only if you alreadyknow about LeftFloor. (Now I do.) Links from Floor to LeftFloor andRightFloor would make a lot of sense, but thatıs probably why theyırenot there.very kindly helping to make up for it.Bobby Treat-----Original Message-----Iım reaching it by clicking on The Mathematica Book and then clickingdie chapter and subchapters as mentioned above. Itıs chapter 3.10.4 (inYou can also Ŝnd it by looking for [LeftFloor] in the Master index.Yours, Alexander Dreyer-- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern /====One can make my original code (below) much faster by adding an auxiliary function and using dynamic programming:In[1]:=ss=ReadList[adj.txt,{Number,Word}]Out[1]={ {1,A},{1,B},{2,B},{3,C},{4,B},{5,D},{5,E},{6,F},{7,A}}In[2]:= l=Length[Union[First[Transpose[ss]]]]Out[2]=7a[i_] := a[i] = Cases[ss, {i, x_} -> x, {1}]In[4]:=Table[If[Intersection[a[i],a[j]]=!={},1,0](1- KroneckerDelta[i,j]),{i,l},{j, l}]//MatrixFormOut[4]//MatrixForm=0 1 0 1 0 0 11 0 0 1 0 0 00 0 0 0 0 0 01 1 0 0 0 0 00 0 0 0 0 0 00 0 0 0 0 0 01 0 0 0 0 0 0For large lists you will see a large difference in speed.Andrzej KozlowskiToyama International UniversityJAPAN> First of all, Import is not really meant for this sort of situation; > it is better to use ReadList. Suppose your Ŝle is:>> 1 A> 1 B> 2 B> 3 C> 4 B> 5 D> 5 E> 6 F> 7 A>> and its name is adj.txt. Here is one way you can deal with this > case. First, read in the Ŝle:> In[1]:=> ss=ReadList[adj.txt,{Number,Word}]>> Out[1]=> {{1,A},{1,B},{2,B},{3,C},{4,B},{5,D},{5,E},{6,F},{7,A}}>> Next, Ŝnd how many actors there are:>> In[2]:=> l=Length[Union[First[Transpose[ss]]]]>> Out[2]=> 7>> Construct the adjacency matrix:>> In[3]:=> Table[If[Intersection[Cases[ss,{i,x_}->x,{1}],> > Cases[ss,{j,x_}->x,{1}]]=!={},1,0](1-KroneckerDelta[i,j]),{i, > l},{j,l}]//MatrixForm>> Out[3]//MatrixForm=> 0 1 0 1 0 0 1>> 1 0 0 1 0 0 0>> 0 0 0 0 0 0 0>> 1 1 0 0 0 0 0>> 0 0 0 0 0 0 0>> 0 0 0 0 0 0 0>> 1 0 0 0 0 0 0>> The function ToAdjacencyMatrix form the Combinatorica package > constructs the adjacency matrix from a graph, so it has no direct > application to your problem.>> Andrzej Kozlowski> Toyama International University> JAPAN>>> I need to create an adjacency matrix from my data, which is currently >> in>> the form of a .txt Ŝle 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 Ŝgure out so far is how to get my>> incidence list into the program using Import[Ŝlename.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>> **********************************************>>>>==== script.Unfortunately when I start Mathreader I get the error message No Ŝle exists for resource 318 while the programme is initialising the text resource manager. It is not possible to click this message away.Can anybody help me with this problem? The only hint I found was the which I didnıt Ŝnd very useful.Best,M.====I have written the following in a JLink program:drawArea=JavaNew[com.wolfram.jlink.MathCanvas];then I perform an analysis of some data with output of this form....plot = DisplayTogether[ListPlot[],ListPlot[].etc...];Unfortunately, at this point I dont know how to associate Œplotı withdrawArea so that draw.Area@RepaintNow[]; repaints the math screen to show the plots Iıvecomputed...Iıve tried draw.Area@update[plot] and draw.Area@setImage[plot] but thesedont work........how to Ŝx?.........thanks.....jerry blimbaum NSWC panama city, ŝ====Somehow, we at WRI seem to have completely neglected to make any slide shows with internal hyperlinks (probably because slide show content, by its very nature, is just less likely to need internal hyperlinks), and so we never saw this problem.Weıll Ŝx it in a future version of Mathematica, but in the mean time, hereıs a workaround. The workaround is not exactly perfect...it can cause ŝashing on screen and may not put the scrollbar in exactly the right place...but it does work.With the slide show youıre editing open, perform the following steps:* Format->Edit Style Sheet... Choose Import Private Copy (unless you want to modify the global style sheet, which I wouldnıt recommend unless you need this in a lot of notebooks).* In the stylesheet, open the Hyperlinks group. Open the group for the Hyperlink style with that.* Place the cell insertion point after the prototype for the Hyperlink style and copy/paste the following in (pressing Yes when asked whether to interpret the cell):Cell[StyleData[Hyperlink, SlideShow], ButtonBoxOptions->{ButtonFunction:>(FrontEndExecute[ { CompoundExpression[ FrontEnd`SetOptions[ FrontEnd`ButtonNotebook[ ], ScrollingOptions -> { PagewiseDisplay -> False}], FrontEnd`NotebookLocate[ #2], FrontEnd`SetOptions[ FrontEnd`ButtonNotebook[ ], ScrollingOptions -> { PagewiseDisplay -> Inherited}]]}]&)}]* Close the style sheet, then save your slideshow notebook. Internal hyperlinks should now work.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.>I am interested in creating a slide presentation using slide view>mode in Mathematica 4.2. I would like to have hyperlinks between>different slides ( e.g., a hyperlink in say slide 6 takes me back to>slide 3).>>I have no difŜculty in creating such a hyperlink (using tags) when>I am in the author mode. But the hyperlink does not work when a>revert back to slide view mode.>>I guess it has somthing to do with the fact that in author view>mode your slides are a subset of a single notebook but in slide view>mode each slide becomes a distinct notebook.>>So my question: Is there a way to reference the individual slides>using the hyperlink command?>Brian====BRIEFMathematica seems to support 3 levels of nesting:section, subsection, and subsubsection.Q: how can I obtain more levels of nesting?I typically go 6-7 levels deep.DETAIL= ConŜg =I am using Mathematica 4 on a Sun Sparc at work.= Good Style or Not =I *know*, good style guides say that you should nevergo more than 3 levels of section deep. I disagree, anddonıt care. After editting my documents may only endup with three levels of subsection nesting, but whileI am editting, moving stuff around, I frequently want more.(Often, I move a whole subtree of the document around,so that all sections become subsubsections, subsectionsbecome subsubsections, etc.) E.g. HTML originally had only H1, H2, H3,but now it goes all the way up to H10.= How are Sections Indicated? =I had hoped to deŜne my own styles, section, subsection, sub2section, sub3section, etc.(ideally, section(level) if styles can be parameterized).But, I cannot see how to indicate how deeply nested a style is.In particular, I want to use the folding or hidingfeature, so that after I have deŜned sub6section, etc.I can hide everything below a sub4section.== Nesting Level or Bracket? ==It appears that Mathematicaıs sections have the level hardwiredinto them. section is at level 0 subsection at level 1 subsubsection at level 2This means that the next section at the same level terminatesa nesting group.The alternative implementation is to use brackets, e.g. XML
level 1
level 2
level3
level 2
level 1
This does not require the section level to be hardwired into the style.Obviously, Mathematica supports the Ŝrst, hardwired or explicit levelscheme. But, I cannot Ŝgure out how to extend it to multiple levels.I woulds be especially happy if the second approach were available,but, again, do not know how to create a Mathematica notebook stylethat accomplishes it.APOLOGIESIım sorry if this is a frequently asked question. I have searched the FAQand the MathGroup archives to no avail. I did Ŝnd stuff on section numbering,which is related - I usually like Dewey decimal section numbers extended to the samearbitrary depth - but none on deeper nesting than subsubsection.====Perhaps, it is a stupid question, but somehow, I was not able to Ŝnd any help on the following:I have a notebook, which does some calculations and saves results onto disk. All I need is to execute this notebook somewhere within another notebook. Sometimes it is nice to keep some parts of the code separated in different notebook Ŝles, which depending on the circumstances could be run manually via FrontEnd or within an automated loop from a notebook.To a certain extent this philosophy resembles, for example, what they have for scripts in another system.Please, reply directly to akolzine@uiuc.eduSincerely,Alexei.====Jens-Peer Kuska tells me that he gets no crash with Mathematica 4.2, however after workingwith this program for more than a month, trying every possible permutation andmanipulation, and having it still crash, I am still worried that upgrading to 4.2wonıt solve my problem. Can anyone else with 4.2 try running this program for me agood number of times, say 3 or 4, and see if they get similar good results?Bernard GressDear Group,I have a program to take the local polynomial non parametric regressionof two variables. It uses Compile, unfortunately, and regularly, butinconsistently, causes Mathematica to crash (in Win2K, with I forgetwhat error, and in Win98/Mathematica4.0 with an invalid memory access fromMathDLL.dll). I am running Mathematica 4.1, and have this problem consistentlyon 4 different machines.Here is the code, if it doesnıt crash the Ŝrst time, it will the secondor third:(*w = Compile[{{xj, _Real, 0}, {XX, _Real, 1}, {YY, _Real, 1}, {h, _Real,0}, {nn, _Integer, 0}, {ord, _Integer, 0}},First[Inverse[Sum[Outer[Times, Table[If[Positive[q], (XX[[i]] - xj)^q,1], {q, 0, ord}],Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0,ord}]*E^(-0.5*((XX[[i]] - xj)/h)^2)], {i, nn}]] .Sum[(Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0, ord}]*YY[[i]])*E^(-0.5*((XX[[i]] - xj)/h)^2), {i, nn}]]];*)(*!(tt = MemoryInUse[]; ListPlot[Table[{((i + 1))^2, (Timing[ nn = ((i + 1))^2; [Epsilon] = Table[Random[]*3, {i,nn}]; testX = Table[i* .3 - Random[]*2, {i, nn}]; testY = Table[Sin[i/3] - 2, {i, nn}] + [Epsilon]; Map[w[#, testX, testY, .1 + Random[], nn, 0] &, testX];])[([1])]/Second}, {i, 15}], PlotJoined ->True, PlotLabel -> ]; MemoryInUse[] - tt)*)====I ran it 10 times on 4.2 with no crashes.> Jens-Peer Kuska tells me that he gets no crash with Mathematica 4.2,however after working> with this program for more than a month, trying every possible permutationand> manipulation, and having it still crash, I am still worried that upgradingto 4.2> wonıt solve my problem. Can anyone else with 4.2 try running this programfor me a> good number of times, say 3 or 4, and see if they get similar goodresults?> Bernard Gress>> Dear Group,>> I have a program to take the local polynomial non parametric regression> of two variables. It uses Compile, unfortunately, and regularly, but> inconsistently, causes Mathematica to crash (in Win2K, with I forget> what error, and in Win98/Mathematica4.0 with an invalid memory access from> MathDLL.dll). I am running Mathematica 4.1, and have this problemconsistently> on 4 different machines.>> Here is the code, if it doesnıt crash the Ŝrst time, it will the second> or third:>> (*> w = Compile[{{xj, _Real, 0}, {XX, _Real, 1}, {YY, _Real, 1}, {h, _Real,> 0},> {nn, _Integer, 0}, {ord, _Integer, 0}},> First[Inverse[Sum[Outer[Times, Table[If[Positive[q], (XX[[i]] - xj)^q,> 1], {q, 0, ord}],> Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0,> ord}]*E^(-0.5*((XX[[i]] - xj)/h)^2)], {i, nn}]] .> Sum[(Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0, ord}]*YY[[i]])*> E^(-0.5*((XX[[i]] - xj)/h)^2), {i, nn}]]];> *)>> (*> !(tt = MemoryInUse[];> ListPlot[Table[{((i + 1))^2, (Timing[> nn = ((i + 1))^2; [Epsilon] = Table[Random[]*3, {i,> nn}];> testX = Table[i* .3 - Random[]*2, {i, nn}];> testY = Table[Sin[i/3] - 2, {i, nn}] + [Epsilon];> Map[w[#, testX, testY, .1 + Random[], nn, 0] &,> testX];])[([1])]/Second}, {i, 15}], PlotJoined ->> True,> PlotLabel -> ];> MemoryInUse[] - tt)> *)>Reply-To: kuska@informatik.uni-leipzig.de====my Mathematica 4.2 does not crash and you may upgradeyour version. Jens> Dear Group,> I have a program to take the local polynomial non parametric regression> of two variables. It uses Compile, unfortunately, and regularly, but> inconsistently, causes Mathematica to crash (in Win2K, with I forget> what error, and in Win98/Mathematica4.0 with an invalid memory access from> MathDLL.dll). I am running Mathematica 4.1, and have this problem consistently> on 4 different machines.> Here is the code, if it doesnıt crash the Ŝrst time, it will the second> or third:> (*> w = Compile[{{xj, _Real, 0}, {XX, _Real, 1}, {YY, _Real, 1}, {h, _Real,> 0},> {nn, _Integer, 0}, {ord, _Integer, 0}},> First[Inverse[Sum[Outer[Times, Table[If[Positive[q], (XX[[i]] - xj)^q,> 1], {q, 0, ord}],> Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0,> ord}]*E^(-0.5*((XX[[i]] - xj)/h)^2)], {i, nn}]] .> Sum[(Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0, ord}]*YY[[i]])*> E^(-0.5*((XX[[i]] - xj)/h)^2), {i, nn}]]];> *)> (*> !(tt = MemoryInUse[];> ListPlot[Table[{((i + 1))^2, (Timing[> nn = ((i + 1))^2; [Epsilon] = Table[Random[]*3, {i,> nn}];> testX = Table[i* .3 - Random[]*2, {i, nn}];> testY = Table[Sin[i/3] - 2, {i, nn}] + [Epsilon];> Map[w[#, testX, testY, .1 + Random[], nn, 0] &,> testX];])[([1])]/Second}, {i, 15}], PlotJoined ->> True,> PlotLabel -> ];> MemoryInUse[] - tt)> *)> I have followed Ted Ersekıs tips and tricks> (http://www.verbeia.com/mathematica/tips/tip_index.html) about Compile,> and have tried changing all variable names (works sometimes), removing> any hidden spaces, restructuring the formulas, changing all 0ıs to 0. Œs> and all 1ıs to 1. Œs, etcetera etcetera, but I still canıt comprehend> what the problem might be. Doing w[[-2]] shows a list of op-code> numbers, and one function name, Inverse[#1]&, so it seems to me that> there are no problems with the use of Compile here. Would anyone have> any thoughts???> Bernard Gress> burnthebiscuit@netscape.net====Mr Kuska,4.2, I thought I had solved this problem so many times and still it would suddenlystart crashing again our of the blue, after 20 or 30 executions.Bernard>> my Mathematica 4.2 does not crash and you may upgrade> your version.>====>Is it possible to conŜgure a style sheet so that functions or data shown in>graphs are coloured (colored :)) in working but black in printing...without>actually re-executing the function that created the graphics?>>thanks>>MikeThere is no way do this, but with a couple of tricks you can create the same effect.First, we generate 2 graphics. One is the normal graphic. The other uses all black colors. This process is automated by changing $DisplayFunction.$DisplayFunction = ( (* Ŝrst the normal graphic *) Display[$Display, #1]; (* then a new B&W graphic *) CellPrint[ Cell[GraphicsData[PostScript, DisplayString[#1 /. {_RGBColor | _CMYKColor -> GrayLevel[0]}]], GraphicsPrintout]]; #1 ) &;If you set this and do a plot you will see the two graphics. The second graphic will look strange because itıs in a different cell style. Weıre going to use the cell styles to control which graphic is shown.Next, open the style sheet (menu item Format>Edit Style Sheet). Replace the Graphics/Printout style with the following cell.Cell[StyleData[Graphics, Printout], ShowCellBracket->False, CellMargins->{{0, 0}, {0, 0}}, CellElementSpacings->{CellMinHeight->0}, CellGroupingRules->NormalGrouping, CellFrameMargins->False, CellSize->{Inherited, 0}, Background->None]It hides the colored cell in the Printout environment. Then, add the following styles.Cell[StyleData[GraphicsPrintout], CellMargins->{{4, Inherited}, {Inherited, Inherited}}, CellGroupingRules->GraphicsGrouping, CellHorizontalScrolling->True, PageBreakWithin->False, GeneratedCell->True, CellAutoOverwrite->True, ShowCellLabel->False, DefaultFormatType->DefaultOutputFormatType, LanguageCategory->None, FormatType->InputForm, ImageMargins->{{43, Inherited}, {Inherited, 0}}, StyleMenuListing->None, FontFamily->Courier, FontSize->10]Cell[StyleData[GraphicsPrintout, Printout], ImageMargins->{{30, Inherited}, {Inherited, 0}}, MagniŜcation->0.8]Cell[StyleData[GraphicsPrintout, Working], ShowCellBracket->False, CellMargins->{{0, 0}, {0, 0}}, CellElementSpacings->{CellMinHeight->0}, CellGroupingRules->NormalGrouping, CellFrameMargins->False, CellSize->{Inherited, 0}, Background->None]It hides the B&W cell in the Working environment and shows the cell in the Printout environment.Finally, try it out.Plot[x, {x, 0, 1}, PlotStyle -> RGBColor[1, 0, 0], TextStyle -> {FontColor -> RGBColor[0, 0, 1]}]--------------------------------------------------------- -----Omega ConsultingThe Ŝnal answer to your Mathematica needsSpend less time searching and more time Ŝnding.http://www.wz.com/internet/Mathematica.html====I was completely wrong about the pattern list_?(VectorQ[#, NumericQ] &).I had forgotten about that notation and didnıt think to look it up.Sorry!Bobby-----Original Message-----evaluates fairly slowly (even if it has been Compiled). SinceInterpolationFunction evaluates so much faster in general, Iıve triedto use Interpolation with InterpolationOrder -> 0. The problem is thatthe resulting InterpolatingFunction doesnıt behave the way (I think)it ought to. For example, letg = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->0]Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.In addition, g is continuous from the left rather than from the right.Obviously I am not aware of the considerations that went intodetermining the behavior of InterpolationFunction whenInterpolationOrder -> 0.So I have two questions: (1) Does anyone have any opinions about how InterpolatingFunctionought to behave with InterpolationOrder -> 0?(2) Does anyone have a faster way to evaluate an empirical CDF than acompiled Which function?By the way, hereıs my current version:CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := Block[{x}, Compile[{{x, _Real}}, Evaluate[ Which @@ Flatten[ Append[ Transpose[{ Thread[x < Sort[list]], Range[0, 1 - 1/#, 1/#] & @ Length[list] }], {True, 1}]] ]]]--Mark====I was wondering if a way exists to move the main menu bar of the front end.I am talking about the bar that occupies the top of the screen and extends,by default, from the left end of the screen to the right. It has a lot ofblank space to the right of the menus. Making it narrower frees up someimportant screen real estate, if you want to reach icons under it. How couldI make Mathematica do that automatically? I cannot seem to Ŝnd it in thePreferences or in the sections on manipulating notebooks.Nicholas====The various Intro/Mathematica Programming books Iıve seen (e.g. Gray:Mastering Mathematica -- now out of print but have a copy on order) andMathematical Navigator and other books Iıve seen are based on V3. Is thereany Intro/Programming book based on V4 (or even updated for 4.2) that isavailable besides the on-line book?Does someone have notes that update the V3 books?====I puzzled over this and came up with an explanation. The phenomenonsomebody noticed is that the fractional part of(Sqrt[3] + Sqrt[2])^(2*n)approaches 1 from below as n (integer) gets large. Hence, for instance,Mod[ N[(Sqrt[2] + Sqrt[3])^2002, 2000], 100]has a string of 996 nines after the decimal point. Well, hereıs thereason for that.Let x and y be the square roots of any integers and let n be an eveninteger power. Then (x + y)^n == Sum[Binomial[n, m]*y^m*x^(n - m), {m, 0, n}];and (x - y)^n == Sum[(-1)^m*Binomial[n, m]*y^m*x^(n - m), {m, 0, n}];so, adding the two equations, we have (x + y)^n + (x - y)^n == Sum[Binomial[n, m]*y^m*x^(n - m)* (1 + (-1)^m), {m, 0, n}];1 + (-1)^m is 0 when m is odd and 2 when m is even, so (x + y)^n + (x - y)^n == 2*Sum[Binomial[n, 2*k]*y^(2*k)*x^(n - 2*k), {k, 0, n/2}];Since n is even, all powers of x and of y are even in this expression.Since x and y are the square roots of integers, it follows that all theterms are integers. Hence(x + y)^n + (x - y)^nis integer. Now we assume, in addition to our other conditions, that0 < x - y < 1In that case, (x - y)^n approaches 0 from above as n gets large, andFractionalPart[(x + y)^n] == 1 - (x - y)^nwhich approaches one from below as n gets large. The number of ninesafter the decimal point can be calculated asFloor[(-n)*Log[10, Sqrt[3] - Sqrt[2]]]For n=2002 (the example we started with, this is indeed)Floor[-2002*Log[10, Sqrt[3] - Sqrt[2]]]996Bobby Treat-----Original Message-----> Ŝnally take the result modulo 10^n.> Mod[Floor[ N[(Sqrt[2] + Sqrt[3])^2002 , 1000]], 10^2]> results in 9, so the last two digits before the decimal point are 09.> With a slight modiŜcation we can Ŝnd the Ŝrst n digits after thedecimal> point. Simply Ŝnd the last n digits before the decimal point of 10^ntimes> the number.> Mod[Floor[ N[10^2 (Sqrt[2] + Sqrt[3])^2002 , 1000]], 10^2]> results in 99, so these are the digits you are interested in.> But there is something curious about this number.> Mod[Floor[N[10^1000 (Sqrt[2] + Sqrt[3])^2002 , 2000]], 10^1000]> results in 996 digits 9 followed by 7405.> You can also play with the following command, resulting in the digitsaround> the decimal point:> Mod[ N[(Sqrt[2] + Sqrt[3])^2002, 2300], 10^6]> The decimal expansion of (Sqrt[2]+Sqrt[3])^2002 contains a sequence of> 997 consecutive digits 9. Do you have any idea why?Not unusual. Try other even exponents and there should be large blocks of 9s . Smaller number for small exponents. Some kind of propagation of 9s as the exponent grows. Try other odd values for 3 and the same thinghappens for some values. Also for other values for 2.Larry> Fred Simons> Eindhoven University of Technology> ====>I have written the following in a JLink program:>drawArea=JavaNew[com.wolfram.jlink.MathCanvas];>> then I perform an analysis of some data with output of this form....>>plot = DisplayTogether[ListPlot[],ListPlot[].etc...];>Unfortunately, at this point I dont know how to associate Œplotı with>drawArea so that>>draw.Area@RepaintNow[]; repaints the math screen to show the plots Iıve>computed...>Iıve tried draw.Area@update[plot] and draw.Area@setImage[plot] but these>dont work........how to Ŝx?.........thanks.....Jerry,You use the MathCanvas.setMathCommand() method to specify the Mathematica command that is used to generate the image to display: drawArea.setMathCommand(plot);You will Ŝnd a very simple example of this in section 1.2.8.2 of the J/Link User Guide (in the Help Browser hierarchy, this is found at JLink/Part 1. Installable Java/Drawing and Displaying Images in Java Windows/Showing Graphics and Typeset Expressions).You do not need to use the repaintNow() method unless you are updating the image continuously in response to a user action, like dragging a slider.Todd GayleyWolfram Research====try:(((((3^(1/2))^(1/2))^(1/2))^(1/2))^(1/2))/(6^ (1/2))Out:1/(Sqrt[2]*3^(15/32))You can see what happened:1st: 6^(1/2) = 2^(1/2)*3^(1/2);2nd: subtraction of the 3ıs exponents (1/2)^5 - 1/2 = 1/32 - 16/32 = -15/32.MATHEMATICA does these straightforward simpliŜcations without you having toinvoke Simplify[].Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de-----UrsprÌ.b9ngliche Nachricht-----Gesendet: Freitag, 13. September 2002 07:14An: mathgroup@smc.vnet.netBetreff: nth rootsSimplify:5nth sqrt (3)/sqrt (6)5nth Sqrt(3)------------ Sqrt(6)1st.. is this the correct notation for use on a computer2nd.. how is the solution solved, step by step please.====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 seemsto be working Ŝne when I produce a document that is just Mathematica code.The problem - as expected - is that when I include the Mathematica code asa part of a larger document, there are (1) clashes with existing packages(2) some LaTeX elements, such as the equations, start to use theMathematica fonts too. My objective would be to typeset a document instandard LaTeX, where only the Mathematica code has the Mathematica feeling.Does anyone know of any style available that is completely seperated fromall other LaTeX deŜnitions?BestKyriakos_____+**+____+**+___+**+__+**+_ Kyriakos ChourdakisLecturer in Financial EconomicsURL: http://www.qmw.ac.uk/~te9001tel: (++44) (+20) 7882 5086Dept of EconomicsUniversity of London, QMLondon E1 4NSU.K.Reply-To: kuska@informatik.uni-leipzig.de====a) you must change the fonts, because the Mathematica symbols are designed to Ŝt 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 Ŝne with the most style Ŝles But you have to use TeX notebooks that are essential TeX Ŝles with mathinput environments. The TeX frontend send the contents of the mathinput environments to the kernel and paste the output into the Ŝnal TeX Ŝle. It also does some fancy formating with the Mathematica input and replace -> with Rule, :> with RuleDelayed .. You can have the program and the style Ŝles 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 Ŝne 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 deŜnitions?> 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.====What about this problem? I have tried the previous suggestions but none ofthem worked. Will Wolfram help us in this problem?====Have you tried deleting ... Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nbThere are two BrowserIndex Ŝles. Only delete the .nb one (or just move itsomewhere else).> What about this problem? I have tried the previous suggestions but none of> them worked. Will Wolfram help us in this problem?>>>====First a thank you to all those who pointed out to me (and othersapparently) about the various ways to input the symbolic form of Floor.On a larger note, it surprises me that no one has yet published a book onhow to use Mathematica to write a technical document. The number of questionsthat appear on this board concerning the details of how to do itsuggests the need for such documentation. Iım speculating when I say thatmany users give up in frustration and go back to (or learn) Latex. Atleast there are bookcases full of learning Latex. I myself have 5!I donıt mean this to sound like a rant, but using Mathematica to publish adocument is, for most of us, not worth the effort.Jack====I often run into this difŜculty: when designing a program, say as amodule, and testing it for various inputs, I get wrong answers. What todo? 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 beimporved. (Oh yes, I abandoned Trace a long time ago!)myFunction[f_] := Module[ {L1,L2,L3},L1 = ... ;L2 = ... ;l3 = ... ; Ŝnal step ]To see what went wrong, I use (* *) selectively as follows:Stage 1myFunction[f_] := Module[ {L1,L2,L3},L1 = ... (*;L2 = ... ;L3 = ... ; Ŝnal step *) ]Thus I see if L1 worked as expected. The next step is to put (* after L2and see if this works. I continue this til the bitter end and I usuallyŜnd my errors.My question; The process of moving (* *) step by step through theprogram is quite tedious when the code has lots more lines. What I wouldlike is a meta-program which (like FoldList) does this job for me. Theoutput of this meta-program is the list of outputs of each line in themodule, probably best printed as a column.This sounds like Trace but my problem with Trace is it is terriblydifŜcult to read. For the not-so-subtle programming I do, the only thingI need is what expression is returned line by line.Any advice? All remarks are appreciated!JackReply-To: kuska@informatik.uni-leipzig.de====does help you ? Jens> I often run into this difŜculty: 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 = ... ;> Ŝnal step> ]> To see what went wrong, I use (* *) selectively as follows:> Stage 1> myFunction[f_] := Module[ {L1,L2,L3},> L1 = ... (*;> L2 = ... ;> L3 = ... ;> Ŝnal 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> Ŝnd 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> difŜcult 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 Iincorrectly attaced to someone elseıs reply). It is somewhat moreŝexible now and does more error checking. It Ŝnds the rule inDownValues that matches f[args] (allowing for more than one rule inDownValues); it allows the user to specify the position of the mainCompoundExpression; and it allows the user to specify an expressionthat gets appended to the truncated CompoundExpression (and henceevaluated and returned). The package is just a bit too large to posthere. It can be downloaded from my web site athttp://www.markŜsher.net/~meŜsher/mma/ mathematica.htmlNevertheless, I can give an outline of the code here (absent the errorchecking stuff).PartialEvaluation[f[args], n, expr]:(* get the DownValues and turn them off *)dv = DownValues[f];DownValues[f] = {};(* Ŝnd the rule that matches *)matches = Position[MatchQ[f[args], #]& /@ dv[[All, 1]], True];match = dv[[ matches[[1, 1]] ]];(* Ŝnd 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 modiŜed rule and restore DownValues *)result = f[args] /. match;DownValues[f] = dv;result--Mark> I often run into this difŜculty: 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 = ... ;> Ŝnal step> ]> To see what went wrong, I use (* *) selectively as follows:> Stage 1> myFunction[f_] := Module[ {L1,L2,L3},> L1 = ... (*;> L2 = ... ;> L3 = ... ;> Ŝnal 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> Ŝnd 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> difŜcult 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====JM,You are certainly correct in wanting to make a tidier plot! Legends areoften poor because they actually distract from the message of the data.However, the best solution will depend on the particular nature of yourdata. If there are not too many curves you could perhaps put Text labelsright on top of each curve. If there are many curves, or some of them areclose together, use arrows for some of them. If you have a really largenumber of curves, then maybe a different approach is needed.It is probably not possible to make a useful general routine for labeledarrows because the best placement would depend upon the particular nature ofthe graph. So, to make a nice graphic you will have to do some hand work,specifying each Arrow and Text label. You can actually click the coordinatesoff the graph to put into the Arrow and Text statements.If you want to actually show me your plot, I could try to make somesuggestions.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ _ | thankyou====>I am interested in creating a slide presentation using slide view>mode in Mathematica 4.2. I would like to have hyperlinks between>different slides ( e.g., a hyperlink in say slide 6 takes me back to>slide 3).>>I have no difŜculty in creating such a hyperlink (using tags) when I>am in the author mode. But the hyperlink does not work when a revert>back to slide view mode.>>I guess it has somthing to do with the fact that in author view mode>your slides are a subset of a single notebook but in slide view mode>each slide becomes a distinct notebook.>>So my question: Is there a way to reference the individual slides>using the hyperlink command?>BrianIf you set PagewiseScrolling->True, then your hyperlink will work. Go to the Option Inspector and set the scope to Notebook. Then go to the optionNotebookOptions|Window Properties|ScrollingOptions|PagewiseScrollingAnd set it to True. The disadvantage to this setting is that you can now only have one screenıs worth of contents per slide. (But then it is a slide show after all, so maybe thatıs not so bad.)-Dale====Does anybody know how to calculate in Mathematica:a)empirical CDF,b)empirical PDF,c)normal QQ-plot;d)QQ-plot two different random samples?!Swidrygiello.====DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to preventthe loading of a large Ŝle in routine cases. However, when ThisPackage`deŜnes its functions, inside the Private` area, it includes a conditionalcall to BigVariable. It turns out that OtherPackage is loaded when thatfunction is deŜned. I was wondering if there is a way to avoid this.Roughly speaking, here is the setting:BeginPackage[ OtherPackage` ]BigVariable::usage=exampleBegin[Private`]BigVariable=Table[x y,{x,1000},{y,1000}]End[ ]EndPackage[ ]BeginPackage[ ThisPackage` ]function::usage=exampleBegin[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 withx>1000 but it loads when function is deŜned. Any ideas?NicholasReply-To: kuska@informatik.uni-leipzig.de====BeginPackage[ OtherPackage` ]BigVariable::usage=exampleBegin[`Private`]BigVariable=Table[ x y,{x,1000},{y,1000}]End[ ]EndPackage[ ]Print[Loading ...];andBeginPackage[ ThisPackage` ]function::usage=exampleBegin[`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 Ŝle in routine cases. However, when ThisPackage`> deŜnes its functions, inside the Private` area, it includes a conditional> call to BigVariable. It turns out that OtherPackage is loaded when that> function is deŜned. 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 deŜned. Any ideas?> Nicholas==== Dynamic programming might help: replace the line deŜning BigVariablewithBigVariable:=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.9in the Mathematica Book).John Jowett> DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent> the loading of a large Ŝle in routine cases. However, when ThisPackage`> deŜnes its functions, inside the Private` area, it includes a conditional> call to BigVariable. It turns out that OtherPackage is loaded when that> function is deŜned. 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 deŜned. Any ideas?>> Nicholas>>>====Could you send a sample example of your Ŝle -- just a few records.Tomas GarzaMexico City----- Original Message -----> This appears to pull in a line. Now I want to take characters 25 to 110 toget just the stuff I want:> y1=StringTake[y ,{25,110}];>> Hereıs the output. StringTake doesnıt seem to work.>321. 317. 367. -115. 126. 146. -410. -426.000000EF 75.},{25, 110}]>> It doesnıt take loading another package as far> as I can tell from the help. Iım thinking that it doesnıt work becauseitıs trying to work on a list> rather than a string. Iıve tried Flatten, and other stuff to try to get tojust a string and not a list but> nothing has worked so far. Iım a long way from getting to those numbersin there but heck, I> canıt even get to the string. Can anyone point me in the right direction?>>====Iıve got to extract some numbers from a Ŝle 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 faras I can tell from the help. Iım thinking that it doesnıt work because itıs trying to work on a listrather than a string. Iıve tried Flatten, and other stuff to try to get to just a string and not a list butnothing has worked so far. Iım a long way from getting to those numbers in there but heck, Icanıt even get to the string. Can anyone point me in the right direction?====this thing. Here is what Iım using now:In[1]:=a=ReadList[197-tst.txt,Word,RecordLists->True, WordSeparators->None];In[2]:=ŝds={{25,31}, {32,39},{40,46},{47,54},{55,62},{63,70},{71,78},{79,86},{87, 94},{95,102},{103,110}};DeŜne this function:In[3]:=f[x_]:=ToExpression[StringTake[x[[1]],#]]&/@ ŝdsNow, map this function onto a:In[8]:=f/@aOut[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 (apparentlyMathematica 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 Ŝle 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.====> 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.> -1281.9 -229. 321. 317. 367. -115. 126. > 146. -410. -426.000000EF 75.}, {25, 110}]> 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?You might try lst = Read[StringToStream[y1], {Word, Table[Number, {16}], Word,Number}]//Flatten;You can then pick the numbers (or words) from the list lst.A quicker alternative might be as follows:-iŜle = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}];Dave.========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au======================================= ========First of all, I used ReadList directly, with Word instead of String, andwith the option WordSeparators -> None, like this (I presume your Ŝle isadequately located, so that there is no problem in Ŝnding it):In[1]:=a = ReadList[197-tst.txt, Word, RecordLists -> True, WordSeparators ->None];This allowed me to examine your records and I found out that in this wayeach record comes out as a list of length 1: In[2]:=Head[a[[1]]]Out[2]=ListIn[3]:=Length[a[[1]]]Out[3]= 1That is,In[3]:=a[[1]]Out[3]=317. 367. -115. 126. 146. -410. -426.000000EF 75.}In[4]:=StringLength[a[[1,1]]]Out[4]=140and the characters you want areIn[5]:=StringTake[a[[1,1]], {25, 110}]Out[5]=5935.80 5946.66 27.06 -1281.9 -229. 321. 317. 367. -115. 126. 146.So far, so good. It seems that you want these 11 numbers, OK? The problemnow, I think, is that this is just a string and I can think of no easy wayto convert it precisely into a list of 11 real numbers. Then, I suggest youread the Ŝle in a different way, without the WordSeparators option:In[6]:=b=ReadList[197-tst.txt,Word,RecordLists -> True];In[7]:=b[[1]]Out[7]=115.,126.,146.,-410.,-426.000000EF, 75.}In[8]:=Head[b[[1]]]Out[8]=ListIn[9]:=Length[b[[1]]]Out[9] =19so that each record is now a list of 19 strings. What you want is strings 6to 16, but converted to reals (unless Iım being presumptuous). This willachieve that:In[10]:=ToExpression[Take[b[[1]],{6,16}]]Out[10]={ 5935.8,5946.66,27.06,-1281.9,-229.,321.,317.,367.,-115.,126., 146.} Now you have a nice list of real numbers to work with. You can do this forthe whole Ŝle like this:In[11]:=ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem.Tomas GarzaMexico City> ----- Original Message -----> Sent: Friday, September 13, 2002 12:14 AM>> Iıve got to extract some numbers from a Ŝle that are in lines of text.> Since the line contents are not numbers, I presume I must pull the lineout> 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 110to> get just the stuff I want:> y1=StringTake[y ,{25,110}];>> Hereıs the output. StringTake doesnıt seem to work.>-229.> 321. 317. 367. -115. 126. 146. -410. -426.000000EF 75.},> {25, 110}]>> 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 getto> 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 rightdirection?>>-------------------------------------------- ------------------------====> BRIEF> Mathematica seems to support 3 levels of nesting:> section, subsection, and subsubsection.> Q: how can I obtain more levels of nesting?> I typically go 6-7 levels deep.Well, I started by editting the notebook in a text editor(having used Edit Style Sheet to unshare),and I created stylesSub3section ... Sub9section,with Dewey decimal numbering 1.2.3.4.5.6.7.8.9.10I got collapsable group working, by mucking with CellGroupingRules->{SectionGrouping, 100},changing the number.I am not sure what the number is, but Iım guessingit may be a pixel count for the nesting boxesat the left of the screen.Iım a bit worried about whether this is fragile.===Was there any way to accomplish this from the GUI?Or was using a text editor mandatory?===Related: this exercise makes it obvious that acommon operation is to push down or pull upa whole subtree - e.g. a Subsection becomes aSubsubsection, a Subsubsection becomes aSub3section, etc. The sort of thing that MicrosoftWord does with Outline mode.Q: has anyone got something like Outline modefor Mathematica?Iım tempted to go the other way, and ask if anyonehas a front end that allows Mathematica to be embeddedin Word documents. But that might be a hassle,since Word runs on Windows, and the Mathematicalicence I have access to runs on Suns.====> 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.> -1281.9 -229. 321. 317. 367. -115. 126. > 146. -410. -426.000000EF 75.}, {25, 110}]> 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?You might try lst = Read[StringToStream[y1], {Word, Table[Number, {16}], Word,Number}]//Flatten;You can then pick the numbers (or words) from the list lst.A quicker alternative might be as follows:-iŜle = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}];Dave.========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au======================================= ========I was and do have problems reading Ŝles Exported Ŝles in AdobeIllustrator format (.ai) from Adobe Illustrator 10.0.3.With an upgrade to Adobe Illustrator 10.0.3, I can read EPS Ŝlescreated by Mathematica 4.0.1.A message from tech support at Wolfram implies that Adobe Illustratorformat Ŝles can be read ONLY if you are using the correct Adobe andWolfram programs. Additionally, Mathematica is going to favor the exportof EPS Ŝles (is that clear enough?).My approach to using Mathematica as a source of images for AdobeIllustrator 10.0.3 is:Create the image in MathematicaExport[ImageFileName.eps, theMathematicaImageCreated, EPS]Open the Ŝle ImageFileName.eps within Adobe Illustrator 10.0.3Save the Ŝle as a .ai ŜleBe sure to check the ImageSize as it is not often what you toldMathematica.====In his not-so-subtle way, Jens-Peer is trying to tell you that since yousee z in the error message, thatıs what NIntegrate saw too. z is asymbol, and NIntegrate needs numbers. Now Iıll have to search onlinefor your original problem, since I deleted my copy long ago... (Excuseme a few minutes...) Hmm... OK, Iım back.Well... thereıs still a missing (or extra) parenthesis in the deŜnitionof f and a missing bracket in the deŜnition of F, but I also canıt seethat youıve given z a numerical value. The error shouldnıt occur untilyou use F though, since you used SetDelayed. So, the error message goeswith a line you didnıt include in your post. However, in your latestpost, the linesNumericQ[z]Falsetell me z is NOT a real number. For instance,NumericQ[1.2]TrueSo, proceeding with the theory that z needs to be numeric, letıs tryF[1.2]NIntegrate::itraw:Raw object 1.2` cannot be used as an iterator.NIntegrate[f[y, 1.2], {1.2, 0, InŜnity}]NIntegrate::itraw:Raw object !(1.2`) cannot be used as aniterator.As you see, in the deŜnition of F, youıve used z as an iterator. Nomatter what the argument z to F is -- number, symbol, whatever -- youcanıt use it as an iterator, because it already has an identity, anditerators are stand-ins -- temporary variables that donıt exist outside(in this case) NIntegrate. So, as Jens-Peer pointed out, y should havebeen your iterator. (Probably. We donıt actually know what you weretrying to do. We only know for sure that z couldnıt be the iterator.)So, if Iıve made the right guesses, the deŜnition for F should beF[z_] := NIntegrate[f[y, z], {y, 0, InŜnity}]But... F[z] will still give you an error if z doesnıt have a numericalvalue, so itıs even better to deŜne F this way:ClearAll[F]F[z_?NumericQ] := NIntegrate[f[y, z], {y, 0, InŜnity}]That way, F[z] is left unevaluated if z isnıt numeric.I canıt go any further, since I donıt know the value of f -- because Idonıt know where to add or subtract that pesky parenthesis. (I askedstill isnıt.)Bobby Treat-----Original Message-----> F[z_?NumericQ]: = NIntegrate[f[y,z], {y, 0, InŜnity}]>Iım a newbie, bat I mean:*************************In[1]= NumericQ[z]Out[1]=False*************************BTW, z is a real number.--Rob_jack====Iım learning the Ŝne art of patterns and Hold one tricky example at atime.Bobby-----Original Message-----> I want to make a list of all symbols in the Global context, as in> Names[Global`*]> and compute a ByteCount for each symbolıs OwnValues -- without> evaluating the symbols.> It seems possible in principle, but I havenıt found a way.> Bobby Treat====Hereıs the fairly useful bit of code I came up with, using Jens-Peerısbrilliant solution:names = Names[Global`*];counts = ToExpression[#, StandardForm, Hold] & /@ names /. Hold[a_] :> ByteCount[OwnValues[a]];Select[Transpose[{names, counts}], Last@# > 16 &] // TableFormIt tells me how some of my memory is being spent.Bobby Treat-----Original Message-----> I want to make a list of all symbols in the Global context, as in> Names[Global`*]> and compute a ByteCount for each symbolıs OwnValues -- without> evaluating the symbols.> It seems possible in principle, but I havenıt found a way.> Bobby Treat====Jack,Often, what I do when developing a slightly complicated module is to Ŝrsttest it after I add each statement L1, L2, etc. But then often I want tomake changes after I have all the statements in. Then to debug I just addtemporary Print statements. For example...myFunction[f_] := Module[ {L1,L2,L3},L1 = ... ;L2 = ... ;Print[{L1, L2}];l3 = ... ;]Sometimes I use multiple Print statements. The only problem with thisapproach is that sometimes the difŜculty might be in a subexpression of alonger expression.This forces me to temporarily break out the longer expression into multiplestatements, or perhaps duplicate the subexpression in the Print statement.But I Ŝnd that the easiest method to track down errors.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/l3 = ... ; Ŝnal step ]To see what went wrong, I use (* *) selectively as follows:Stage 1myFunction[f_] := Module[ {L1,L2,L3},L1 = ... (*;L2 = ... ;L3 = ... ; Ŝnal step *) ]Thus I see if L1 worked as expected. The next step is to put (* after L2and see if this works. I continue this til the bitter end and I usuallyŜnd my errors.My question; The process of moving (* *) step by step through theprogram is quite tedious when the code has lots more lines. What I wouldlike is a meta-program which (like FoldList) does this job for me. Theoutput of this meta-program is the list of outputs of each line in themodule, probably best printed as a column.This sounds like Trace but my problem with Trace is it is terriblydifŜcult to read. For the not-so-subtle programming I do, the only thingI need is what expression is returned line by line.Any advice? All remarks are appreciated!Jack====The following code is my attempt to provide the functionality yourequested. It does some rudimentary error checking, but I havenıttried very hard to fool it. The code manipulates the DownValues,locating the highest CompoundExpression (see the lines in whichpos is deŜned), keeping only those expressions speciŜed.DownValues are restored after the expression is evaluated. The trickypart is keeping the CompoundExpression from evaluating while it isbeing manipulated. (See the lines in which held and new aredeŜned.) Iım not sure Iım doing this part the most elegant way, butit seems to work.(* code starts here *)PartialEvaluation::usage = PartialEvaluation[f[args], n] returnsf[args] where only the Ŝrst n expressions are evaluated in themainCompoundExpression in DownValues[f]. For example:ntClear[f]ntf[x_] := Module[{a,b}, a=3; b=4; a b x]ntPartialEvaluation[f, 2]n returns 4.PartialEvaluation::dvprob = DownValues[``] is either empty or hasmorethan one element.PartialEvaluation::toobig = There are only `1` expressions inthe CompoundExpression in `2`.PartialEvaluation::noce = There are no CompoundExpressions inDownValues[``].SetAttributes[PartialEvaluation, HoldFirst]PartialEvaluation[f_[args__], n_Integer] := Module[{dv, pos, held, new, eval}, Catch[ dv = DownValues[f]; If[Length[dv] != 1, Message[PartialEvaluation::dvprob, f]; Throw[HoldForm[f[args]]]]; pos = Sort[Position[dv, CompoundExpression]]; If[pos == {}, Message[PartialEvaluation::noce, f]; Throw[HoldForm[f[args]]]]; pos = Drop[First @ pos, -1]; held = Extract[dv, pos, Hold] /. CompoundExpression -> Sequence; If[Abs[n] > Length[held], Message[PartialEvaluation::toobig, Length[held], HoldForm[f[args]]]; Throw[HoldForm[f[args]]]]; new = ReplacePart[dv, Take[held, n] /. Hold[x__] :> Hold[CompoundExpression[x]], pos, 1]; DownValues[f] = new; eval = f[args]; DownValues[f] = dv; eval ]](* code ends here *)--Mark.P.S. The version of this message I posted directly from my newsreaderdidnıt show up, so Iım reposting (a slightly improved version) fromGoogle.> Jack,> Often, what I do when developing a slightly complicated module is to Ŝrst> test it after I add each statement L1, L2, etc. But then often I want to> make changes after I have all the statements in. Then to debug I just add> temporary Print statements. For example...> myFunction[f_] := Module[ {L1,L2,L3},> L1 = ... ;> L2 = ... ;> Print[{L1, L2}];> l3 = ... ;> ]> Sometimes I use multiple Print statements. The only problem with this> approach is that sometimes the difŜculty might be in a subexpression of a> longer expression.> This forces me to temporarily break out the longer expression into multiple> statements, or perhaps duplicate the subexpression in the Print statement.> But I Ŝnd that the easiest method to track down errors.> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> I often run into this difŜculty: 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 = ... ;> Ŝnal step> ]> To see what went wrong, I use (* *) selectively as follows:> Stage 1> myFunction[f_] := Module[ {L1,L2,L3},> L1 = ... (*;> L2 = ... ;> L3 = ... ;> Ŝnal 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> Ŝnd 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> difŜcult 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====Mathematica often produces complex resluts. But the problem is not complex:TrySolve[FR == Pi r1^2 - Pi r2^2, r1]It is simple to eliminate it in this case. Just square it.Does someone give me a hint, how to write ra rule for simplify, lik Ted Ersek did inhttp://www.verbeia.com/mathematica/tips/Links/Tricks_lnk_41 .htmlI thin, one has to to replace the patterni Sqrt[-a_]bySqrt[(i Sqrt[-a_])^2]and then one has to simplify it?Peter Klamser====There has been an interesting discussion about using InterpolatingFunctionfor an empirical CDF.If one is willing to sacriŜce some theoretical soundness, an empirical CDFmay be computed in a simpliŜed form:simpleEmpiricalCDF[distr_/;VectorQ[distr,NumberQ]] :=With[{nonu=Sort[distr], u=Union[distr]},Transpose[{u,FoldList[Plus,0,(Count[nonu,#]&/ @u)/Length[nonu]]//Rest}]]This code does not return a function, and the result needs someinterpretation. Nevertheless, it may be of some use.data = {0.59, 0.72, 0.47, 0.43, 0.31, 0.56, 0.22, 0.9, 0.96, 0.78, 0.66,0.18, 0.73, 0.43, 0.58, 0.11}(the tie [0.43] will be accounted for in a way that is consistent with sometextbooks)simpleEmpiricalCDF[data]//N returns{{0.11,0.0625},{0.18,0.125},{0.22,0.1875},{0.31,0.25}, {0.43,0.375},{0.47,0.4375},{0.56,0.5},{0.58,0.5625},{ 0.59,0.625},{0.66,0.6875},{0.72,0.75},{0.73,0..8125},{ 0.78,0.875},{0.9,0.9375},{0.96,1.}}A plot may be given with:simpleEmpiricalCDFPlot[distr_/;VectorQ[distr,NumberQ]] :=Module[{res,x,p},res=simpleEmpiricalCDF[distr];x=({#,#}& /@ Transpose[res][[1]])//Flatten;p=({#,#}& /@ Transpose[res][[2]])//Flatten;p= Join[{0},Drop[p,-2],{1}];ListPlot[Transpose[{x,p}],c]]Again, this plot does not reŝect theoretical considerations at the lowerand upper end.With regardHermann Meier====Caution: where right- and left-continuity are concerned, Danielısrelying on undocumented behavior that may change in the next version.Bobby-----Original Message-----that evaluates the empirical CDF given the observations in the list.The function is deŜned on the entire real line.MakeEmpiricalCDF[list_?(VectorQ[#, NumericQ]&)] := Module[{n, s, a, r, idata}, n = Length[list]; s = Sort[list]; a = Append[s, s[[-1]] + 1]; (* phantom obs. *) r = Range[1/n, 1 + 1/n, 1/n]; (* phantom value 1 + 1/n *) idata = Last /@ Split[Transpose[{-a, r}], #1[[1]] == #2[[1]]&]; (* -a is the Ŝrst sign change *) Block[{x}, Function @@ {x, Which @@ { x < s[[ 1]], 0., x > s[[-1]], 1., True, Interpolation[idata, InterpolationOrder -> 0][-x] (* -x is the second sign change *) }}] ]The construction Last /@ Split[ ... ] accounts for duplicate values.Here are two examples. Needs[Statistics`ContinuousDistributions`]list1 = RandomArray[NormalDistribution[0, 1], 100];f1 = MakeEmpiricalCDF[list1];Plot[f1[x], {x, -4, 4}]list2 = Table[Random[Integer, {1, 10}], {10}];f2 = MakeEmpiricalCDF[list2];Plot[f2[x], {x, 0, 11}]--Mark> Iım trying to write a fast empirical cummulative distribution function> (CDF). Empirical CDFs are step functions that can be expressed in> terms of a Which statement. For example, given the list of> observations {1, 2, 3},> f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&> is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}> and f is continuous from the right.> When the number of observations is large, the Which statement> evaluates fairly slowly (even if it has been Compiled). Since> InterpolationFunction evaluates so much faster in general, Iıve tried> to use Interpolation with InterpolationOrder -> 0. The problem is that> the resulting InterpolatingFunction doesnıt behave the way (I think)> it ought to. For example, let> g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->> 0]> Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.> In addition, g is continuous from the left rather than from the right.> Obviously I am not aware of the considerations that went into> determining the behavior of InterpolationFunction when> InterpolationOrder -> 0.> So I have two questions: > (1) Does anyone have any opinions about how InterpolatingFunction> ought to behave with InterpolationOrder -> 0?> (2) Does anyone have a faster way to evaluate an empirical CDF than a> compiled Which function?> By the way, hereıs my current version:> CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]> --Mark====Hey,How can I duplicate those nifty ŒMoreı hyperlinks in my usagestatements? That is the hyperlinks that appears at the end of text thatis generated after invoking a Œ?ı to get more information about a function.Lawrence====>Iıve got to extract some numbers from a Ŝle 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.ReadList returns a List not a String. So, y is a List and StringTake fails since it expects a String.Also, you do not need the options RecordLists->True when reading Strings. Nor do you need the OpenRead/Close statements with ReadListTryy = First[readList[197-tst.txt,String,1];y1 = StringTake[y, {25,110}];====>Does anybody know how to calculate in Mathematica: >a)empirical CDF,>b)empirical PDF, >c)normal QQ-plot; >d)QQ-plot two different random samples?!Yes, but there are a number of issues particularly with an empirical PDF. A 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 signiŜcant effect for large data sets.====> I am trying to implement a very simple sorted tree to quickly store some> real numbers I need. I have written an add, delete, minimum, and pop> (delete the lowest value) function and they seem to work ok but are very> slow. Letıs just look @ my implementation of the add part:> nums=Null;(*my initial blank Tree)> In[326]:=> Clear[add]> In[327]:=> add[Null,x_Real]:=node[x,Null,Null]> add[Null,node[x_Real,lower_,higher_]]=node[x,lower,higher]> In[328]:=> add[node[x_Real,lower_,higher_],y_Real]:=> If[x>y,node[x,add[lower,y],higher],node[x,lower,add[higher,y] ]]> In[288]:=> add[node[x_Real,lowerx_,higherx_],node[y_Real,lowery_,highery _]]:=If[x>y,> node[x,add[lowerx,node[y,lowery,highery]],higherx],> node[x,lowerx,add[higherx,node[y,lowery,highery]]]> ]> Now this is my attempt to test how fast my add works:> SeedRandom[5];> Do[nums=add[nums,Random[]],{5000}];//Timing> Out[333]=> {13.279 Second,Null}> running on an 1.4GHz Athlon with 1GB of ram).> Questions:> 1. Is this as fast as I can get my code to run?> 2. Am I doing something obviously stupid?> 3. would Compiling things help?> HusainIıll respond to your third question Ŝrst. No, use of Compile will nothelp. You do not have a tensor structure and moreover it will copy itsarguments. Hence invoking it within a loop would be quite slow for aproblem where the argument grows in size.One thing you did not check is the actual run-time complexity of yourcode. On my 15.GHz machine I get:In[6]:= SeedRandom[5];In[7]:= ee = Table[Random[], {10000}];In[8]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,1000}];]Out[8]= {0.34 Second, Null}In[9]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,2000}];]Out[9]= {1.28 Second, Null}In[10]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,4000}];]Out[10]= {4.94 Second, Null}In[11]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,8000}];]Out[11]= {25.08 Second, Null}We see this is clearly of no better than quadratic complexity, whereas Iwould guess you were expecting O(n*Log[n]). So this indicates a problem.Offhand I do not know what aspect of your code is responsible, but Iıllgive some different code that has the desired complexity.Note that some of this, and code very similar to that below, isdiscussed at:http://library.wolfram.com/conferences/devconf99/lichtblau /in the section entitled Trees.There is a corresponding Mathematica notebook available at:http://library.wolfram.com/conferences/devconf99/near the bottom of the web page.The code I used to implement a tree structure similar to yours is below.One difference is that, as I place node values in the center, when theyare ŝattened the tree is automatically sorted. You might (or might not)regard this as an added beneŜt.leftsubtree[node[left_, _, _]] := leftrightsubtree[node[_, _, right_]] := rightnodevalue[node[_, val_, _]] := valemptyTree = node[];Clear[treeInsert]treeInsert[emptyTree, elem_] := node[emptyTree, elem, emptyTree]treeInsert[tree_, elem_] /; OrderedQ[{nodevalue[tree], elem}] := node[leftsubtree[tree], nodevalue[tree], treeInsert[rightsubtree[tree], elem]]treeInsert[tree_, elem_] := node[treeInsert[leftsubtree[tree],elem], nodevalue[tree], rightsubtree[tree]]Now for some tests.In[40]:= tt1k = First[Timing[ff1k = node[]; Do[ff1k = treeInsert[ff1k, ee[[j]]], {j,1000}];]] Out[40]= 0.15 SecondWe will check that the ŝattened version is actually sorted.In[41]:= gg1k = Apply[List,Flatten[ff1k]];In[42]:= gg1k === Sort[Take[ee,1000]]Out[42]= TrueAlso we will observe that the maximum depth is reasonable.In[43]:= Depth[ff1k]Out[43]= 23In the perfectly balanced case it would be 10 so this is not too bad.For larger examples Iıll just show timings.In[44]:= tt2k = First[Timing[ff2k = node[]; Do[ff2k = treeInsert[ff2k, ee[[j]]], {j,2000}];]]Out[44]= 0.32 SecondIn[45]:= tt4k = First[Timing[ff4k = node[]; Do[ff4k = treeInsert[ff4k, ee[[j]]], {j,4000}];]]Out[45]= 0.73 SecondIn[47]:= tt8k = First[Timing[ff8k = node[]; Do[ff8k = treeInsert[ff8k, ee[[j]]], {j,8000}];]]Out[47]= 1.58 SecondIn[53]:= SeedRandom[5]; ee = Table[Random[], {32000}];In[54]:= tt32k = First[Timing[ff32k = node[]; Do[ff32k = treeInsert[ff32k, ee[[j]]], {j,32000}];]]Out[54]= 7.58 SecondThis is not of blinding speed but it has the advantage of exhibiting theappropriate run-time complexity. One can, with careful coding, cut downon tree size but if you check with LeafCount you will Ŝnd that theversion above is already not too wasteful (3x larger than #valuesstored). Moreover the code needed would run a bit slower as it wouldhave more cases to check.As for removing nodes, I think you will need to use some form of heldattribute so as to avoid copying the entire tree when you alterelements.Daniel LichtblauWolfram Research====>>So far, so good. It seems that you want these 11 numbers, OK? Theproblemnow, I think, is that this is just a string and I can think of no easywayto convert it precisely into a list of 11 real numbers.You could try StringToStream followed by a Read from that stream.Bobby Treat-----Original Message-----None];This allowed me to examine your records and I found out that in this wayeach record comes out as a list of length 1: In[2]:=Head[a[[1]]]Out[2]=ListIn[3]:=Length[a[[1]]]Out[3]= 1That is,In[3]:=a[[1]]Out[3]=317. 367. -115. 126. 146. -410. -426.000000EF 75.}In[4]:=StringLength[a[[1,1]]]Out[4]=140and the characters you want areIn[5]:=StringTake[a[[1,1]], {25, 110}]Out[5]=5935.80 5946.66 27.06 -1281.9 -229. 321. 317. 367. -115.126. 146.So far, so good. It seems that you want these 11 numbers, OK? Theproblemnow, I think, is that this is just a string and I can think of no easywayto convert it precisely into a list of 11 real numbers. Then, I suggestyouread the Ŝle in a different way, without the WordSeparators option:In[6]:=b=ReadList[197-tst.txt,Word,RecordLists -> True];In[7]:=b[[1]]Out[7]=.,-115.,126.,146.,-410.,- 426.000000EF,75.}In[8]:=Head[b[[1]]]Out[8]=ListIn[9]:=Length[ b[[1]]]Out[9]=19so that each record is now a list of 19 strings. What you want isstrings 6to 16, but converted to reals (unless Iım being presumptuous). This willachieve that:In[10]:=ToExpression[Take[b[[1]],{6,16}]]Out[10]={ 5935.8,5946.66,27.06,-1281.9,-229.,321.,317.,367.,-115.,126., 146.} Now you have a nice list of real numbers to work with. You can do thisforthe whole Ŝle like this:In[11]:=ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem.Tomas GarzaMexico City> ----- Original Message -----> Sent: Friday, September 13, 2002 12:14 AMfrom a Ŝle...>> Iıve got to extract some numbers from a Ŝle that are in lines oftext.> Since the line contents are not numbers, I presume I must pull thelineout> 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 to110to> get just the stuff I want:> y1=StringTake[y ,{25,110}];>> Hereıs the output. StringTake doesnıt seem to work.>-229.> 321. 317. 367. -115. 126. 146. -410. -426.000000EF 75.},> {25, 110}]>> It doesnıt take loading another package as far> as I can tell from the help. Iım thinking that it doesnıt workbecause> itıs trying to work on a list> rather than a string. Iıve tried Flatten, and other stuff to try togetto> just a string and not a list but> nothing has worked so far. Iım a long way from getting to thosenumbers> in there but heck, I> canıt even get to the string. Can anyone point me in the rightdirection?>>-------------------------------------------- ------------------------====Evaluate ?Floor and then, with your cursor in the output cell from that,push Ctrl-Shift-E, and you should see something like:Information[Floor, LongForm -> False]Floor[x] gives the greatest integer less than or equal tox.*Button[More[Ellipsis], ButtonData :> Floor, Active -> True, ButtonStyle -> RefGuideLink]OK. Change ButtonData :> Floor to ButtonData :> Ceiling, and pushCtrl-Shift-E again. Push the More... button, and you should go toCeiling in the Help Browser, not Floor.Another method is to click Input>Create Button>RefLink and type inCeiling. You should get a button that takes you to Help for Ceiling.Push Ctrl-Shift-E in both cells and compare, and youıll see some cluesto your options. Clues are all you get in Mathematica, so get used toit!Bobby Treat-----Original Message-----====Since r1 and r2 only appear squared, you can do it this way:Simplify[Solve[FR == Pi*r1Sq - Pi*r2Sq, r1Sq]]{{r1Sq -> FR/Pi + r2Sq}}orSimplify[Solve[FR == Pi*r1Sq - Pi*r2^2, r1Sq]]{{r1Sq -> FR/Pi + r2^2}}Then r1 is the square root of r1Sq. In the complex plane, real numbershave two square roots, but we usually ignore that.Bobby Treat-----Original Message-----http://www.verbeia.com/mathematica/tips/Links/ Tricks_lnk_41.htmlI thin, one has to to replace the patterni Sqrt[-a_]bySqrt[(i Sqrt[-a_])^2]and then one has to simplify it?Peter Klamser====> 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.Beside the Print statements, sometimes I do the following. Put the functionto be tested in its own context and then empty the list of local symbols,e.g.,myfunction[stuff__] := Module [{}, expr1; expr2; ... ]so that all temporary variables deŜned within the function are now globalwithin the new context. Then I can examine the values of all these variablesafter execution of the function and can often Ŝnd the error. If the erroris caused by a complex expression of nested functions, then I unwind thecomplex expression, adding more temporary variables, until I see theproblem. Then I think twice before recomplexifying.The two advandages of a special context are (1) I donıt get the previouslylocal symbols mixed up with other symbols and (2) I can examine all of themand only them with TableForm[{#,ToExpression[#]}&/@Names[mynewcontext`*]]Once I do this, I often leave the new context in place. Mathematica seems tobe able to handle a large number of contexts efŜciently.Tom Burton====I have quite an easy and annoying problem with mathematica:I need to deŜne a function f(x,y) which takes some values forx=0,2pi,4pi (indepently of y) and has a different expression for allthe other values of y. This is easily done for one-dimensionalfunctions but I am in serious troubles for my two-dimensional problem:any suggestion?FabioReply-To: kuska@informatik.uni-leipzig.de====Clear[f]f[0, _] := qf[Pi, _] := pf[2Pi, _] := rf[x_, y_] := x^2*y^2??? Jens> I have quite an easy and annoying problem with mathematica:> I need to deŜne 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 deŜne 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?> FabioThere 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 byf(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 deŜne 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?> FabioLet the known values of the function at x={0,2Pi,4Pi} be {f0,f2,f4}.Your conditions can be met byf(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 deŜne 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?> FabioSomething 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 PiOut[2]= EIn[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 deŜne 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_] := 5f[2 Pi, y_] := 7f[4 Pi, y_] := -3f[x_ /; x < 0, y_] := x yf[x_ /; 0 < x < 2 Pi, y_] := x + yf[x_ /; 2Pi < x < 4 Pi, y_] := x - yf[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 deŜne 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?>FabioItıs difŜcult to guess what you wanted to attain and what your problemswere. Perhaps this example might help you:In[11]:= f[x_, _] /; Mod[x, 2Pi] == 0 := x/(2Pi)In[12]:= f[x_, y_] := x + yIn[13]:= epsilon = $MachineEpsilonOut[13]= 2.220446049250313*^-16In[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 deŜnition.--Hartmut====I am new with Mathematica, I have one question,I know that the sollution might be very easy, but I wasnıt able toŜnd 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 = 4Maciej====Although it is not outstanding, I prefer to write your equation in the form:9*x^2+4*x*y+6*y^2==400In 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>====Ŝrst 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.09x^2 +0.04 x y + 0.06 y^2 = 4 for x varying into a given range.As you can veryŜng 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. ifapproximatively -6 True]the same for the other soluztion.good luck-upimak 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> Ŝnd 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> Ŝnd 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.eduMathematics & Statistics Dept.Lederle Graduate Research Tower phone 413 549-1020 (H)University of Massachusetts 413 545-2859 (W)710 North Pleasant StreetAmherst, MA 01375Reply-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> Ŝnd 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 itgets 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ısinputs Ŝrst, and so NDSolve is trying to solve the differential equationyıı[x]+y[x]==x^2 instead of yıı[x]+y[x]==f[x]. By restricting the deŜnitionof 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 incase the old deŜnition of f was still there.Carl WollPhysics DeptU 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 aftercont = 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 itto an internal function. So *your* function is only oncewhen Mathematica can include it into itıs internal functionfor 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 arationalization error is allowed and there is always the question about whatdomain around 2nPi you want to include in the Ŝrst deŜnition.David Parkdjmp@earthlink.nethttp://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 Ŝles which load much quicker than .m Ŝles.It would be really nice if WRI could investigate why loading larger .m Ŝles is so slow ( I suspect it has to do something with the speed of side effectslike DownValues declarations etc., but I donıt know ).Rolf MertigMertig Consultinghttp://www.mertig.com============================== ====DeclareePackage[OtherPackage`, {BigVariable} ]. The idea was to preventthe loading of a large Ŝle in routine cases. However, when ThisPackage`deŜnes its functions, inside the Private` area, it includes a conditionalcall to BigVariable. It turns out that OtherPackage is loaded when thatfunction is deŜned. I was wondering if there is a way to avoid this.Roughly speaking, here is the setting:BeginPackage[ OtherPackage` ]BigVariable::usage=exampleBegin[Private`]BigVariable=Table[x y,{x,1000},{y,1000}]End[ ]EndPackage[ ]BeginPackage[ ThisPackage` ]function::usage=exampleBegin[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 withx>1000 but it loads when function is deŜned. 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 thedesired end base.Is there a single command or simple function to do such conversions? Forexample,ConvertBase[from_, to_, num_]would convert from base to base 9 using the number num as the number toconvert (it would best be allowed to let users input in that speciŜc basesince theyıd be going from base 3 to base 9, for example so maybe num isneeded at all).====Dear NGMabye this is too simple, but I cant just Ŝgure it outI want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]]andR[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= Dear NG> Mabye this is too simple, but I cant just Ŝgure 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=> after that I hope to be able to calculate the integral :>> 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>>====Martin,In a post a while ago, I introduced a function called NInverse which oughtto be able to help you out. The message can be found athttp://library.wolfram.com/mathgroup/archive/2001/Jun/ msg00125.htmlThe output of NInverse (in your case) is a function which given a value of yreturns 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 WollPhysics DeptU of Washington> Dear NG> Mabye this is too simple, but I cant just Ŝgure 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=> after that I hope to be able to calculate the integral :>> 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>====There is a very nice java applet athttp://statman.stat.sc.edu/~west/javahtml/classes/ , in which you caninclude 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 widthand see how this effects the histogram....it wasnt until I saw this that iunderstood the signiŜcance 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 addressesthe empirical CDF. However, in this code you may want to replace 1/n with1/(n+1) or (j-0.5)/n depending on your application. Note, these will have nosigniŜcant effect for large data sets.The key issue with an empirical PDF is deciding the bin width. A simpleapproach would be to use the functions in Statistics`DataManipulation` andBinListCounts. More sophisticated approaches involve kernel methods. Thesemethods will generate smoother estimates for the PDF. Again, the key isbandwidth. There is no apriori choice for bin width or bandwith. Bad choiceswill obscure signiŜcant features in the data set.====A while back someone asked if Mathematica could plot data one point at atime....most answers were no, with one exception, where someone showed howto use the same Graphic Cell repeatedly....here is some Mathematica, JLinkprogram that will do just that... << JLink` InstallJava[CommandLine -> c:j2sdk1.4.1binjava.exe] (* or setcommand line to where your java.exe is *)UseFrontEndForRendering = False;createWindow[] := Module[{frame}, frame = JavaNew[com.wolfram.jlink.MathFrame, Drawing Sine Wave AnimationOne 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, ŝ====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 Ŝnd the element of the table that has the largest Ŝrst 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 ScienceTruman State University100 East Normal St.Kirksville, MO 63501http://vh216801.truman.edu660.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 Ŝrst 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 (deŜning 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 > Ŝnd the element of the table that has the largest Ŝrst 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 AddressReply-To: kuska@informatik.uni-leipzig.de====fun[x_, y_] := x^2 + y^2RandomMin[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> Ŝnd the element of the table that has the largest Ŝrst 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.7430Reply-To: murray@math.umass.edu====The same principles that allow particular cases for deŜning 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^3This 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 Ŝrst 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 deŜne 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.eduMathematics & Statistics Dept.Lederle Graduate Research Tower phone 413 549-1020 (H)University of Massachusetts 413 545-2859 (W)710 North Pleasant StreetAmherst, 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 makeyourself 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_] := yf[2*Pi | N[2*Pi], y_] := y^2f[4*Pi | 4.*Pi, y_] := y^3f[x_, y_] := y^4If the Ŝrst three of those expressions are supposed to be the same, youcan substitutef[0 | N[0] | 2*Pi | N[2*Pi] | 4*Pi | 4.*Pi, y_] := y^3Bobby Treat-----Original Message-----Fabio==== 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 fHow can I do that? Please suggest. Raj====Well, you can just solve for h. However, in this case there isnıt a symbolicsolution.>> 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 seriesexpansion as long as the function is monotonser = 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 workcorrectly. It advances instead of go back and there is pointer mark of the mouse looks like a hand insteadof an arrow, and this donıt work Ŝne too.ConŜguration one? How can I solve this?Note: This problem seems to appear just in myworkspacei mean this not happen for other users. Cesar. __________________________________________________Do you Yahoo!?Yahoo! News - Todayıs headlineshttp://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 Ŝne too.> ConŜguration 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====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 Ŝnd 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 Ŝnd 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 asspecialized and esoteric as programming in microcode or assembler seems today. -- Stephen Wolfram, creator of MathematicaReply-To: kuska@informatik.uni-leipzig.de====Hmm,oldOptions=Options[ Graphics3D];SetOptions[Graphics3D,Boxed->False](* do something with it *)SetOptions[Graphics3D, Sequence @@ oldOptions]works Ŝne. 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 Ŝnd 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 slightlyslower. 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 shortcutfor walking the tree left-to-right. > Bobby TreatIt seems I did not look hard enough at the original post or thefollow-ups. In point of fact, regarding speed, there IS no obviousadvantage of my code over that Ŝrst version. The advantage is there, ofcourse, as timing checks indicate. But it is quite far from obvious.The reason is related to the (rare) need for Update. It is pointed outin the manual that inŜnite evaluation is not in fact possible (nosurprise thus far). A consequence is that Mathematica requires internaloptimization features to keep reevaluation to a minimum. Update may berequired in cases where such optimizations are overzealous.What we have in the case of this example is, roughly, the opposite. Thecode that determines need for reevaluation is simply not workingsufŜciently well. It does make the correct determination, but onlyafter looking over the entire structure that is being evaluated. As wehave a structure growing linearly in the number of iterations, and itgets mostly traversed each iteration, the algorithmic complexity becomesat least O(n^2). Not a disaster unless the appropriate complexity issmaller, which was the case for this example.This is not a bug insofar as it is a (regretably) necessary consequenceof Mathematica evaluation semantics. The problems it can cause are allthe same quite undesirable. Weıve made some inroads on this problem byenlarging substantially the class of expressions for which reevaluationmay be quickly short-circuited, with the idea of Ŝxing all but the mostpathological of examples. The status of that work is unfortunately notknown to me at present, though Iıll try to Ŝnd out about it.Daniel LichtblauWolfram Research====This code is almost identical to yours in principle, yet 30% faster:(compared with the code in your notebook, not the code in the postbelow)ClearAll[emptyTree, treeInsert];emptyTree = {};treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree}treeInsert[tree_, elem_] /; SameQ[tree[[2]], elem] := treetreeInsert[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 see one obvious advantage of your algorithm over Husainıs and myearlier code; though Iım not sure it explains its better behavior. Thatis, while my algorithm made pattern matching more burdensome, yoursvirtually eliminated it.Also, the biggest improvement Iıve seen comes simply from replacing Nullwith anything else in Husainıs code. Again, that seems to suggest thattime spent on pattern matching is the problem. All the algorithms doapproximately the same real work on the tree structure.I really like how Flatten changes your tree into a sorted list. Verynice!Bobby Treat-----Original Message-----> (delete the lowest value) function and they seem to work ok but arevery> slow. Letıs just look @ my implementation of the add part:> nums=Null;(*my initial blank Tree)> In[326]:=> Clear[add]> In[327]:=> add[Null,x_Real]:=node[x,Null,Null]> add[Null,node[x_Real,lower_,higher_]]=node[x,lower,higher]> In[328]:=> add[node[x_Real,lower_,higher_],y_Real]:=> If[x>y,node[x,add[lower,y],higher],node[x,lower,add[higher,y] ]]> In[288]:=>add[node[x_Real,lowerx_,higherx_],node[y_Real, lowery_,highery_]]:=If[x>y,> node[x,add[lowerx,node[y,lowery,highery]],higherx],> node[x,lowerx,add[higherx,node[y,lowery,highery]]]> ]> Now this is my attempt to test how fast my add works:> SeedRandom[5];> Do[nums=add[nums,Random[]],{5000}];//Timing> Out[333]=> {13.279 Second,Null}> RH7.3> running on an 1.4GHz Athlon with 1GB of ram).> Questions:> 1. Is this as fast as I can get my code to run?> 2. Am I doing something obviously stupid?> 3. would Compiling things help?> HusainIıll respond to your third question Ŝrst. No, use of Compile will nothelp. You do not have a tensor structure and moreover it will copy itsarguments. Hence invoking it within a loop would be quite slow for aproblem where the argument grows in size.One thing you did not check is the actual run-time complexity of yourcode. On my 15.GHz machine I get:In[6]:= SeedRandom[5];In[7]:= ee = Table[Random[], {10000}];In[8]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,1000}];]Out[8]= {0.34 Second, Null}In[9]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,2000}];]Out[9]= {1.28 Second, Null}In[10]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,4000}];]Out[10]= {4.94 Second, Null}In[11]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,8000}];]Out[11]= {25.08 Second, Null}We see this is clearly of no better than quadratic complexity, whereas Iwould guess you were expecting O(n*Log[n]). So this indicates a problem.Offhand I do not know what aspect of your code is responsible, but Iıllgive some different code that has the desired complexity.Note that some of this, and code very similar to that below, isdiscussed at:http://library.wolfram.com/conferences/devconf99/lichtblau /in the section entitled Trees.There is a corresponding Mathematica notebook available at:http://library.wolfram.com/conferences/devconf99/near the bottom of the web page.The code I used to implement a tree structure similar to yours is below.One difference is that, as I place node values in the center, when theyare ŝattened the tree is automatically sorted. You might (or might not)regard this as an added beneŜt.leftsubtree[node[left_, _, _]] := leftrightsubtree[node[_, _, right_]] := rightnodevalue[node[_, val_, _]] := valemptyTree = node[];Clear[treeInsert]treeInsert[emptyTree, elem_] := node[emptyTree, elem, emptyTree]treeInsert[tree_, elem_] /; OrderedQ[{nodevalue[tree], elem}] := node[leftsubtree[tree], nodevalue[tree], treeInsert[rightsubtree[tree], elem]]treeInsert[tree_, elem_] := node[treeInsert[leftsubtree[tree],elem], nodevalue[tree], rightsubtree[tree]]Now for some tests.In[40]:= tt1k = First[Timing[ff1k = node[]; Do[ff1k = treeInsert[ff1k, ee[[j]]], {j,1000}];]] Out[40]= 0.15 SecondWe will check that the ŝattened version is actually sorted.In[41]:= gg1k = Apply[List,Flatten[ff1k]];In[42]:= gg1k === Sort[Take[ee,1000]]Out[42]= TrueAlso we will observe that the maximum depth is reasonable.In[43]:= Depth[ff1k]Out[43]= 23In the perfectly balanced case it would be 10 so this is not too bad.For larger examples Iıll just show timings.In[44]:= tt2k = First[Timing[ff2k = node[]; Do[ff2k = treeInsert[ff2k, ee[[j]]], {j,2000}];]]Out[44]= 0.32 SecondIn[45]:= tt4k = First[Timing[ff4k = node[]; Do[ff4k = treeInsert[ff4k, ee[[j]]], {j,4000}];]]Out[45]= 0.73 SecondIn[47]:= tt8k = First[Timing[ff8k = node[]; Do[ff8k = treeInsert[ff8k, ee[[j]]], {j,8000}];]]Out[47]= 1.58 SecondIn[53]:= SeedRandom[5]; ee = Table[Random[], {32000}];In[54]:= tt32k = First[Timing[ff32k = node[]; Do[ff32k = treeInsert[ff32k, ee[[j]]], {j,32000}];]]Out[54]= 7.58 SecondThis is not of blinding speed but it has the advantage of exhibiting theappropriate run-time complexity. One can, with careful coding, cut downon tree size but if you check with LeafCount you will Ŝnd that theversion above is already not too wasteful (3x larger than #valuesstored). Moreover the code needed would run a bit slower as it wouldhave more cases to check.As for removing nodes, I think you will need to use some form of heldattribute so as to avoid copying the entire tree when you alterelements.Daniel LichtblauWolfram Research====Daniel,Iıd say your algorithm (as an ALGORITHM) is precisely the same asHusainıs. The implementation is different, but the logical steps arethe same (except perhaps for <= vs. <), and so is the logical structureof the tree produced. Even the storage method is pretty much the same.Using {} instead of Null and List instead of Œnodeı, and putting valuesin the middle position, doesnıt add up to a change that could affectalgorithmic complexity.Even the fact that Flatten gives a sorted List with your implementationis something you get for free, and the advantage comes only when itıstime to output a sorted list. It has nothing to do with the work ofbuilding the tree.Algorithmic complexity (absent hidden factors under the kernelıscontrol) 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 ofthe kernel, pattern matching costs, etc. Our three nearly equivalentalgorithms simply incur different hidden costs.Thatıs the case with many of the problems that turn into speed warsamong us. We compare implementation speed (including hidden costs), notpure algorithmic complexity. Compiled code or packed arrays often makeall the difference, and it usually happens in the background where wecanıt see it.As youıve hinted below, the vagaries of Update can make a linearalgorithm quadratic, but may NOT so plague a slightly differentimplementation of the very same algorithm.So... Iım suggesting we might want to be careful when we leap toconclusions about algorithmic complexity based on a few timedexperiments.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 slightlyslower. 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 replacingNull> with anything else in Husainıs code. Again, that seems to suggestthat> 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 shortcutfor walking the tree left-to-right. > Bobby TreatIt seems I did not look hard enough at the original post or thefollow-ups. In point of fact, regarding speed, there IS no obviousadvantage of my code over that Ŝrst version. The advantage is there, ofcourse, as timing checks indicate. But it is quite far from obvious.The reason is related to the (rare) need for Update. It is pointed outin the manual that inŜnite evaluation is not in fact possible (nosurprise thus far). A consequence is that Mathematica requires internaloptimization features to keep reevaluation to a minimum. Update may berequired in cases where such optimizations are overzealous.What we have in the case of this example is, roughly, the opposite. Thecode that determines need for reevaluation is simply not workingsufŜciently well. It does make the correct determination, but onlyafter looking over the entire structure that is being evaluated. As wehave a structure growing linearly in the number of iterations, and itgets mostly traversed each iteration, the algorithmic complexity becomesat least O(n^2). Not a disaster unless the appropriate complexity issmaller, which was the case for this example.This is not a bug insofar as it is a (regretably) necessary consequenceof Mathematica evaluation semantics. The problems it can cause are allthe same quite undesirable. Weıve made some inroads on this problem byenlarging substantially the class of expressions for which reevaluationmay be quickly short-circuited, with the idea of Ŝxing all but the mostpathological of examples. The status of that work is unfortunately notknown to me at present, though Iıll try to Ŝnd out about it.Daniel LichtblauWolfram Research====Iım curious, why the built-in boolean functions And and Orarenı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 TrifonovVladivostok, Russia====Evgeni,Note that both And and Or can return a value without evaluating all oftheir arguments. For example, if the Ŝrst argument to And is False, thereis no reason to look at the other arguments. Suppose a user knows that oneof the arguments is usually false, and so would like to look at thatargument before any of the others, to avoid unneeded computations of theother arguments. He would put that argument Ŝrst. If Mathematica turnedaround and sorted the arguments (which is what happens when a function isorderless), then that argument might end up being evaluated last. If thearguments take a signiŜcant amount of time to compute, then sorting Ŝrstmay cause the function to take much longer to evaluate.At any rate, if the above is not a concern for you, you may always changethe attributes of And and Or to anything you want.Carl WollPhysics DeptU 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 deŜned 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 coefŜcient is the letter d or lower (solution Ŝne) or f or higher (solution wrong) . Here is an example: Using letter fIn[3]:=integrate[f Exp[-0.8316*tau], t]Out[3]:=integrate[f, t]/E^(0.8316*tau) (*wrong*)Using letter a (the solution is rigthIn[4]:=integrate[a Exp[-0.8316*tau], t]Out[4]:=-1.20250*a*(-1 + E^(-0.8316*t))What it wrong?GuillermoSanchez--------------------------------------- ------This message was sent using Endymion MailMan.====Neither of your solutions are wrong according to your rules.Lets step through themIn[3]:=integrate[f Exp[-0.8316*tau], t]lexographical (sp) order asIn[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 yourrule it is equal toExp[-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 theexponential are reversed, and you get the behaviour that you actuallydesired. A simple Ŝx is to replace the condition in rule 1 byFreeQ[c,t]&&FreeQ[c,tau]You may however want to think carefully about exactly what you want yourfunction integrate to do. For example, with the rules given, thevariable t and the variable tau seem to be playing the same role.Erich> I have deŜned 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 coefŜcient is> the letter d or lower (solution Ŝne) 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 BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de-----UrsprÌ.b9ngliche Nachricht-----Gesendet: Mittwoch, 18. September 2002 08:09An: mathgroup@smc.vnet.netBetreff: Drawing an ellipseI am new with Mathematica, I have one question,I know that the sollution might be very easy, but I wasnıt able toŜnd 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 = 4Maciej====Solve[eqn, var] and InverseFunction are designed to do what you want, inprinciple. TrySolve[(a*h+b*h^2) == f, h]For your eqn, however, it is impossible to solve for h since h appears as afactor in a sum *and* as an exponent.TrySolve[Exp[-h]*(a*h+b*h^2) == f, h] and study Mathematicaıs message.Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de-----UrsprÌ.b9ngliche Nachricht-----Gesendet: Mittwoch, 18. September 2002 08:10An: mathgroup@smc.vnet.netBetreff: 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 fHow 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 onlythe String obj to the setMathCommand method, not the contentof 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, withoutever 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 Ŝle called My_DisplayGraphicsViaJava.javaand compile it. Put the class Ŝle in a directory that is inyour CLASSPATH (or look up how the CLASSPATH works in J/Link2.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 theString array and the drawArea variablen (which is the MathCanvasobject, you have instantiated in your Mathematica Notebook):My_DisplayGraphicsViaJava`displayGraphics[obj, drawArea];obj being the String array (or string List in M_) that holds yourGraphics 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 leastcompile properly;Place the compiled class Ŝle in a directory on your CLASSPATH (consultJ/Link docu if you donıt know about CLASSPATH) and then try theMathematica 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 mycode.murphee====I am trying to write an animation using JLink.....basically asfollows...(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 thetime value to make a graphics plot......unfortunately, this routine drawsthe next time plot very slowly, plus I also notice that without the Pause[]statement, Mathematica only draws the graph for the Ŝnal time value...Following an example in the JLink documentation, I have written thefollowing java routine....which I saved in the same dir as MathFrame,etc....public class My_DisplayGraphicsViaJava { public void displayGraphics(String cmds[]) { // declare String Arrayfor 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 thearray of Graphics plots created *)But needless to say this dont work....LoadJavaClass responds by saying Classnot Found.....so what should I do to correct this? Also , on the javaroutine, was i supposed to add: Extends MathFrame, etc....how will myjava routine know what drawArea.setMathCommand is, etc.....am I alsosupposed to compile my java routine? thanks....jerry blimbaum NSWC panama city, ŝ====Dear colleagues,Iım trying to plot the next exponential functionPlot[Exp[1/(Abs[x-1]-Abs[x-2])],Range]If the Range is positive there arenĞt problems. However if the Range isnegative Mathematica plots a strange beast...Have anyone found anything of this sort? I would apreciate to know how toresolve this problem.Juan Egea GarciaBullas - Murcia - Espa.96a====The function you are plotting is constant for negative x. You might wantto specify a plotrange, such as PlotRange->{0,2}, or Mathematica may tryto 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 whichmay have DASSL-routines that do whatI want. Has anybody suggestions on which of thesesystems is easy to interface with Mathematica?Is there a C++ library that contains such routines and can beinterfaced 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 circuitanalysis toolbox Analog Insydes? You can get a free evaluation versionof 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 whilstball B - starting from the same height - rolls down Cosh[t]ıs path from theright.x-axis is time t, y-axis is height h.Ball A is Ŝne; ball B - which should arrive at h=0 before A - is beyond mymeans.Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: 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 - PEand 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 Ŝne; 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 yetfamiliar with Lagrangian formalism. Itıs quite easy to derive a generalequation of motion for a point mass, subjected to gravity and to moving on acurve f = y(x) (i.e. f = Cosh[#]&).1) Iıll leave re-deriving equation to you, here is what Iıve got (just copypaste 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, applymy 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 aswell, thus speciŜng 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 fromthe| right.|| x-axis is time t, y-axis is height h.|| Ball A is Ŝne; ball B - which should arrive at h=0 before A - is beyondmy| 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ıdnoticed a mistake in my equation posted below, a factor Œ2ı in expressioninvolving xı[t]^2, should be Œ1ı.Since this forum is of an alt. type, Iıve published the whole notebook athttp://www2.arnes.si/~gljpoljane22/math/ FallingCurve3D.nbBye,Borutp.s. A ŒŜll-the-gapı riddle for those interested in physics lore. RichardFeynman once said:Science is like _ _ _, sometimes something useful comes out, but that isnot the reason why we are doing it.| ...| 1) Iıll leave re-deriving equation to you, here is what Iıve got (justcopy| 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 Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator====I have the following code and am trying to include a legend. The BarChartappears, but with no legend. I have followed the Œhelp Ŝlesı, but I thinkIım missing something.In my code, SortTime and SessTime are value pairs. Photog is a string arraycontaining 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 Ŝnd the element of the table that has the largest Ŝrst 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 ScienceTruman State University100 East Normal St.Kirksville, MO 63501http://vh216801.truman.edu660.785.7430========> Simplify:> 5nth sqrt (3)/sqrt (6)> 5nth Sqrt(3)> ------------> Sqrt(6)> 1st.. is this the correct notation for use on a computerNo. May be you mean3^(1/5)/Sqrt[6]??> 2nd.. how is the solution solved, step by step please.3^(1/5)/Sqrt[6] // FullSimplify JensReply-To: kuska@informatik.uni-leipzig.de====whats wrong withToExpression[#, StandardForm, Hold] & /@ Names[Global`*] /. Hold[a_] :> ByteCount[OwnValues[a]] Jens> I want to make a list of all symbols in the Global context, as in> Names[Global`*]> and compute a ByteCount for each symbolıs OwnValues -- without> evaluating the symbols.> It seems possible in principle, but I havenıt found a way.> Bobby TreatReply-To: kuska@informatik.uni-leipzig.de====Needs[Graphics`Arrow`]Plot [{Sin[x], Cos[x]}, {x, 0, 2Pi}, Epilog -> {{GrayLevel[0.9], Rectangle[{3.75, 0.25}, {5.2, 0.9}]}, Arrow[{4, 0.75}, {2, Sin[2]}], Text[Sin[x], {4, 0.75}, {-1, 0}], Arrow[{4, 0.5}, {2, Cos[2]}], Text[Cos[x], {4, 0.5}, {-1, 0}]}] Jens> Instead of using Legend in plots with multiple series is there a way> to have arrows with a text at the end identifying the different> series? The reason Iıd like this is that the legend is a bit Œbulkyı> looking and Iıd want something tidier.> I know there is an Arrow package but I think youıd need to manually> enter each start and end point of each arrow - is there a simple> command to do this?> Also - is there a way to adjust the legend font size? I.e. make it> small so that it doesnıt interfere with data series.> _> |> > > > > thankyou====>I have written the following in a JLink program:>drawArea=JavaNew[com.wolfram.jlink.MathCanvas];>> then I perform an analysis of some data with output of this form....>>plot = DisplayTogether[ListPlot[],ListPlot[].etc...];>Unfortunately, at this point I dont know how to associate Œplotı with>drawArea so that>>draw.Area@RepaintNow[]; repaints the math screen to show the plots Iıve>computed...>Iıve tried draw.Area@update[plot] and draw.Area@setImage[plot] but these>dont work........how to Ŝx?.........thanks.....Jerry,You use the MathCanvas.setMathCommand() method to specify the Mathematica command that is used to generate the image to display: drawArea.setMathCommand(plot);You will Ŝnd a very simple example of this in section 1.2.8.2 of the J/Link User Guide (in the Help Browser hierarchy, this is found at JLink/Part 1. Installable Java/Drawing and Displaying Images in Java Windows/Showing Graphics and Typeset Expressions).You do not need to use the repaintNow() method unless you are updating the image continuously in response to a user action, like dragging a slider.Todd GayleyWolfram Research====try:(((((3^(1/2))^(1/2))^(1/2))^(1/2))^(1/2))/(6^ (1/2))Out:1/(Sqrt[2]*3^(15/32))You can see what happened:1st: 6^(1/2) = 2^(1/2)*3^(1/2);2nd: subtraction of the 3ıs exponents (1/2)^5 - 1/2 = 1/32 - 16/32 = -15/32.MATHEMATICA does these straightforward simpliŜcations without you having toinvoke Simplify[].Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de-----UrsprÌ.b9ngliche Nachricht-----Gesendet: Freitag, 13. September 2002 07:14An: mathgroup@smc.vnet.netBetreff: nth rootsSimplify:5nth sqrt (3)/sqrt (6)5nth Sqrt(3)------------ Sqrt(6)1st.. is this the correct notation for use on a computer2nd.. how is the solution solved, step by step please.====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 seemsto be working Ŝne when I produce a document that is just Mathematica code.The problem - as expected - is that when I include the Mathematica code asa part of a larger document, there are (1) clashes with existing packages(2) some LaTeX elements, such as the equations, start to use theMathematica fonts too. My objective would be to typeset a document instandard LaTeX, where only the Mathematica code has the Mathematica feeling.Does anyone know of any style available that is completely seperated fromall other LaTeX deŜnitions?BestKyriakos_____+**+____+**+___+**+__+**+_ Kyriakos ChourdakisLecturer in Financial EconomicsURL: http://www.qmw.ac.uk/~te9001tel: (++44) (+20) 7882 5086Dept of EconomicsUniversity of London, QMLondon E1 4NSU.K.====What about this problem? I have tried the previous suggestions but none ofthem worked. Will Wolfram help us in this problem?====Have you tried deleting ... Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nbThere are two BrowserIndex Ŝles. Only delete the .nb one (or just move itsomewhere else).> What about this problem? I have tried the previous suggestions but none of> them worked. Will Wolfram help us in this problem?>>>====Daniel Lichtblau made two suggestions that allow one to useInterpolation the way I wanted. First, to make the resulting functionright-continuous, change the sign twice. Second, to make the end pointreturn the correct value, add an extra (phantom) observation (with anextra (irrelevant) value). (The phantom observation is made at thehigh end because of the sign reversals.) Hereıs the code I cooked upbased on his suggestions:MakeEmpiricalCDF::usage = MakeEmpiricalCDF[list] returns a functionthat evaluates the empirical CDF given the observations in the list.The function is deŜned on the entire real line.MakeEmpiricalCDF[list_?(VectorQ[#, NumericQ]&)] := Module[{n, s, a, r, idata}, n = Length[list]; s = Sort[list]; a = Append[s, s[[-1]] + 1]; (* phantom obs. *) r = Range[1/n, 1 + 1/n, 1/n]; (* phantom value 1 + 1/n *) idata = Last /@ Split[Transpose[{-a, r}], #1[[1]] == #2[[1]]&]; (* -a is the Ŝrst sign change *) Block[{x}, Function @@ {x, Which @@ { x < s[[ 1]], 0., x > s[[-1]], 1., True, Interpolation[idata, InterpolationOrder -> 0][-x] (* -x is the second sign change *) }}] ]The construction Last /@ Split[ ... ] accounts for duplicate values.Here are two examples. Needs[Statistics`ContinuousDistributions`]list1 = RandomArray[NormalDistribution[0, 1], 100];f1 = MakeEmpiricalCDF[list1];Plot[f1[x], {x, -4, 4}]list2 = Table[Random[Integer, {1, 10}], {10}];f2 = MakeEmpiricalCDF[list2];Plot[f2[x], {x, 0, 11}]--Mark> Iım trying to write a fast empirical cummulative distribution function> (CDF). Empirical CDFs are step functions that can be expressed in> terms of a Which statement. For example, given the list of> observations {1, 2, 3},> f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&> is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}> and f is continuous from the right.> When the number of observations is large, the Which statement> evaluates fairly slowly (even if it has been Compiled). Since> InterpolationFunction evaluates so much faster in general, Iıve tried> to use Interpolation with InterpolationOrder -> 0. The problem is that> the resulting InterpolatingFunction doesnıt behave the way (I think)> it ought to. For example, let> g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->> 0]> Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.> In addition, g is continuous from the left rather than from the right.> Obviously I am not aware of the considerations that went into> determining the behavior of InterpolationFunction when> InterpolationOrder -> 0.> So I have two questions: > (1) Does anyone have any opinions about how InterpolatingFunction> ought to behave with InterpolationOrder -> 0?> (2) Does anyone have a faster way to evaluate an empirical CDF than a> compiled Which function?> By the way, hereıs my current version:> CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]> --Mark====>> do you realy think that>> 1.07577/( 1+7.12336*10^-7 (1. + z)^2 )>> with the z inside is numerical ? or do you mean>> F[z_?NumericQ]: = NIntegrate[f[y,z], {y, 0, InŜnity}]>Iım a newbie, bat I mean:*************************In[1]= NumericQ[z]Out[1]=False*************************BTW, z is a real number.--Rob_jack====First a thank you to all those who pointed out to me (and othersapparently) about the various ways to input the symbolic form of Floor.On a larger note, it surprises me that no one has yet published a book onhow to use Mathematica to write a technical document. The number of questionsthat appear on this board concerning the details of how to do itsuggests the need for such documentation. Iım speculating when I say thatmany users give up in frustration and go back to (or learn) Latex. Atleast there are bookcases full of learning Latex. I myself have 5!I donıt mean this to sound like a rant, but using Mathematica to publish adocument is, for most of us, not worth the effort.Jack====I often run into this difŜculty: when designing a program, say as amodule, and testing it for various inputs, I get wrong answers. What todo? 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 beimporved. (Oh yes, I abandoned Trace a long time ago!)myFunction[f_] := Module[ {L1,L2,L3},L1 = ... ;L2 = ... ;l3 = ... ; Ŝnal step ]To see what went wrong, I use (* *) selectively as follows:Stage 1myFunction[f_] := Module[ {L1,L2,L3},L1 = ... (*;L2 = ... ;L3 = ... ; Ŝnal step *) ]Thus I see if L1 worked as expected. The next step is to put (* after L2and see if this works. I continue this til the bitter end and I usuallyŜnd my errors.My question; The process of moving (* *) step by step through theprogram is quite tedious when the code has lots more lines. What I wouldlike is a meta-program which (like FoldList) does this job for me. Theoutput of this meta-program is the list of outputs of each line in themodule, probably best printed as a column.This sounds like Trace but my problem with Trace is it is terriblydifŜcult to read. For the not-so-subtle programming I do, the only thingI need is what expression is returned line by line.Any advice? All remarks are appreciated!Jack====JM,You are certainly correct in wanting to make a tidier plot! Legends areoften poor because they actually distract from the message of the data.However, the best solution will depend on the particular nature of yourdata. If there are not too many curves you could perhaps put Text labelsright on top of each curve. If there are many curves, or some of them areclose together, use arrows for some of them. If you have a really largenumber of curves, then maybe a different approach is needed.It is probably not possible to make a useful general routine for labeledarrows because the best placement would depend upon the particular nature ofthe graph. So, to make a nice graphic you will have to do some hand work,specifying each Arrow and Text label. You can actually click the coordinatesoff the graph to put into the Arrow and Text statements.If you want to actually show me your plot, I could try to make somesuggestions.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ _ | thankyou====>I am interested in creating a slide presentation using slide view>mode in Mathematica 4.2. I would like to have hyperlinks between>different slides ( e.g., a hyperlink in say slide 6 takes me back to>slide 3).>>I have no difŜculty in creating such a hyperlink (using tags) when I>am in the author mode. But the hyperlink does not work when a revert>back to slide view mode.>>I guess it has somthing to do with the fact that in author view mode>your slides are a subset of a single notebook but in slide view mode>each slide becomes a distinct notebook.>>So my question: Is there a way to reference the individual slides>using the hyperlink command?>BrianIf you set PagewiseScrolling->True, then your hyperlink will work. Go to the Option Inspector and set the scope to Notebook. Then go to the optionNotebookOptions|Window Properties|ScrollingOptions|PagewiseScrollingAnd set it to True. The disadvantage to this setting is that you can now only have one screenıs worth of contents per slide. (But then it is a slide show after all, so maybe thatıs not so bad.)-Dale====Does anybody know how to calculate in Mathematica:a)empirical CDF,b)empirical PDF,c)normal QQ-plot;d)QQ-plot two different random samples?!Swidrygiello.====DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to preventthe loading of a large Ŝle in routine cases. However, when ThisPackage`deŜnes its functions, inside the Private` area, it includes a conditionalcall to BigVariable. It turns out that OtherPackage is loaded when thatfunction is deŜned. I was wondering if there is a way to avoid this.Roughly speaking, here is the setting:BeginPackage[ OtherPackage` ]BigVariable::usage=exampleBegin[Private`]BigVariable=Table[x y,{x,1000},{y,1000}]End[ ]EndPackage[ ]BeginPackage[ ThisPackage` ]function::usage=exampleBegin[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 withx>1000 but it loads when function is deŜned. Any ideas?Nicholas====Could you send a sample example of your Ŝle -- just a few records.Tomas GarzaMexico City----- Original Message -----> This appears to pull in a line. Now I want to take characters 25 to 110 toget just the stuff I want:> y1=StringTake[y ,{25,110}];>> Hereıs the output. StringTake doesnıt seem to work.>321. 317. 367. -115. 126. 146. -410. -426.000000EF 75.},{25, 110}]>> It doesnıt take loading another package as far> as I can tell from the help. Iım thinking that it doesnıt work becauseitıs trying to work on a list> rather than a string. Iıve tried Flatten, and other stuff to try to get tojust a string and not a list but> nothing has worked so far. Iım a long way from getting to those numbersin there but heck, I> canıt even get to the string. Can anyone point me in the right direction?>>====> you mean the inverse of TeXForm[] ?> For what ? A TeXpert && Mathematica guru && MathLink expert> has a TeX frontend, that translate a TeXNotebook> (that is a TeX Ŝle with some Mathematica Input/Output > environments) and send the input cells to a kernel> and insert the output into the Ŝnal TeX Ŝle ...Congratulations to you if you can do that and if youıre happy with it. Iıd prefer life to be a bit simpler. The point is that many users of Mathematica already have sufŜcient knowledge of TeX/LaTeX to typeset very complicated mathematics and get excellent results with little or no grief. To achieve even close to the same quality with Mathematica alone can require ten times the effort and a hundred times the grief.---Selwyn> The most of the remaining work like creating hyperlinks> to references and Ŝgures is done my LaTeX and pdfLaTeX,> with help of CTAN and some macros one generate almost every> layout *and* I have more than 20 books about TeX/LaTeX > (including Don Knuths excelent manuals) but I have not> a single book about the Mathematica Frontend.> The way is not to teach TeX to the frontend, the way is> to teach TeX a bit Mathematica.> And a TeXpert will never switch from his beloved TeX> to the Frontend and itıs typesetting -- thatıs why> he is a TeXpert.> Jens>>Recent threads about word processing and typesetting have got me>>dreaming again...>>Wouldnıt it be nice if someone developed a package that provided a>>function like this:>> DisplayTeX[ some TeX code ]>>which would cause the kernel to generate PostScript for the typeset>>text, to be displayed by the front end?>>I doubt that WRI will ever consider this, but surely thereıs someone out>>there whoıs both a TeXpert and a Mathematica guru who can do it. No>>doubt thereıs money to be made.>>Probably just a pipe dream...>>--->>Selwyn Hollis> ====> 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.> -1281.9 -229. 321. 317. 367. -115. 126. > 146. -410. -426.000000EF 75.}, {25, 110}]> 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?You might try lst = Read[StringToStream[y1], {Word, Table[Number, {16}], Word,Number}]//Flatten;You can then pick the numbers (or words) from the list lst.A quicker alternative might be as follows:-iŜle = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}];Dave.========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au======================================= ========First of all, I used ReadList directly, with Word instead of String, andwith the option WordSeparators -> None, like this (I presume your Ŝle isadequately located, so that there is no problem in Ŝnding it):In[1]:=a = ReadList[197-tst.txt, Word, RecordLists -> True, WordSeparators ->None];This allowed me to examine your records and I found out that in this wayeach record comes out as a list of length 1: In[2]:=Head[a[[1]]]Out[2]=ListIn[3]:=Length[a[[1]]]Out[3]= 1That is,In[3]:=a[[1]]Out[3]=317. 367. -115. 126. 146. -410. -426.000000EF 75.}In[4]:=StringLength[a[[1,1]]]Out[4]=140and the characters you want areIn[5]:=StringTake[a[[1,1]], {25, 110}]Out[5]=5935.80 5946.66 27.06 -1281.9 -229. 321. 317. 367. -115. 126. 146.So far, so good. It seems that you want these 11 numbers, OK? The problemnow, I think, is that this is just a string and I can think of no easy wayto convert it precisely into a list of 11 real numbers. Then, I suggest youread the Ŝle in a different way, without the WordSeparators option:In[6]:=b=ReadList[197-tst.txt,Word,RecordLists -> True];In[7]:=b[[1]]Out[7]=115.,126.,146.,-410.,-426.000000EF, 75.}In[8]:=Head[b[[1]]]Out[8]=ListIn[9]:=Length[b[[1]]]Out[9] =19so that each record is now a list of 19 strings. What you want is strings 6to 16, but converted to reals (unless Iım being presumptuous). This willachieve that:In[10]:=ToExpression[Take[b[[1]],{6,16}]]Out[10]={ 5935.8,5946.66,27.06,-1281.9,-229.,321.,317.,367.,-115.,126., 146.} Now you have a nice list of real numbers to work with. You can do this forthe whole Ŝle like this:In[11]:=ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem.Tomas GarzaMexico City> ----- Original Message -----> Sent: Friday, September 13, 2002 12:14 AM>> Iıve got to extract some numbers from a Ŝle that are in lines of text.> Since the line contents are not numbers, I presume I must pull the lineout> 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 110to> get just the stuff I want:> y1=StringTake[y ,{25,110}];>> Hereıs the output. StringTake doesnıt seem to work.>-229.> 321. 317. 367. -115. 126. 146. -410. -426.000000EF 75.},> {25, 110}]>> 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 getto> 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 rightdirection?>>-------------------------------------------- ------------------------====> BRIEF> Mathematica seems to support 3 levels of nesting:> section, subsection, and subsubsection.> Q: how can I obtain more levels of nesting?> I typically go 6-7 levels deep.Well, I started by editting the notebook in a text editor(having used Edit Style Sheet to unshare),and I created stylesSub3section ... Sub9section,with Dewey decimal numbering 1.2.3.4.5.6.7.8.9.10I got collapsable group working, by mucking with CellGroupingRules->{SectionGrouping, 100},changing the number.I am not sure what the number is, but Iım guessingit may be a pixel count for the nesting boxesat the left of the screen.Iım a bit worried about whether this is fragile.===Was there any way to accomplish this from the GUI?Or was using a text editor mandatory?===Related: this exercise makes it obvious that acommon operation is to push down or pull upa whole subtree - e.g. a Subsection becomes aSubsubsection, a Subsubsection becomes aSub3section, etc. The sort of thing that MicrosoftWord does with Outline mode.Q: has anyone got something like Outline modefor Mathematica?Iım tempted to go the other way, and ask if anyonehas a front end that allows Mathematica to be embeddedin Word documents. But that might be a hassle,since Word runs on Windows, and the Mathematicalicence I have access to runs on Suns.====> 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.> -1281.9 -229. 321. 317. 367. -115. 126. > 146. -410. -426.000000EF 75.}, {25, 110}]> 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?You might try lst = Read[StringToStream[y1], {Word, Table[Number, {16}], Word,Number}]//Flatten;You can then pick the numbers (or words) from the list lst.A quicker alternative might be as follows:-iŜle = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}];Dave.========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au======================================= ========I was and do have problems reading Ŝles Exported Ŝles in AdobeIllustrator format (.ai) from Adobe Illustrator 10.0.3.With an upgrade to Adobe Illustrator 10.0.3, I can read EPS Ŝlescreated by Mathematica 4.0.1.A message from tech support at Wolfram implies that Adobe Illustratorformat Ŝles can be read ONLY if you are using the correct Adobe andWolfram programs. Additionally, Mathematica is going to favor the exportof EPS Ŝles (is that clear enough?).My approach to using Mathematica as a source of images for AdobeIllustrator 10.0.3 is:Create the image in MathematicaExport[ImageFileName.eps, theMathematicaImageCreated, EPS]Open the Ŝle ImageFileName.eps within Adobe Illustrator 10.0.3Save the Ŝle as a .ai ŜleBe sure to check the ImageSize as it is not often what you toldMathematica.====I ran it 10 times on 4.2 with no crashes.> Jens-Peer Kuska tells me that he gets no crash with Mathematica 4.2,however after working> with this program for more than a month, trying every possible permutationand> manipulation, and having it still crash, I am still worried that upgradingto 4.2> wonıt solve my problem. Can anyone else with 4.2 try running this programfor me a> good number of times, say 3 or 4, and see if they get similar goodresults?> Bernard Gress>> Dear Group,>> I have a program to take the local polynomial non parametric regression> of two variables. It uses Compile, unfortunately, and regularly, but> inconsistently, causes Mathematica to crash (in Win2K, with I forget> what error, and in Win98/Mathematica4.0 with an invalid memory access from> MathDLL.dll). I am running Mathematica 4.1, and have this problemconsistently> on 4 different machines.>> Here is the code, if it doesnıt crash the Ŝrst time, it will the second> or third:>> (*> w = Compile[{{xj, _Real, 0}, {XX, _Real, 1}, {YY, _Real, 1}, {h, _Real,> 0},> {nn, _Integer, 0}, {ord, _Integer, 0}},> First[Inverse[Sum[Outer[Times, Table[If[Positive[q], (XX[[i]] - xj)^q,> 1], {q, 0, ord}],> Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0,> ord}]*E^(-0.5*((XX[[i]] - xj)/h)^2)], {i, nn}]] .> Sum[(Table[If[Positive[q], (XX[[i]] - xj)^q, 1.], {q, 0, ord}]*YY[[i]])*> E^(-0.5*((XX[[i]] - xj)/h)^2), {i, nn}]]];> *)>> (*> !(tt = MemoryInUse[];> ListPlot[Table[{((i + 1))^2, (Timing[> nn = ((i + 1))^2; [Epsilon] = Table[Random[]*3, {i,> nn}];> testX = Table[i* .3 - Random[]*2, {i, nn}];> testY = Table[Sin[i/3] - 2, {i, nn}] + [Epsilon];> Map[w[#, testX, testY, .1 + Random[], nn, 0] &,> testX];])[([1])]/Second}, {i, 15}], PlotJoined ->> True,> PlotLabel -> ];> MemoryInUse[] - tt)> *)>====In his not-so-subtle way, Jens-Peer is trying to tell you that since yousee z in the error message, thatıs what NIntegrate saw too. z is asymbol, and NIntegrate needs numbers. Now Iıll have to search onlinefor your original problem, since I deleted my copy long ago... (Excuseme a few minutes...) Hmm... OK, Iım back.Well... thereıs still a missing (or extra) parenthesis in the deŜnitionof f and a missing bracket in the deŜnition of F, but I also canıt seethat youıve given z a numerical value. The error shouldnıt occur untilyou use F though, since you used SetDelayed. So, the error message goeswith a line you didnıt include in your post. However, in your latestpost, the linesNumericQ[z]Falsetell me z is NOT a real number. For instance,NumericQ[1.2]TrueSo, proceeding with the theory that z needs to be numeric, letıs tryF[1.2]NIntegrate::itraw:Raw object 1.2` cannot be used as an iterator.NIntegrate[f[y, 1.2], {1.2, 0, InŜnity}]NIntegrate::itraw:Raw object !(1.2`) cannot be used as aniterator.As you see, in the deŜnition of F, youıve used z as an iterator. Nomatter what the argument z to F is -- number, symbol, whatever -- youcanıt use it as an iterator, because it already has an identity, anditerators are stand-ins -- temporary variables that donıt exist outside(in this case) NIntegrate. So, as Jens-Peer pointed out, y should havebeen your iterator. (Probably. We donıt actually know what you weretrying to do. We only know for sure that z couldnıt be the iterator.)So, if Iıve made the right guesses, the deŜnition for F should beF[z_] := NIntegrate[f[y, z], {y, 0, InŜnity}]But... F[z] will still give you an error if z doesnıt have a numericalvalue, so itıs even better to deŜne F this way:ClearAll[F]F[z_?NumericQ] := NIntegrate[f[y, z], {y, 0, InŜnity}]That way, F[z] is left unevaluated if z isnıt numeric.I canıt go any further, since I donıt know the value of f -- because Idonıt know where to add or subtract that pesky parenthesis. (I askedstill isnıt.)Bobby Treat-----Original Message-----> F[z_?NumericQ]: = NIntegrate[f[y,z], {y, 0, InŜnity}]>Iım a newbie, bat I mean:*************************In[1]= NumericQ[z]Out[1]=False*************************BTW, z is a real number.--Rob_jack====Iım learning the Ŝne art of patterns and Hold one tricky example at atime.Bobby-----Original Message-----> I want to make a list of all symbols in the Global context, as in> Names[Global`*]> and compute a ByteCount for each symbolıs OwnValues -- without> evaluating the symbols.> It seems possible in principle, but I havenıt found a way.> Bobby Treat====Hereıs the fairly useful bit of code I came up with, using Jens-Peerısbrilliant solution:names = Names[Global`*];counts = ToExpression[#, StandardForm, Hold] & /@ names /. Hold[a_] :> ByteCount[OwnValues[a]];Select[Transpose[{names, counts}], Last@# > 16 &] // TableFormIt tells me how some of my memory is being spent.Bobby Treat-----Original Message-----> I want to make a list of all symbols in the Global context, as in> Names[Global`*]> and compute a ByteCount for each symbolıs OwnValues -- without> evaluating the symbols.> It seems possible in principle, but I havenıt found a way.> Bobby Treat====>Try deleting ...>Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nb >====Jack,Often, what I do when developing a slightly complicated module is to Ŝrsttest it after I add each statement L1, L2, etc. But then often I want tomake changes after I have all the statements in. Then to debug I just addtemporary Print statements. For example...myFunction[f_] := Module[ {L1,L2,L3},L1 = ... ;L2 = ... ;Print[{L1, L2}];l3 = ... ;]Sometimes I use multiple Print statements. The only problem with thisapproach is that sometimes the difŜculty might be in a subexpression of alonger expression.This forces me to temporarily break out the longer expression into multiplestatements, or perhaps duplicate the subexpression in the Print statement.But I Ŝnd that the easiest method to track down errors.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/l3 = ... ; Ŝnal step ]To see what went wrong, I use (* *) selectively as follows:Stage 1myFunction[f_] := Module[ {L1,L2,L3},L1 = ... (*;L2 = ... ;L3 = ... ; Ŝnal step *) ]Thus I see if L1 worked as expected. The next step is to put (* after L2and see if this works. I continue this til the bitter end and I usuallyŜnd my errors.My question; The process of moving (* *) step by step through theprogram is quite tedious when the code has lots more lines. What I wouldlike is a meta-program which (like FoldList) does this job for me. Theoutput of this meta-program is the list of outputs of each line in themodule, probably best printed as a column.This sounds like Trace but my problem with Trace is it is terriblydifŜcult to read. For the not-so-subtle programming I do, the only thingI need is what expression is returned line by line.Any advice? All remarks are appreciated!Jack====The following code is my attempt to provide the functionality yourequested. It does some rudimentary error checking, but I havenıttried very hard to fool it. The code manipulates the DownValues,locating the highest CompoundExpression (see the lines in whichpos is deŜned), keeping only those expressions speciŜed.DownValues are restored after the expression is evaluated. The trickypart is keeping the CompoundExpression from evaluating while it isbeing manipulated. (See the lines in which held and new aredeŜned.) Iım not sure Iım doing this part the most elegant way, butit seems to work.(* code starts here *)PartialEvaluation::usage = PartialEvaluation[f[args], n] returnsf[args] where only the Ŝrst n expressions are evaluated in themainCompoundExpression in DownValues[f]. For example:ntClear[f]ntf[x_] := Module[{a,b}, a=3; b=4; a b x]ntPartialEvaluation[f, 2]n returns 4.PartialEvaluation::dvprob = DownValues[``] is either empty or hasmorethan one element.PartialEvaluation::toobig = There are only `1` expressions inthe CompoundExpression in `2`.PartialEvaluation::noce = There are no CompoundExpressions inDownValues[``].SetAttributes[PartialEvaluation, HoldFirst]PartialEvaluation[f_[args__], n_Integer] := Module[{dv, pos, held, new, eval}, Catch[ dv = DownValues[f]; If[Length[dv] != 1, Message[PartialEvaluation::dvprob, f]; Throw[HoldForm[f[args]]]]; pos = Sort[Position[dv, CompoundExpression]]; If[pos == {}, Message[PartialEvaluation::noce, f]; Throw[HoldForm[f[args]]]]; pos = Drop[First @ pos, -1]; held = Extract[dv, pos, Hold] /. CompoundExpression -> Sequence; If[Abs[n] > Length[held], Message[PartialEvaluation::toobig, Length[held], HoldForm[f[args]]]; Throw[HoldForm[f[args]]]]; new = ReplacePart[dv, Take[held, n] /. Hold[x__] :> Hold[CompoundExpression[x]], pos, 1]; DownValues[f] = new; eval = f[args]; DownValues[f] = dv; eval ]](* code ends here *)--Mark.P.S. The version of this message I posted directly from my newsreaderdidnıt show up, so Iım reposting (a slightly improved version) fromGoogle.> Jack,> Often, what I do when developing a slightly complicated module is to Ŝrst> test it after I add each statement L1, L2, etc. But then often I want to> make changes after I have all the statements in. Then to debug I just add> temporary Print statements. For example...> myFunction[f_] := Module[ {L1,L2,L3},> L1 = ... ;> L2 = ... ;> Print[{L1, L2}];> l3 = ... ;> ]> Sometimes I use multiple Print statements. The only problem with this> approach is that sometimes the difŜculty might be in a subexpression of a> longer expression.> This forces me to temporarily break out the longer expression into multiple> statements, or perhaps duplicate the subexpression in the Print statement.> But I Ŝnd that the easiest method to track down errors.> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> I often run into this difŜculty: 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 = ... ;> Ŝnal step> ]> To see what went wrong, I use (* *) selectively as follows:> Stage 1> myFunction[f_] := Module[ {L1,L2,L3},> L1 = ... (*;> L2 = ... ;> L3 = ... ;> Ŝnal 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> Ŝnd 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> difŜcult 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====Mathematica often produces complex resluts. But the problem is not complex:TrySolve[FR == Pi r1^2 - Pi r2^2, r1]It is simple to eliminate it in this case. Just square it.Does someone give me a hint, how to write ra rule for simplify, lik Ted Ersek did inhttp://www.verbeia.com/mathematica/tips/Links/Tricks_lnk_41 .htmlI thin, one has to to replace the patterni Sqrt[-a_]bySqrt[(i Sqrt[-a_])^2]and then one has to simplify it?Peter Klamser====There has been an interesting discussion about using InterpolatingFunctionfor an empirical CDF.If one is willing to sacriŜce some theoretical soundness, an empirical CDFmay be computed in a simpliŜed form:simpleEmpiricalCDF[distr_/;VectorQ[distr,NumberQ]] :=With[{nonu=Sort[distr], u=Union[distr]},Transpose[{u,FoldList[Plus,0,(Count[nonu,#]&/ @u)/Length[nonu]]//Rest}]]This code does not return a function, and the result needs someinterpretation. Nevertheless, it may be of some use.data = {0.59, 0.72, 0.47, 0.43, 0.31, 0.56, 0.22, 0.9, 0.96, 0.78, 0.66,0.18, 0.73, 0.43, 0.58, 0.11}(the tie [0.43] will be accounted for in a way that is consistent with sometextbooks)simpleEmpiricalCDF[data]//N returns{{0.11,0.0625},{0.18,0.125},{0.22,0.1875},{0.31,0.25}, {0.43,0.375},{0.47,0.4375},{0.56,0.5},{0.58,0.5625},{ 0.59,0.625},{0.66,0.6875},{0.72,0.75},{0.73,0..8125},{ 0.78,0.875},{0.9,0.9375},{0.96,1.}}A plot may be given with:simpleEmpiricalCDFPlot[distr_/;VectorQ[distr,NumberQ]] :=Module[{res,x,p},res=simpleEmpiricalCDF[distr];x=({#,#}& /@ Transpose[res][[1]])//Flatten;p=({#,#}& /@ Transpose[res][[2]])//Flatten;p= Join[{0},Drop[p,-2],{1}];ListPlot[Transpose[{x,p}],c]]Again, this plot does not reŝect theoretical considerations at the lowerand upper end.With regardHermann Meier====Caution: where right- and left-continuity are concerned, Danielısrelying on undocumented behavior that may change in the next version.Bobby-----Original Message-----that evaluates the empirical CDF given the observations in the list.The function is deŜned on the entire real line.MakeEmpiricalCDF[list_?(VectorQ[#, NumericQ]&)] := Module[{n, s, a, r, idata}, n = Length[list]; s = Sort[list]; a = Append[s, s[[-1]] + 1]; (* phantom obs. *) r = Range[1/n, 1 + 1/n, 1/n]; (* phantom value 1 + 1/n *) idata = Last /@ Split[Transpose[{-a, r}], #1[[1]] == #2[[1]]&]; (* -a is the Ŝrst sign change *) Block[{x}, Function @@ {x, Which @@ { x < s[[ 1]], 0., x > s[[-1]], 1., True, Interpolation[idata, InterpolationOrder -> 0][-x] (* -x is the second sign change *) }}] ]The construction Last /@ Split[ ... ] accounts for duplicate values.Here are two examples. Needs[Statistics`ContinuousDistributions`]list1 = RandomArray[NormalDistribution[0, 1], 100];f1 = MakeEmpiricalCDF[list1];Plot[f1[x], {x, -4, 4}]list2 = Table[Random[Integer, {1, 10}], {10}];f2 = MakeEmpiricalCDF[list2];Plot[f2[x], {x, 0, 11}]--Mark> Iım trying to write a fast empirical cummulative distribution function> (CDF). Empirical CDFs are step functions that can be expressed in> terms of a Which statement. For example, given the list of> observations {1, 2, 3},> f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]&> is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1}> and f is continuous from the right.> When the number of observations is large, the Which statement> evaluates fairly slowly (even if it has been Compiled). Since> InterpolationFunction evaluates so much faster in general, Iıve tried> to use Interpolation with InterpolationOrder -> 0. The problem is that> the resulting InterpolatingFunction doesnıt behave the way (I think)> it ought to. For example, let> g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder ->> 0]> Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}.> In addition, g is continuous from the left rather than from the right.> Obviously I am not aware of the considerations that went into> determining the behavior of InterpolationFunction when> InterpolationOrder -> 0.> So I have two questions: > (1) Does anyone have any opinions about how InterpolatingFunction> ought to behave with InterpolationOrder -> 0?> (2) Does anyone have a faster way to evaluate an empirical CDF than a> compiled Which function?> By the way, hereıs my current version:> CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] :=> Block[{x}, Compile[{{x, _Real}}, Evaluate[> Which @@ Flatten[> Append[> Transpose[{> Thread[x < Sort[list]],> Range[0, 1 - 1/#, 1/#] & @ Length[list]> }],> {True, 1}]]> ]]]> --Mark====Hey,How can I duplicate those nifty ŒMoreı hyperlinks in my usagestatements? That is the hyperlinks that appears at the end of text thatis generated after invoking a Œ?ı to get more information about a function.Lawrence====>Iıve got to extract some numbers from a Ŝle 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.ReadList returns a List not a String. So, y is a List and StringTake fails since it expects a String.Also, you do not need the options RecordLists->True when reading Strings. Nor do you need the OpenRead/Close statements with ReadListTryy = First[readList[197-tst.txt,String,1];y1 = StringTake[y, {25,110}];====>Does anybody know how to calculate in Mathematica: >a)empirical CDF,>b)empirical PDF, >c)normal QQ-plot; >d)QQ-plot two different random samples?!Yes, but there are a number of issues particularly with an empirical PDF. A 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 signiŜcant effect for large data sets.====> I am trying to implement a very simple sorted tree to quickly store some> real numbers I need. I have written an add, delete, minimum, and pop> (delete the lowest value) function and they seem to work ok but are very> slow. Letıs just look @ my implementation of the add part:> nums=Null;(*my initial blank Tree)> In[326]:=> Clear[add]> In[327]:=> add[Null,x_Real]:=node[x,Null,Null]> add[Null,node[x_Real,lower_,higher_]]=node[x,lower,higher]> In[328]:=> add[node[x_Real,lower_,higher_],y_Real]:=> If[x>y,node[x,add[lower,y],higher],node[x,lower,add[higher,y] ]]> In[288]:=> add[node[x_Real,lowerx_,higherx_],node[y_Real,lowery_,highery _]]:=If[x>y,> node[x,add[lowerx,node[y,lowery,highery]],higherx],> node[x,lowerx,add[higherx,node[y,lowery,highery]]]> ]> Now this is my attempt to test how fast my add works:> SeedRandom[5];> Do[nums=add[nums,Random[]],{5000}];//Timing> Out[333]=> {13.279 Second,Null}> running on an 1.4GHz Athlon with 1GB of ram).> Questions:> 1. Is this as fast as I can get my code to run?> 2. Am I doing something obviously stupid?> 3. would Compiling things help?> HusainIıll respond to your third question Ŝrst. No, use of Compile will nothelp. You do not have a tensor structure and moreover it will copy itsarguments. Hence invoking it within a loop would be quite slow for aproblem where the argument grows in size.One thing you did not check is the actual run-time complexity of yourcode. On my 15.GHz machine I get:In[6]:= SeedRandom[5];In[7]:= ee = Table[Random[], {10000}];In[8]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,1000}];]Out[8]= {0.34 Second, Null}In[9]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,2000}];]Out[9]= {1.28 Second, Null}In[10]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,4000}];]Out[10]= {4.94 Second, Null}In[11]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,8000}];]Out[11]= {25.08 Second, Null}We see this is clearly of no better than quadratic complexity, whereas Iwould guess you were expecting O(n*Log[n]). So this indicates a problem.Offhand I do not know what aspect of your code is responsible, but Iıllgive some different code that has the desired complexity.Note that some of this, and code very similar to that below, isdiscussed at:http://library.wolfram.com/conferences/devconf99/lichtblau /in the section entitled Trees.There is a corresponding Mathematica notebook available at:http://library.wolfram.com/conferences/devconf99/near the bottom of the web page.The code I used to implement a tree structure similar to yours is below.One difference is that, as I place node values in the center, when theyare ŝattened the tree is automatically sorted. You might (or might not)regard this as an added beneŜt.leftsubtree[node[left_, _, _]] := leftrightsubtree[node[_, _, right_]] := rightnodevalue[node[_, val_, _]] := valemptyTree = node[];Clear[treeInsert]treeInsert[emptyTree, elem_] := node[emptyTree, elem, emptyTree]treeInsert[tree_, elem_] /; OrderedQ[{nodevalue[tree], elem}] := node[leftsubtree[tree], nodevalue[tree], treeInsert[rightsubtree[tree], elem]]treeInsert[tree_, elem_] := node[treeInsert[leftsubtree[tree],elem], nodevalue[tree], rightsubtree[tree]]Now for some tests.In[40]:= tt1k = First[Timing[ff1k = node[]; Do[ff1k = treeInsert[ff1k, ee[[j]]], {j,1000}];]] Out[40]= 0.15 SecondWe will check that the ŝattened version is actually sorted.In[41]:= gg1k = Apply[List,Flatten[ff1k]];In[42]:= gg1k === Sort[Take[ee,1000]]Out[42]= TrueAlso we will observe that the maximum depth is reasonable.In[43]:= Depth[ff1k]Out[43]= 23In the perfectly balanced case it would be 10 so this is not too bad.For larger examples Iıll just show timings.In[44]:= tt2k = First[Timing[ff2k = node[]; Do[ff2k = treeInsert[ff2k, ee[[j]]], {j,2000}];]]Out[44]= 0.32 SecondIn[45]:= tt4k = First[Timing[ff4k = node[]; Do[ff4k = treeInsert[ff4k, ee[[j]]], {j,4000}];]]Out[45]= 0.73 SecondIn[47]:= tt8k = First[Timing[ff8k = node[]; Do[ff8k = treeInsert[ff8k, ee[[j]]], {j,8000}];]]Out[47]= 1.58 SecondIn[53]:= SeedRandom[5]; ee = Table[Random[], {32000}];In[54]:= tt32k = First[Timing[ff32k = node[]; Do[ff32k = treeInsert[ff32k, ee[[j]]], {j,32000}];]]Out[54]= 7.58 SecondThis is not of blinding speed but it has the advantage of exhibiting theappropriate run-time complexity. One can, with careful coding, cut downon tree size but if you check with LeafCount you will Ŝnd that theversion above is already not too wasteful (3x larger than #valuesstored). Moreover the code needed would run a bit slower as it wouldhave more cases to check.As for removing nodes, I think you will need to use some form of heldattribute so as to avoid copying the entire tree when you alterelements.Daniel LichtblauWolfram Research====>>So far, so good. It seems that you want these 11 numbers, OK? Theproblemnow, I think, is that this is just a string and I can think of no easywayto convert it precisely into a list of 11 real numbers.You could try StringToStream followed by a Read from that stream.Bobby Treat-----Original Message-----None];This allowed me to examine your records and I found out that in this wayeach record comes out as a list of length 1: In[2]:=Head[a[[1]]]Out[2]=ListIn[3]:=Length[a[[1]]]Out[3]= 1That is,In[3]:=a[[1]]Out[3]=317. 367. -115. 126. 146. -410. -426.000000EF 75.}In[4]:=StringLength[a[[1,1]]]Out[4]=140and the characters you want areIn[5]:=StringTake[a[[1,1]], {25, 110}]Out[5]=5935.80 5946.66 27.06 -1281.9 -229. 321. 317. 367. -115.126. 146.So far, so good. It seems that you want these 11 numbers, OK? Theproblemnow, I think, is that this is just a string and I can think of no easywayto convert it precisely into a list of 11 real numbers. Then, I suggestyouread the Ŝle in a different way, without the WordSeparators option:In[6]:=b=ReadList[197-tst.txt,Word,RecordLists -> True];In[7]:=b[[1]]Out[7]=.,-115.,126.,146.,-410.,- 426.000000EF,75.}In[8]:=Head[b[[1]]]Out[8]=ListIn[9]:=Length[ b[[1]]]Out[9]=19so that each record is now a list of 19 strings. What you want isstrings 6to 16, but converted to reals (unless Iım being presumptuous). This willachieve that:In[10]:=ToExpression[Take[b[[1]],{6,16}]]Out[10]={ 5935.8,5946.66,27.06,-1281.9,-229.,321.,317.,367.,-115.,126., 146.} Now you have a nice list of real numbers to work with. You can do thisforthe whole Ŝle like this:In[11]:=ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem.Tomas GarzaMexico City> ----- Original Message -----> Sent: Friday, September 13, 2002 12:14 AMfrom a Ŝle...>> Iıve got to extract some numbers from a Ŝle that are in lines oftext.> Since the line contents are not numbers, I presume I must pull thelineout> 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 to110to> get just the stuff I want:> y1=StringTake[y ,{25,110}];>> Hereıs the output. StringTake doesnıt seem to work.>-229.> 321. 317. 367. -115. 126. 146. -410. -426.000000EF 75.},> {25, 110}]>> It doesnıt take loading another package as far> as I can tell from the help. Iım thinking that it doesnıt workbecause> itıs trying to work on a list> rather than a string. Iıve tried Flatten, and other stuff to try togetto> just a string and not a list but> nothing has worked so far. Iım a long way from getting to thosenumbers> in there but heck, I> canıt even get to the string. Can anyone point me in the rightdirection?>>-------------------------------------------- ------------------------====Evaluate ?Floor and then, with your cursor in the output cell from that,push Ctrl-Shift-E, and you should see something like:Information[Floor, LongForm -> False]Floor[x] gives the greatest integer less than or equal tox.*Button[More[Ellipsis], ButtonData :> Floor, Active -> True, ButtonStyle -> RefGuideLink]OK. Change ButtonData :> Floor to ButtonData :> Ceiling, and pushCtrl-Shift-E again. Push the More... button, and you should go toCeiling in the Help Browser, not Floor.Another method is to click Input>Create Button>RefLink and type inCeiling. You should get a button that takes you to Help for Ceiling.Push Ctrl-Shift-E in both cells and compare, and youıll see some cluesto your options. Clues are all you get in Mathematica, so get used toit!Bobby Treat-----Original Message-----====Since r1 and r2 only appear squared, you can do it this way:Simplify[Solve[FR == Pi*r1Sq - Pi*r2Sq, r1Sq]]{{r1Sq -> FR/Pi + r2Sq}}orSimplify[Solve[FR == Pi*r1Sq - Pi*r2^2, r1Sq]]{{r1Sq -> FR/Pi + r2^2}}Then r1 is the square root of r1Sq. In the complex plane, real numbershave two square roots, but we usually ignore that.Bobby Treat-----Original Message-----http://www.verbeia.com/mathematica/tips/Links/ Tricks_lnk_41.htmlI thin, one has to to replace the patterni Sqrt[-a_]bySqrt[(i Sqrt[-a_])^2]and then one has to simplify it?Peter Klamser====> 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.Beside the Print statements, sometimes I do the following. Put the functionto be tested in its own context and then empty the list of local symbols,e.g.,myfunction[stuff__] := Module [{}, expr1; expr2; ... ]so that all temporary variables deŜned within the function are now globalwithin the new context. Then I can examine the values of all these variablesafter execution of the function and can often Ŝnd the error. If the erroris caused by a complex expression of nested functions, then I unwind thecomplex expression, adding more temporary variables, until I see theproblem. Then I think twice before recomplexifying.The two advandages of a special context are (1) I donıt get the previouslylocal symbols mixed up with other symbols and (2) I can examine all of themand only them with TableForm[{#,ToExpression[#]}&/@Names[mynewcontext`*]]Once I do this, I often leave the new context in place. Mathematica seems tobe able to handle a large number of contexts efŜciently.Tom Burton====This code is almost identical to yours in principle, yet 30% faster:(compared with the code in your notebook, not the code in the postbelow)ClearAll[emptyTree, treeInsert];emptyTree = {};treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree}treeInsert[tree_, elem_] /; SameQ[tree[[2]], elem] := treetreeInsert[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 see one obvious advantage of your algorithm over Husainıs and myearlier code; though Iım not sure it explains its better behavior. Thatis, while my algorithm made pattern matching more burdensome, yoursvirtually eliminated it.Also, the biggest improvement Iıve seen comes simply from replacing Nullwith anything else in Husainıs code. Again, that seems to suggest thattime spent on pattern matching is the problem. All the algorithms doapproximately the same real work on the tree structure.I really like how Flatten changes your tree into a sorted list. Verynice!Bobby Treat-----Original Message-----> (delete the lowest value) function and they seem to work ok but arevery> slow. Letıs just look @ my implementation of the add part:> nums=Null;(*my initial blank Tree)> In[326]:=> Clear[add]> In[327]:=> add[Null,x_Real]:=node[x,Null,Null]> add[Null,node[x_Real,lower_,higher_]]=node[x,lower,higher]> In[328]:=> add[node[x_Real,lower_,higher_],y_Real]:=> If[x>y,node[x,add[lower,y],higher],node[x,lower,add[higher,y] ]]> In[288]:=>add[node[x_Real,lowerx_,higherx_],node[y_Real, lowery_,highery_]]:=If[x>y,> node[x,add[lowerx,node[y,lowery,highery]],higherx],> node[x,lowerx,add[higherx,node[y,lowery,highery]]]> ]> Now this is my attempt to test how fast my add works:> SeedRandom[5];> Do[nums=add[nums,Random[]],{5000}];//Timing> Out[333]=> {13.279 Second,Null}> RH7.3> running on an 1.4GHz Athlon with 1GB of ram).> Questions:> 1. Is this as fast as I can get my code to run?> 2. Am I doing something obviously stupid?> 3. would Compiling things help?> HusainIıll respond to your third question Ŝrst. No, use of Compile will nothelp. You do not have a tensor structure and moreover it will copy itsarguments. Hence invoking it within a loop would be quite slow for aproblem where the argument grows in size.One thing you did not check is the actual run-time complexity of yourcode. On my 15.GHz machine I get:In[6]:= SeedRandom[5];In[7]:= ee = Table[Random[], {10000}];In[8]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,1000}];]Out[8]= {0.34 Second, Null}In[9]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,2000}];]Out[9]= {1.28 Second, Null}In[10]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,4000}];]Out[10]= {4.94 Second, Null}In[11]:= nums = Null; Timing[Do[nums = add[nums,ee[[j]]],{j,8000}];]Out[11]= {25.08 Second, Null}We see this is clearly of no better than quadratic complexity, whereas Iwould guess you were expecting O(n*Log[n]). So this indicates a problem.Offhand I do not know what aspect of your code is responsible, but Iıllgive some different code that has the desired complexity.Note that some of this, and code very similar to that below, isdiscussed at:http://library.wolfram.com/conferences/devconf99/lichtblau /in the section entitled Trees.There is a corresponding Mathematica notebook available at:http://library.wolfram.com/conferences/devconf99/near the bottom of the web page.The code I used to implement a tree structure similar to yours is below.One difference is that, as I place node values in the center, when theyare ŝattened the tree is automatically sorted. You might (or might not)regard this as an added beneŜt.leftsubtree[node[left_, _, _]] := leftrightsubtree[node[_, _, right_]] := rightnodevalue[node[_, val_, _]] := valemptyTree = node[];Clear[treeInsert]treeInsert[emptyTree, elem_] := node[emptyTree, elem, emptyTree]treeInsert[tree_, elem_] /; OrderedQ[{nodevalue[tree], elem}] := node[leftsubtree[tree], nodevalue[tree], treeInsert[rightsubtree[tree], elem]]treeInsert[tree_, elem_] := node[treeInsert[leftsubtree[tree],elem], nodevalue[tree], rightsubtree[tree]]Now for some tests.In[40]:= tt1k = First[Timing[ff1k = node[]; Do[ff1k = treeInsert[ff1k, ee[[j]]], {j,1000}];]] Out[40]= 0.15 SecondWe will check that the ŝattened version is actually sorted.In[41]:= gg1k = Apply[List,Flatten[ff1k]];In[42]:= gg1k === Sort[Take[ee,1000]]Out[42]= TrueAlso we will observe that the maximum depth is reasonable.In[43]:= Depth[ff1k]Out[43]= 23In the perfectly balanced case it would be 10 so this is not too bad.For larger examples Iıll just show timings.In[44]:= tt2k = First[Timing[ff2k = node[]; Do[ff2k = treeInsert[ff2k, ee[[j]]], {j,2000}];]]Out[44]= 0.32 SecondIn[45]:= tt4k = First[Timing[ff4k = node[]; Do[ff4k = treeInsert[ff4k, ee[[j]]], {j,4000}];]]Out[45]= 0.73 SecondIn[47]:= tt8k = First[Timing[ff8k = node[]; Do[ff8k = treeInsert[ff8k, ee[[j]]], {j,8000}];]]Out[47]= 1.58 SecondIn[53]:= SeedRandom[5]; ee = Table[Random[], {32000}];In[54]:= tt32k = First[Timing[ff32k = node[]; Do[ff32k = treeInsert[ff32k, ee[[j]]], {j,32000}];]]Out[54]= 7.58 SecondThis is not of blinding speed but it has the advantage of exhibiting theappropriate run-time complexity. One can, with careful coding, cut downon tree size but if you check with LeafCount you will Ŝnd that theversion above is already not too wasteful (3x larger than #valuesstored). Moreover the code needed would run a bit slower as it wouldhave more cases to check.As for removing nodes, I think you will need to use some form of heldattribute so as to avoid copying the entire tree when you alterelements.Daniel LichtblauWolfram Research====I have quite an easy and annoying problem with mathematica:I need to deŜne a function f(x,y) which takes some values forx=0,2pi,4pi (indepently of y) and has a different expression for allthe other values of y. This is easily done for one-dimensionalfunctions but I am in serious troubles for my two-dimensional problem:any suggestion?Fabio