A37 == 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 === 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 === 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}]}] === 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.> === 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 fix?.........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 find 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. === Hello watcher2,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 simplifications without you having toinvoke Simplify[].Best regards, === Betreff: 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. === 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 fine 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 from all other LaTeX definitions? === you must change the fonts, because the Mathematica symbols are designed to fit to Times/Helvetica/Courier and not to Computer Modern ! Mixing Computer Modern and the Mathematica fonts look not very nice because Comuter Modern has smaler strokes. You need atleast wrisym.sty, i.e. usepackage[monospacemath]{wrisym} but this will switch the main document font to Times and the mono-space font to courier. With Mathematica 4.2 you can use Adobe-Garamond and Janson as document fonts too, with usepackage[monospacemath,garamond]{wrisym} but this are commercial fonts and you have to buy it from Adobe.b) If you like the narrow monotype fonts similar to Computer Modern you can use the CMTT fonts, now included in Mathematica 4.2 Just use the package option usepackage[cmtt]{wrisym}c) I have a TeX frontend that use only the wrisym package and a preprocessor. It run fine with the most style files But you have to use TeX notebooks that are essential TeX files with mathinput environments. The TeX frontend send the contents of the mathinput environments to the kernel and paste the output into the final TeX file. It also does some fancy formating with the Mathematica input and replace -> with Rule, :> with RuleDelayed .. You can have the program and the style files if you like.Regards JensKyriakos Chourdakis wrote:> > Dear all,> > I want to include some Mathematica code in some lecture notes I am writing.> For that purpose, I use the LaTeX style provided with Mathematica. It seems> to be working fine when I produce a document that is just Mathematica code.> > The problem - as expected - is that when I include the Mathematica code as> a part of a larger document, there are> (1) clashes with existing packages> (2) some LaTeX elements, such as the equations, start to use the> Mathematica fonts too. My objective would be to typeset a document in> standard LaTeX, where only the Mathematica code has the Mathematica feeling.> > Does anyone know of any style available that is completely seperated from> all other LaTeX definitions? == There are two BrowserIndex files. Only delete the .nb one (or just move it somewhere 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 defined 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 first 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}]- 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 id55 6g == 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, Infinity}]>I'm a newbie, bat I mean:*************************In[1]= NumericQ[z]Out[1]=False*************************BTW, z is a real number. === Group;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 difficulty: 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 = ... ; final step ]To see what went wrong, I use (* *) selectively as follows:Stage 1myFunction[f_] := Module[ {L1,L2,L3},L1 = ... (*;L2 = ... ;L3 = ... ; final step *) ]Thus I see if L1 worked as expected. The next step is to put (* after L2and see if this works. I continue this til the bitter end and I usuallyfind 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. The output 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 terriblydifficult 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 === I often run into this difficulty: when designing a program, say as a> module, and testing it for various inputs, I get wrong answers. What to> do? I use a method that works for me but may not be the best available.> I want to show my method and then ask a question about how it can be> imporved. (Oh yes, I abandoned Trace a long time ago!)> > myFunction[f_] := Module[ {L1,L2,L3},> > L1 = ... ;> L2 = ... ;> l3 = ... ;> final step> > ]> > To see what went wrong, I use (* *) selectively as follows:> > Stage 1> > myFunction[f_] := Module[ {L1,L2,L3},> > L1 = ... (*;> L2 = ... ;> L3 = ... ;> final step *)> > ]> > Thus I see if L1 worked as expected. The next step is to put (* after L2> and see if this works. I continue this til the bitter end and I usually> find my errors.> > My question; The process of moving (* *) step by step through the> program is quite tedious when the code has lots more lines. What I would> like is a meta-program which (like FoldList) does this job for me. The> output of this meta-program is the list of outputs of each line in the> module, probably best printed as a column.> This sounds like Trace but my problem with Trace is it is terribly> difficult to read. For the not-so-subtle programming I do, the only thing> I need is what expression is returned line by line.> > Any advice? All remarks are appreciated!> I've enhanced the code for PartialEvaluation (see my post, which Iincorrectly attaced to someone else's reply). It is somewhat moreflexible now and does more error checking. It finds 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.markfisher.net/~mefisher/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] = {};(* find the rule that matches *)matches = Position[MatchQ[f[args], #]& /@ dv[[All, 1]], True];match = dv[[ matches[[1, 1]] ]];(* find the main CompoundExpression *)ppos = Position[match, HoldPattern[CompoundExpression[__]]];pos = First[Sort[ppos]];(* extract, truncate, append to, and reinsert it *)held = Extract[match, pos, Hold];held = ReplacePart[held, Sequence, {1, 0}];held = Take[held, n];held = Join[held, Hold[expr]];held = ReplacePart[Hold[Evaluate[held]], CompoundExpression, {1, 0}];match = ReplacePart[match, held, pos, 1];(* apply the modified rule and restore DownValues *)result = f[args] /. match;DownValues[f] = dv;result- I often run into this difficulty: when designing a program, say as a> module, and testing it for various inputs, I get wrong answers. What to> do? I use a method that works for me but may not be the best available.> I want to show my method and then ask a question about how it can be> imporved. (Oh yes, I abandoned Trace a long time ago!)> > myFunction[f_] := Module[ {L1,L2,L3},> > L1 = ... ;> L2 = ... ;> l3 = ... ;> final step> > ]> > To see what went wrong, I use (* *) selectively as follows:> > Stage 1> > myFunction[f_] := Module[ {L1,L2,L3},> > L1 = ... (*;> L2 = ... ;> L3 = ... ;> final step *)> > ]> > Thus I see if L1 worked as expected. The next step is to put (* after L2> and see if this works. I continue this til the bitter end and I usually> find my errors.> > My question; The process of moving (* *) step by step through the> program is quite tedious when the code has lots more lines. What I would> like is a meta-program which (like FoldList) does this job for me. The> output of this meta-program is the list of outputs of each line in the> module, probably best printed as a column.> This sounds like Trace but my problem with Trace is it is terribly> difficult to read. For the not-so-subtle programming I do, the only thing> I need is what expression is returned line by line.> > Any advice? All remarks are appreciated!> === 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 large number 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/: 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. _ | 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 difficulty 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?>>Thanks in advance for all your help>>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. === I wrote a package (call it ThisPackage`) that usesDeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to preventthe loading of a large file in routine cases. However, when ThisPackage`defines its functions, inside the Private` area, it includes a conditionalcall to BigVariable. It turns out that OtherPackage is loaded when thatfunction is defined. 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 defined. Any ideas?Thanks!Nicholas === Hi,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.Regards Jensng wrote:> > I wrote a package (call it ThisPackage`) that uses> DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent> the loading of a large file in routine cases. However, when ThisPackage`> defines its functions, inside the Private` area, it includes a conditional> call to BigVariable. It turns out that OtherPackage is loaded when that> function is defined. I was wondering if there is a way to avoid this.> Roughly speaking, here is the setting:> > BeginPackage[ OtherPackage` ]> BigVariable::usage=example> Begin[Private`]> BigVariable=Table[x y,{x,1000},{y,1000}]> End[ ]> EndPackage[ ]> > BeginPackage[ ThisPackage` ]> function::usage=example> Begin[Private`]> function[x_]:=Module[{y},> y=If[x>1000,BigVariable[[x]],x] ]> End[ ]> EndPackage[ ]> > I don't want OtherPakage to be loaded unless function[x] is called with> x>1000 but it loads when function is defined. Any ideas?> > Thanks!> > Nicholas === Dynamic programming might help: replace the line defining 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 Jowettng wrote in messagenews:alubet$no8$1@smc.vnet.net...> I wrote a package (call it ThisPackage`) that uses> DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent> the loading of a large file in routine cases. However, when ThisPackage`> defines its functions, inside the Private` area, it includes a conditional> call to BigVariable. It turns out that OtherPackage is loaded when that> function is defined. I was wondering if there is a way to avoid this.> Roughly speaking, here is the setting:>> BeginPackage[ OtherPackage` ]> BigVariable::usage=example> Begin[Private`]> BigVariable=Table[x y,{x,1000},{y,1000}]> End[ ]> EndPackage[ ]>> BeginPackage[ ThisPackage` ]> function::usage=example> Begin[Private`]> function[x_]:=Module[{y},> y=If[x>1000,BigVariable[[x]],x] ]> End[ ]> EndPackage[ ]>>> I don't want OtherPakage to be loaded unless function[x] is called with> x>1000 but it loads when function is defined. Any ideas?>>> === Could you send a sample example of your file -- just a few records.Tomas GarzaMexico City----- Original Message -----From: 1.156 Subject: trying to pull numbers out of a string from a file...> I've got to extract some numbers from a file that are in lines of text.Since the line contents are not numbers, I presume I must pull the line outas 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 toget just the stuff I want:> y1=StringTake[y ,{25,110}];>> Here's the output. StringTake doesn't seem to work.>> StringTake[{aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 -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 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?>> === Hi,> > 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 file with some Mathematica Input/Output > environments) and send the input cells to a kernel> and insert the output into the final TeX file ...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 sufficient 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 figures 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.> > 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> > Rob,> 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.> > StringTake[{aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 > -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:-ifile = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}]; === First of all, I used ReadList directly, with Word instead of String, andwith the option WordSeparators -> None, like this (I presume your file isadequately located, so that there is no problem in finding 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]={aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 -1281.9 -229. 321. 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 file in a different way, without the WordSeparators option:In[6]:=b=ReadList[197-tst.txt,Word,RecordLists -> True];In[7]:=b[[1]]Out[7]={aEX-004,2002197,0,0,0,5935.80,5946.66,27.06,-1281 .9 ,-229.,321.,317.,367.,-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 file like this:In[11]:=ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem.Tomas GarzaMexico City> ----- Original Message -----> From: 1.156 > Sent: Friday, September 13, 2002 12:14 AM> Subject: trying to pull numbers out of a string from a file...>> > I've got to extract some numbers from a file that are in lines of text.> Since the line contents are not numbers, I presume I must pull the 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.> >> > StringTake[{aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 -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 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?> >> > === 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. === Rob,> 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.> > StringTake[{aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 > -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:-ifile = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}] === I was and do have problems reading files Exported files in AdobeIllustrator format (.ai) from Adobe Illustrator 10.0.3.With an upgrade to Adobe Illustrator 10.0.3, I can read EPS filescreated by Mathematica 4.0.1.A message from tech support at Wolfram implies that Adobe Illustratorformat files can be read ONLY if you are using the correct Adobe andWolfram programs. Additionally, Mathematica is going to favor the exportof EPS files (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 file ImageFileName.eps within Adobe Illustrator 10.0.3Save the file as a .ai fileBe sure to check the ImageSize as it is not often what you toldMathematica. == 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?>> Regards,>> Bernard Gress>> Wizard Lab wrote:> 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 first 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 definitionof f and a missing bracket in the definition 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, Infinity}]NIntegrate::itraw:Raw object !(1.2`) cannot be used as aniterator.As you see, in the definition 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 definition for F should beF[z_] := NIntegrate[f[y, z], {y, 0, Infinity}]But... F[z] will still give you an error if z doesn't have a numericalvalue, so it's even better to define F this way:ClearAll[F]F[z_?NumericQ] := NIntegrate[f[y, z], {y, 0, Infinity}]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 askedyou about that days ago, but your e-mail address was no good -- probablystill isn't.)Bobby Treat === Subject: Re: NIntegrateJens-Peer Kuska wrote>> 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, Infinity}]>I'm a newbie, bat I mean:*************************In[1]= NumericQ[z]Out[1]=False*************************BTW, z is a real number.--Rob_jack === Thanks! You're brilliant -- though I'm not clear on why that worked.I'm learning the fine art of patterns and Hold one tricky example at atime. Re: ByteCount for Global symbolsHi,whats wrong withToExpression[#, StandardForm, Hold] & /@ Names[Global`*] /. Hold[a_] :> ByteCount[OwnValues[a]]Regards JensDrBob wrote:> > 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.> == 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-----From: Jens-Peer Kuska [mailto:kuska@informatik.uni-leipzig.de] Subject: Re: ByteCount for Global symbolsHi,whats wrong withToExpression[#, StandardForm, Hold] & /@ Names[Global`*] /. Hold[a_] :> ByteCount[OwnValues[a]]Regards JensDrBob wrote:> > 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 === T === Often, what I do when developing a slightly complicated module is to firsttest 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 difficulty 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 find that the easiest method to track down errors.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/From: Jack Goldberg [mailto:jackgold@umich.edu]Hi Group:I often run into this difficulty: when designing a program, say as a module, and testing it for various inputs, I get wrong answers. What 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 = ... ; final step ]To see what went wrong, I use (* *) selectively as follows:Stage 1myFunction[f_] := Module[ {L1,L2,L3},L1 = ... (*;L2 = ... ;L3 = ... ; final step *) ]Thus I see if L1 worked as expected. The next step is to put (* after L2and see if this works. I continue this til the bitter end and I usuallyfind 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 terriblydifficult 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! === 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 defined), keeping only those expressions specified.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 aredefined.) 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 first 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.David Park wrote in message news:...> Jack,> > Often, what I do when developing a slightly complicated module is to first> 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 difficulty 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 find that the easiest method to track down errors.> > David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> > From: Jack Goldberg [mailto:jackgold@umich.edu]> > Hi Group:> > I often run into this difficulty: when designing a program, say as a> module, and testing it for various inputs, I get wrong answers. What to> do? I use a method that works for me but may not be the best available.> I want to show my method and then ask a question about how it can be> imporved. (Oh yes, I abandoned Trace a long time ago!)> > myFunction[f_] := Module[ {L1,L2,L3},> > L1 = ... ;> L2 = ... ;> l3 = ... ;> final step> > ]> > To see what went wrong, I use (* *) selectively as follows:> > Stage 1> > myFunction[f_] := Module[ {L1,L2,L3},> > L1 = ... (*;> L2 = ... ;> L3 = ... ;> final step *)> > ]> > Thus I see if L1 worked as expected. The next step is to put (* after L2> and see if this works. I continue this til the bitter end and I usually> find my errors.> > My question; The process of moving (* *) step by step through the> program is quite tedious when the code has lots more lines. What I would> like is a meta-program which (like FoldList) does this job for me. The> output of this meta-program is the list of outputs of each line in the> module, probably best printed as a column.> This sounds like Trace but my problem with Trace is it is terribly> difficult to read. For the not-so-subtle programming I do, the only thing> I need is what expression is returned line by line.> > Any advice? All remarks are appreciated!> === 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?Regards,Peter Klamser === There has been an interesting discussion about using InterpolatingFunctionfor an empirical CDF.If one is willing to sacrifice some theoretical soundness, an empirical CDFmay be computed in a simplified 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}],PlotRange->{0,1},PlotJoin ed ->True,Axes->None,Frame->True,GridLines->Automatic]]Again, this plot does not reflect 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-----From: Mark Fisher [mailto:mark@markfisher.net] Subject: Re: Empirical CDF and InterpolatingFunctionDaniel 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 defined 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 first 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}]--Markmark@markfisher.net (Mark Fisher) wrote in 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 trying to pull numbers out of a string from a file...Organization: wrote:>I've got to extract some numbers from a file that are in lines of>text. Since the line contents are not numbers, I presume I must pull>the line out as a string. Here I start by pulling out just one line:>>inFile = OpenRead[197-tst.txt] >y = ReadList[inFile, String, 1, RecordLists -> True] >Close[inFile];>>This appears to pull in a line. Now I want to take characters 25 to>110 to get just the stuff I want: y1=StringTake[y ,{25,110}];>>Here's the output. StringTake doesn't seem to work.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 significant effect for large data sets.The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and Graphics`Graphics`. Look at the functions Histogram, Frequencies and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. === I 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 Mathematica 4.1 on a win2k VMWare machine running on Linux 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?> > Thanks,> HusainI'll respond to your third question first. 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 flattened the tree is automatically sorted. You might (or might not)regard this as an added benefit.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 flattened 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 find 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-----From: tgarza01@prodigy.net.mx [mailto:tgarza01@prodigy.net.mx] Subject: trying to pull numbers out of a stringfrom a file...Hello, Rob:First of all, I used ReadList directly, with Word instead of String, andwith the option WordSeparators -> None, like this (I presume your fileisadequately located, so that there is no problem in finding 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]={aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 -1281.9 -229. 321.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 file in a different way, without the WordSeparators option:In[6]:=b=ReadList[197-tst.txt,Word,RecordLists -> True];In[7]:=b[[1]]Out[7]={aEX-004,2002197,0,0,0,5935.80,5946.66,27.06,-1281 .9 ,-229.,321.,317.,367.,-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 file like this:In[11]:=ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem.Tomas GarzaMexico City> ----- Original Message -----> From: 1.156 > Sent: Friday, September 13, 2002 12:14 AM> Subject: trying to pull numbers out of a stringfrom a file...>> > I've got to extract some numbers from a file 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.> >> > StringTake[{aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 -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 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-----From: Lawrence A. Walker Jr. [mailto:lwalker701@earthlink.net] Subject: 'More' hyperlinksHey,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 afunction.Thanks,Lawrence === 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-----From: Klamser [mailto:klamser@t-online.de] Subject: no complexHi,Mathematica often produces complex resluts. But the problem is notcomplex: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?Regards,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 defined 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 find 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 efficiently.Tom Burton === Hi there!!I have quite an easy and annoying problem with mathematica:I need to define 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?Thanks a lot,Fabio == Hi,Clear[f]f[0, _] := qf[Pi, _] := pf[2Pi, _] := rf[x_, y_] := x^2*y^2???Regards Jensfabio bagarello wrote:> > Hi there!!> I have quite an easy and annoying problem with mathematica:> I need to define a function f(x,y) which takes some values for> x=0,2pi,4pi (indepently of y) and has a different expression for all> the other values of y. This is easily done for one-dimensional> functions but I am in serious troubles for my two-dimensional problem:> any suggestion?> Thanks a lot,> Fabio === I have quite an easy and annoying problem with mathematica:> I need to define a function f(x,y) which takes some values for> x=0,2pi,4pi (indepently of y) and has a different expression for all> the other values of y. This is easily done for one-dimensional> functions but I am in serious troubles for my two-dimensional problem:> any suggestion?> Thanks a lot,> 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}} ==== Hi there!!> I have quite an easy and annoying problem with mathematica:> I need to define a function f(x,y) which takes some values for> x=0,2pi,4pi (indepently of y) and has a different expression for all> the other values of y. This is easily done for one-dimensional> functions but I am in serious troubles for my two-dimensional problem:> any suggestion?> Thanks a lot,> 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 define a function f(x,y) which takes some values for> x=0,2pi,4pi (indepently of y) and has a different expression for all> the other values of y. This is easily done for one-dimensional> functions but I am in serious troubles for my two-dimensional problem:> any suggestion?> Thanks a lot,> FabioHi,Something like this?In[1]:= f[x_,y_] := If[Mod[x,2*Pi] ==== 0, Exp[x], Sin[y]+x]In[2]:= f[4*Pi, y] 4 PiOut[2]= EIn[3]:= f[1, y]Out[3]= 1 + Sin[y]--Bhuvanesh,Wolfram Research. === Hi there!!> I have quite an easy and annoying problem with mathematica:> I need to define a function f(x,y) which takes some values for> x=0,2pi,4pi (indepently of y) and has a different expression for all> the other values of y. This is easily done for one-dimensional> functions but I am in serious troubles for my two-dimensional problem:> any suggestion?> Thanks a lot,> 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 === Subject: problems with the definition of a function >I have quite an easy and annoying problem with mathematica:>I need to define a function f(x,y) which takes some values for>x=0,2pi,4pi (indepently of y) and has a different expression for all>the other values of y. This is easily done for one-dimensional>functions but I am in serious troubles for my two-dimensional problem:>any suggestion?>Thanks a lot,>FabioIt's difficult 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 definition === I am new with Mathematica, I have one question,I know that the solution might be very easy, but I wasn't able to find it by now.I would like to draw an ellipse, the formula let's say is as follows:0.09 x^2 +0.04 x y + 0.06 y^2 = 4 === 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]];German Buitrago A.----- Original Drawing an ellipse> I am new with Mathematica, I have one question,> I know that the sollution might be very easy, but I wasn't able to> find it by now.> I would like to draw an ellipse, the formula let's say is as follows:>>>> 0.09 x^2 +0.04 x y + 0.06 y^2 = 4>> === hello,first this in not an ellipse.the ellipse generic formula is : (x^2)/(a^2)+(y^2)/(b^2) = 0.I guest that you want report a graph of the solution y of the equation: 0.09x^2 +0.04 x y + 0.06 y^2 = 4 for x varying into a given range.As you can veryfing using:Solve[0.09 x^2 + 0.04 x y + 0.06 y^2 == 4, y]the solutins are two:{{y -> 8.333333333333334*(-0.04*x -0.1414213562373095*Sqrt[48.00000000000001 + 0.*x - 1.*x^2])}, {y -> 8.333333333333334*(-0.04*x +0.1414213562373095*Sqrt[48.00000000000001 + 0.*x - 1.*x^2])}}than you can construct a function:function1[x_] = 8.333333333333334*(-0.04*x -0.1414213562373095*Sqrt[48.00000000000001 - *x^2])},that is a real value only if (48.00000000000001 - *x^2)>0, i.e. ifapproximatively -6 True]the same for the other soluztion.good luck-upimak ha scritto nel messaggionews:am95aj$jsk$1@smc.vnet.net...> Hello,> I am new with Mathematica, I have one question,> I know that the sollution might be very easy, but I wasn't able to> find it by now.> I would like to draw an ellipse, the formula let's say is as follows:>>>> 0.09 x^2 +0.04 x y + 0.06 y^2 = 4>> === 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];pimak wrote:> Hello,> I am new with Mathematica, I have one question,> I know that the sollution might be very easy, but I wasn't able to> find it by now.> I would like to draw an ellipse, the formula let's say is as follows:> > > > 0.09 x^2 +0.04 x y + 0.06 y^2 = 4> > Thanks> > Maciej> > > > > - === Hi,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.Regards Jenspimak wrote:> > Hello,> I am new with Mathematica, I have one question,> I know that the sollution might be very easy, but I wasn't able to> find it by now.> I would like to draw an ellipse, the formula let's say is as follows:> > 0.09 x^2 +0.04 x y + 0.06 y^2 = 4> > === 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?> > Thanks.> Higinio RamosHi Higinio,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}] === 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 first, 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 definitionof 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 definition of f was still there.Carl WollPhysics DeptU of WashingtonHiginio Ramos wrote in messagenews:am95cj$k1k$1@smc.vnet.net...>> 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?>> == Hi,and after cont = 0;f[x_?NumericQ] := (cont++; x^2);NDSolve[{y''[x] + y[x] == f[x], y[0] == 1, y'[0] == 0}, y, {x, 0, 6}]cont is 93.Thats because *you* gave only a blank pattern for f[x_] and NDSolve[]evaluate it to compile the right hand sides or translate itto an internal function. So *your* function is only oncewhen Mathematica can include it into it's internal functionfor the right hand sides.Regards JensHiginio Ramos wrote:> > 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?> > === 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 first definition. I have quite an easy and annoying problem with mathematica:I need to define 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? Hi,yes, this is a comon problem.You can either do:y=If[x>1000, ToExpression[BigVariable][[x]],x] ]or, maybe more readable, declare at the begging of ThisPackage:bigvar := bigvar = ToExpression[OtherPackage`BigVariable];and then y=If[x>1000, bigvar, x](* ************************** *)Alternatively you can create .mx files which load much quicker than .m files.It would be really nice if WRI could investigate why loading larger .m files is so slow ( I suspect it has to do something with the speed of side effectslike DownValues declarations etc., but I don't know I wrote a package (call it ThisPackage`) that usesDeclareePackage[OtherPackage`, {BigVariable} ]. The idea was to preventthe loading of a large file in routine cases. However, when ThisPackage`defines its functions, inside the Private` area, it includes a conditionalcall to BigVariable. It turns out that OtherPackage is loaded when thatfunction is defined. 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>100 0, 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 defined. Any ideas? === 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 specific basesince they'd be going from base 3 to base 9, for example so maybe num isneeded at all).Thank you, Flip === Mabye this is too simple, but I cant just figure 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 figure it out>> I want to get an inverse function for y[t] where>> y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]]> and> R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0=> 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.> === 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 Washingtonmartin skogstad wrote in messagenews:am95s4$k3d$1@smc.vnet.net...> Dear NG>>> Mabye this is too simple, but I cant just figure it out>> I want to get an inverse function for y[t] where>> y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]]> and> R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0=> 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.>>> === 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 significance of choosing the bin width......jerry blimbaum-----Original Message----- 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. Avery nice package that does all of the above and more is mathStatica. Seehttp://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 nosignificant 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` andGraphics`Graphics`. Look at the functions Histogram, Frequencies 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 significant 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, fl === I never liked the function, but now I have need of it. I hope someone can help me see the way to implement it.For a class I am teaching I want to write a simple function that does a random search for a function's maxima. I feed the function N randomly generated inputs and look at the outputs. Provided N is large enough, the largest of the outputs I obtain should be near the function's maximum value.What I want to be able to do is to identify the input that gave me that largest output. Any ideas?My only idea is this: create a table of pairs {output, input{ and find the element of the table that has the largest first entry. This will give me the input I seek. Is there a slick way of doing this in mathematica? === Here's one way:argMax::usage = argMax[f, domain] returns the element of domain for which f of that element is maximal -- breaks ties in favor of first occurrence.;SetAttributes[argMax, HoldFirst];argMax[f_, dom_List] := Fold[If[f[#1]>=f[#2], #1, #2]&, First[dom], Rest[dom]]And here's another way (defining it in terms of tupleMax)...tupleMax::usage = tupleMax[list] returns the tuple that is lexicographically maximal.;tupleMax[l_List] := Fold[If[OrderedQ[{#1, #2}], #2, #1]&, First[l], Rest[l]]argMax[f_, dom_List] := tupleMax[{f[#],#}& /@dom][[2]]--- I never liked the function, but now I have need of it. I hope > someone can help me see the way to implement it.> > For a class I am teaching I want to write a simple function that does > a random search for a function's maxima. I feed the function N > randomly generated inputs and look at the outputs. Provided N is > large enough, the largest of the outputs I obtain should be near the > function's maximum value.> > What I want to be able to do is to identify the input that gave me > that largest output. Any ideas?> > My only idea is this: create a table of pairs {output, input{ and > find the element of the table that has the largest first entry. This > will give me the input I seek. Is there a slick way of doing this in > mathematica?-- -- -- -- -- -- -- -- -- In science it often happens that scientists say, 'You know that's a really good argument; my position is mistaken,' and then they would actually change their minds and you never hear that old view from them again. They really do it. It doesn't happen as often as it should, because scientists are human and change is sometimes painful. But it happens every day. I cannot recall the last time something like that happened in politics or religion. -- Carl Sagan, 1987 CSICOP Keynote Address === Hi,fun[x_, y_] := x^2 + y^2RandomMin[n_Integer] := First[Sort[ {#, fun @@ #} & /@ Table[{Random[], Random[]}, {n}], Last[#1] < Last[#2] &]]should do it.Regards JensJason Miller wrote:> > I never liked the function, but now I have need of it. I hope> someone can help me see the way to implement it.> > For a class I am teaching I want to write a simple function that does> a random search for a function's maxima. I feed the function N> randomly generated inputs and look at the outputs. Provided N is> large enough, the largest of the outputs I obtain should be near the> function's maximum value.> > What I want to be able to do is to identify the input that gave me> that largest output. Any ideas?> > My only idea is this: create a table of pairs {output, input{ and> find the element of the table that has the largest first entry. This> will give me the input I seek. Is there a slick way of doing this in> mathematica?> > --> === The same principles that allow particular cases for defining a function of a single variable would apply here, because Mathematica applies particular rules before it applies general ones. For example: f[0, y_] := 0 f[2 Pi, y_] := y - 2 f[4 Pi, y_] := y - 4 f[x_, y_] := x^2 + y^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 first three lines above: f[k_ Pi, y_] := y - k /; IntegerQ[k] && EvenQ[k]There are variants as to where to place the condition IntegerQ[k] && EvenQ[k], for example: f[k_ Pi , y_] /; IntegerQ[k] && EvenQ[k] := y - k f[k_ Pi /; IntegerQ[k] && EvenQ[k], y_] := y - kfabio bagarello wrote:> Hi there!!> I have quite an easy and annoying problem with mathematica:> I need to define a function f(x,y) which takes some values for> x=0,2pi,4pi (indepently of y) and has a different expression for all> the other values of y. This is easily done for one-dimensional> functions but I am in serious troubles for my two-dimensional problem:> any suggestion?> Thanks a lot,> 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 first 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^3 Subject: problems with the definition of a functionHi there!!I have quite an easy and annoying problem with mathematica:I need to define 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?Thanks a lot,Fabio === Hi Everybody, 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? === Well, you can just solve for h. However, in this case there isn't a symbolicsolution.Raj Hi Everybody,>> 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 === 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]Regards JensRaj wrote:> > Hi Everybody,> > 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.Thanks in advance for any hints...Back space key when I am in the front end don't workcorrectly. It advances instead of go back and there isno way to erase something I wrote in the notebook. The pointer mark of the mouse looks like a hand insteadof an arrow, and this don't work fine too.Is it a Mathematica Configuration problem or a LinuxConfiguration one? How can I solve this?Note: This problem seems to appear just in myworkspacei mean this not happen for other users. I used Mathematica 4.1 for Linux Red hat 7.0 === Hi math group,> I don't have any idea about how to solve next problem.> Thanks in advance for any hints...> > Back space key when I am in the front end don't work> correctly. It advances instead of go back and there is> no way to erase something I wrote in the notebook. The> pointer mark of the mouse looks like a hand instead> of an arrow, and this don't work fine too.> Is it a Mathematica Configuration problem or a Linux> Configuration one? How can I solve this?> Note: This problem seems to appear just in my> workspace> i mean this not happen for other users. > I used Mathematica 4.1 for Linux Red hat 7.0> > Regards,> 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 === Thanks to all who helped me on this. Tomas in Mexico appears to have nailed this thing. Here is what I'm using now:In[1]:=a=ReadList[197-tst.txt,Word,RecordLists->True, WordSeparators->None];In[2]:=flds={{25,31}, {32,39},{40,46},{47,54},{55,62},{63,70},{71,78},{79,86},{87, 94},{95,102},{103,110}};Define this function:In[3]:=f[x_]:=ToExpression[StringTake[x[[1]],#]]&/@fldsNow, 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)Rob1.156 wrote:> I've got to extract some numbers from a file that are in lines of text. Since the line contents are not numbers, I presume I must pull the line out as a string. Here I start by pulling out just one line:>> inFile = OpenRead[197-tst.txt]> y = ReadList[inFile, String, 1, RecordLists -> True]> Close[inFile];>> This appears to pull in a line. Now I want to take characters 25 to 110 to get just the stuff I want:> y1=StringTake[y ,{25,110}];>> Here's the output. StringTake doesn't seem to work.>> StringTake[{aEX-004 2002197 0 0 0 5935.80 5946.66 27.06 -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?>> === 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}-- === Help!After using SetOptions[Graphics3D, ...] I am trying to set the default options of Graphics3D back to what they were when I started up Mathematica. I cannot find a command to do this. Is this possible? -- Thanks for any help, === Options[Graphics3D]; (* save the original options *)SetOptions[Graphics3D, ...]; (* mess with them *)SetOptions[Graphics3D, Sequence@@o]; (* restore them *)--- / FROM David Sagan AT 02.09.18 06:29 (Today) / ---> Help!> > After using SetOptions[Graphics3D, ...] I am trying to set the default > options of Graphics3D back to what they were when I started up > Mathematica. I cannot find a command to do this. Is this possible?> > -- Thanks for any help, David Sagan-- -- -- -- -- -- -- -- -- -- -- -- 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 Mathematica Hmm,oldOptions=Options[Graphics3D]; SetOptions[Graphics3D,Boxed->False](* do something with it *)SetOptions[Graphics3D, Sequence @@ oldOptions]works fine.Regards JensDavid Sagan wrote:> > Help!> > After using SetOptions[Graphics3D, ...] I am trying to set the default> options of Graphics3D back to what they were when I started up> Mathematica. I cannot find a command to do this. Is this possible?> > -- Thanks for any help, David Sagan === 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 first 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 infinite 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 be required 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 workingsufficiently 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 fixing all but the mostpathological of examples. The status of that work is unfortunately notknown to me at present, though I'll try to find out about it. === 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-----From: Daniel Lichtblau [mailto:danl@wolfram.com] Subject: Why is my Implementation of SortedTrees So Slow?Husain Ali Al-Mohssen wrote:> > Hi all,> > I am trying to implement a very simple sorted tree to quickly storesome> 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 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}> > (running on Mathematica 4.1 on a win2k VMWare machine running on LinuxRH7.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?> > Thanks,> HusainI'll respond to your third question first. 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 flattened the tree is automatically sorted. You might (or might not)regard this as an added benefit.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 flattened 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 find 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'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-----From: danl@wolfram.com [mailto:danl@wolfram.com] Subject: Re: Why is myImplementation of Sorted Trees So Slow?DrBob wrote:> > 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 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 first 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 infinite 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 workingsufficiently 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 fixing all but the mostpathological of examples. The status of that work is unfortunately notknown to me at present, though I'll try to find 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 === Note that both And and Or can return a value without evaluating all oftheir arguments. For example, if the first 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 first. 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 significant amount of time to compute, then sorting firstmay 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 -----From: Evgeni Trifonov Subject: build-in commutativity> I'm curious, why the built-in boolean functions And and Or> aren't commutative?>> Attributes/@{Or,And}//ColumnForm>> {Flat, HoldAll, OneIdentity, Protected}> {Flat, HoldAll, OneIdentity, Protected}>> However, the arithmetical functions are Orderless:>> Attributes/@{Plus,Times}//ColumnForm>> {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}> {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}>> -------------------> Evgeni Trifonov> Vladivostok, Russia === I have defined two functions (Math 4.1)In[1]:= integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t];In[2]:= integrate[Exp[(a_.)*tau], t_]:=(E^(a*t)-1)/a/; FreeQ[a,t]&&FreeQ[a,tau];when I applied these functions the solution is different if the coefficient is the letter d or lower (solution fine) or f or higher (solution wrong) . Here is an example: Using letter 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? === Neither of your solutions are wrong according to your rules.Lets step through themIn[3]:=integrate[f Exp[-0.8316*tau], t]The function Times is Orderless, so the kernel rewrites the integrand inlexographical (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 your rule 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 fix 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.Cheers,ErichOn Thu, 19 Sep 2002 guillerm@usal.es wrote:> I have defined two functions (Math 4.1)> In[1]:= integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t];> In[2]:= integrate[Exp[(a_.)*tau], t_]:=(E^(a*t)-1)/a/;> FreeQ[a,t]&&FreeQ[a,tau];>> when I applied these functions the solution is different if the coefficient is> the letter d or lower (solution fine) or f or higher (solution wrong) . Here is> an example:>> Using letter f> In[3]:=integrate[f Exp[-0.8316*tau], t]>> Out[3]:=integrate[f, t]/E^(0.8316*tau) (*wrong*)>> Using letter a (the solution is rigth>> In[4]:=integrate[a Exp[-0.8316*tau], t]>> Out[4]:=-1.20250*a*(-1 + E^(-0.8316*t))>> What it wrong?> === I am new with Mathematica, I have one question,I know that the sollution might be very easy, but I wasn't able tofind 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 === Hello Raj,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. Invert a functionHi Everybody, 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 file called My_DisplayGraphicsViaJava.javaand compile it. Put the class file 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 file 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 final 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? === I'm trying to plot the next exponential functionPlot[Exp[1/(Abs[x-1]-Abs[x-2])],Range]If the Range is positive there arent problems. However if the Range isnegative Mathematica plots a strange beast...Have anyone found anything of this sort? I would apreciate to know how to resolve this problem.Thanks in advance, === 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.ErichOn Thu, 19 Sep 2002, Juan Egea Garcia wrote:> 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 arent 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.>> === 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 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 === 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 fine; ball B - which should arrive at h=0 before A - is beyond mymeans.Thank you for your consideration, === Subject: RE: Resetting after SetOptionsOrganization: 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 Help!After using SetOptions[Graphics3D, ...] I am trying to set the defaultoptions of Graphics3D back to what they were when I started upMathematica. I cannot find a command to do this. Is this possible? -- Thanks for any help, David Sagan I have the following code and am trying to include a legend. The BarChartappears, but with no legend. I have followed the 'help files', 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-----From: Jason Miller [mailto:millerj@truman.edu] Subject: Q: argmaxI never liked the function, but now I have need of it. I hope someone can help me see the way to implement it.For a class I am teaching I want to write a simple function that does a random search for a function's maxima. I feed the function N randomly generated inputs and look at the outputs. Provided N is large enough, the largest of the outputs I obtain should be near the function's maximum value.What I want to be able to do is to identify the input that gave me that largest output. Any ideas?My only idea is this: create a table of pairs {output, input{ and find the element of the table that has the largest first entry. This will give me the input I seek. Is there a slick way of doing this in mathematica?- Start with IntegerDigits and FromDigits. A key issue is what form youwant base 12 numbers, for instance, stored in -- a List of digits? Acharacter string? A list of digits, highest power to lowest, is easy to handle:ClearAll[convertBase]convertBase[(from_Integer)? (#1 > 1 & ), (to_Integer)?(#1 > 1 & ), n:{_Integer..}] /; Max[n] < from := IntegerDigits[FromDigits[n, from], to]convertBase[5, 3, {1, 2}]{2, Subject: Converting Between BasesHello,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 tothedesired 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 specificbasesince they'd be going from base 3 to base 9, for example so maybe num isneeded at all).Thank you, Flip This came up some time ago. Can't remember exactly what my reply was but Idiscovered later that it is because the number lock is on. Turn it off andthe hand will disappear. May even fix the back space trouble.YasOn Wed, 18 Sep 2002, Cesar Guerra wrote:> Hi math group,> I don't have any idea about how to solve next problem.> Thanks in advance for any hints...>> Back space key when I am in the front end don't work> correctly. It advances instead of go back and there is> no way to erase something I wrote in the notebook. The> pointer mark of the mouse looks like a hand instead> of an arrow, and this don't work fine too.> Is it a Mathematica Configuration problem or a Linux> Configuration one? How can I solve this?> Note: This problem seems to appear just in my> workspace> i mean this not happen for other users.> I used Mathematica 4.1 for Linux Red hat 7.0>> Regards,> Cesar.>>> __________________________________________________> I believe that's not the adjacency matrix Thomas asked for. It doesn'thave zeroes on the diagonal (it isn't square) and it doesn't have onesto indicate that two actors are associated with the same event.Instead, it shows connections between actors and events, which isactually more useful, as I'll demonstrate.(In addition -- though it doesn't really matter -- Jens-Peer switchedthe 'actors' and 'events' nomenclature within the function.)If you multiply it by its transpose, you get something else that'suseful:lst = {{1, A}, {1, B}, {2, B}, {3, C}, {3, D}, {1, D}, {1, C}};AdjacenceMatrix[lst : {{_, _} ..}] := Module[{actors, events, adj}, {actors, events} = Union /@ Transpose[lst]; adj = Table[0, {Length[actors]}, {Length[events]}]; Scan[(Part[adj, Sequence @@ #] = 1) &, lst /. MapIndexed[Rule[#1, First[#2]] &, events]]; adj]MatrixForm[a = AdjacenceMatrix[lst]]MatrixForm[b = a.Transpose[a]]Matrix 'b' records how many events two actors have in common. On thediagonal, it shows the total number of events each actor is connectedto.It's easy to put zeroes on the diagonal:MatrixForm[c = b (1 - IdentityMatrix[Length[b]])]To get the originally intended incidence matrix, this works:d = c /. {_?Positive -> 1}However, I think matrices 'a' and 'b' are actually more useful, and 'a'easily leads to all the others.Bobby-----Original Message-----From: Jens-Peer Kuska [mailto:kuska@informatik.uni-leipzig.de] Subject: Re: creating adjacency matricesHi,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}}Regards JensMoliterno, Thomas wrote:> > I need to create an adjacency matrix from my data, which is currentlyin> the form of a .txt file and is basically a two column incidence list.> For example:> > 1 A> 1 B> 2 B> 3 C> . .> . .> . .> m n> > Where 1 to m represent actors and A to n represent events. My goal isto> have an (m x m) matrix where cell i,j equals 1 if two actors are> incident to the same event (in the sample above, 1 and 2 are both> incident to B) and 0 otherwise (w/ zeros on the diagonal).> > I'm new to Mathmatica, and so I'm on the steep part of the learning> curve ... All I've been able to figure out so far is how to get my> incidence list into the program using Import[filename.txt]. But then> what? How do I convert to the adjacency matrix? I've found the> ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but Ican't> seem to get it to work ...> > Thanks to any and all in advance.> Maybe this will help. I had to do some guessing, and I fabricated myown R function (r). I never start user-defined symbols with capitalletters.ClearAll[r]t = Pi/2.;r = Interpolation[{#, Abs@Cos@#} & /@ Range[0, N@t, Pi/100.]];y[z_] := NIntegrate[r[x]^4, {x, 0, z}]Timing[yInverse = Interpolation[{y[#], #} & /@ Range[0, N@t, Pi/100.]];]{0.030999999999998806*Second, Null}a = NIntegrate[r[yInverse[z]*Cos[z]], {z, 0, y[t]}]/y[t]0.9249048118568042Bobby Treat-----Original Message-----From: martin skogstad [mailto:martinskogstad@hotmail.com] Subject: Inv.Interpol.FunctionDear NGMabye this is too simple, but I cant just figure 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 interval0= r Sin[t], y -> r Cos[t]}radius[t_] = r /. Last@Solve[polarEqn, r]ParametricPlot[radius[x]{Cos[x], Sin[x]}, {x, 0, 2Pi}, AspectRatio ->1];I tried and failed with InequalityGraphics:<< Graphics`InequalityGraphics`InequalityPlot[{LessEqual @@ eqn}, {x, -xMax, xMax}, {y, -yMax, yMax}]InequalityPlot::region:The region defined by[LeftSkeleton]1[RightSkeleton] could not be broken down intocylinders.InequalityPlot[ 0.09*x^2 + 0.04*x*y + 0.06*y^2 <= 4, {x, -xMax, xMax}, {y, -yMax,yMax}]Plot can be used very neatly, if you first figure out the true extent ofthe x-values:positiveX[y_] = x /. Last@Solve[eqn, x]Solve[positiveX'[y] == 0]xMax = First@(positiveX[y] /. %)Plot[Evaluate[y /. Solve[eqn, y]], {x, -xMax, xMax}, AspectRatio -> 1];Bobby Treat-----Original Message-----From: pimak [mailto:piotrowski.maciek@interia.pl] Subject: Drawing an ellipseHello,I am new with Mathematica, I have one question,I know that the sollution might be very easy, but I wasn't able tofind 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 That function isn't easily inverted and, in fact, has no inverse unlessyou limit the range of h. In this plot, for instance, you see that thesame f[h] values are taken on for two different values of h:Plot[f@h /. {a -> 3, b -> 0.2}, {h, 0, 10}]The peak of the graph depends on the parameters a and b, so the domainof an inverse (if it exists) also depends on a and b. That's exactlythe kind of situation Solve can't handle.For specific a, b and y, FindRoot can find h for you:FindRoot[Evaluate[f[h] == 1 /. {a -> 3,