A10 I'm curious about the different efficiencies of Export vs. Put; Import vs. Get. Eg. Saving a list called c with approx. 16,000 elements, each element being a three element list of reals. Export[ac.dat,c] takes forever and consumes heaps of kernel memory c>>ac.dat all done in an instant (relatively speaking) and without the transient burst of kernel memory usage. Ditto Import and Get. Can anyone explain this? Mike ==== Dear DrBob, I fear that your diagnosis of the efficiency problems in Husain's binary tree implementation is not correct. Furthermore your code is inefficient and awkward. Consider the following implementation using list to represent the tree. It is three lines long and is three times faster than yours on my computer though it uses twice as much memory as your representation. myadd[{},x_]:={x,{},{}}; myadd[{v_,a_,b_},x_]:=If[v>x, {v,myadd[a,x],b}, {v,a,myadd[b,x]}] t={}; Timing[Do[t=myadd[t,Random[]],{5000}];] {1.98 Second,Null} The real problem with the implementation is probably that the tree structure has to be 'copied' each time when add is called. You have to write tree = add[tree, x] t2 = add[t1, x] then you have *two* trees t1 and t2 which differ by the one element inserted by add. To the best of my knowledge, the internal representation of t1 and t2 in Mathematica is a tree too. But in principle the user code is duplicated in Mathematica. A further problem of all direct implementations is that they cannot be compiled (since they use pattern matching and the tree is a nested structure). Thus I guess that the efficient way to implement tree data structures is the indirect one using heaps (i.e. a combination of contiguous arrays with length known in advance and hashing). Johannes Ludsteck > You're not doing anything dumb as far as I can see, but you're using far > more memory than necessary. Here are statistics for your algorithm on > my machine: > > SeedRandom[5]; > nums = Null > Do[nums = add[nums, Random[]], {5000}]; // Timing > nums // LeafCount > nums // ByteCount > Count[nums, Null, Infinity] > Count[nums, node[_, Null, _], Infinity] > Count[nums, node[_, _, Null], Infinity] > Count[nums, node[_, Null, Null], Infinity] > Count[nums, node[___], Infinity] > Count[nums, node[_, _node | _?NumericQ, _node | _?NumericQ], Infinity] > Depth[nums] > > {4.406000000000001*Second, Null} > 15001 > 240000 > 5001 (* Null values in the tree *) > 2458 (* nodes without left offspring *) > 2543 (* nodes without right offspring *) > 1669 (* leaf nodes *) > 4999 (* total nodes *) > 1667 (* nodes with both left and right offspring *) > 28 (* minus one, makes 27 levels in the tree *) > > It's clearly not ideal to store 5001 Nulls for 5000 actual values! > > Here's a method that doesn't change the algorithm much, but changes the > storage method a great deal: > > First of all, I'm lazy, so I'll redefine <,>,<=,>=, etc. to make the > code simpler: > > Unprotect[Less, Greater, LessEqual, GreaterEqual]; > Less[a : _node ..] := Less @@ (First /@ {a}) > LessEqual[a : _node ..] := LessEqual @@ (First /@ {a}) > Greater[a : _node ..] := Greater @@ (First /@ {a}) > GreaterEqual[a : _node ..] := GreaterEqual @@ (First /@ {a}) > Protect[Less, Greater, LessEqual, GreaterEqual]; > > Again because I'm lazy, I'll define node so that I don't have to > consciously avoid leaf nodes and unnecessary nesting: > > ClearAll[node] > node[a___, node[b_], c___] = node[a, b, c]; > node[node[a__]] = node[a]; > > Here's my add function: > > Clear[add] > add[Null, x_] = node[x]; > add[x_, (y_)?NumericQ] := add[node[x], node[y]] > add[(x_)?NumericQ, y_] := add[node[x], node[y]] > add[node[x_], node[y_]] := If[x > y, node[x, y], node[y, x]] (* <-- > THERE! *) > add[node[x_, lower_], y_node] := > Which[y >= node[x], node[x, lower, y], > y <= node[lower], node[lower, y, x], True, node[y, lower, x]] > add[node[x_, lower_, higher_], y_node] /; > node[y] <= node[x] := node[x, add[lower, y], higher] > add[node[x_, lower_, higher_], y_node] := node[x, lower, add[higher, > y]] > > Where I have a pointer is the code that prevents adding right-offspring > to a leaf node. That avoids nodes like your node[a,Null,c]. When you > would have node[a,b,Null], I have node[a,b]. When you would have > node[a,Null,Null], I use a itself. > > Timing and space requirements are much better now: > > SeedRandom[5]; > nums = Null > Timing[Do[nums = add[nums, Random[]], {5000}]; ] > > {2.109*Second, Null} > > LeafCount[nums] > ByteCount[nums] > Count[nums, Null, Infinity] > Count[nums, node[_], Infinity] > Count[nums, node[_, _], Infinity] > Count[nums, node[_, _, _], Infinity] > Count[nums, node[___], Infinity] > Depth[nums] > > 7852 (* 48% fewer leaf expressions, > mostly due to Nulls and right-offspring eliminated *) > 165624 (* 31% less storage *) > 0 (* no Nulls, versus 5001 *) > 0 (* no leaf nodes, versus 1669 *) > (* no nodes without left-offspring, versus 2458 *) > 705 (* nodes without right offspring, versus 2543 *) > 2146 (* nodes with both left and right offspring, versus 1667 *) > 2851 (* total nodes *) > 21 (* 21 tree levels versus 27 *) > > The logical structure is identical to yours except that there are no > nodes with only right-offspring. This incidentally tends to reduce tree > depth. > > The storage format is far different: there are no trivial (childless) > nodes, and nodes with left-offspring but no right-offspring are stored > without a Null on the right. > > I could make this quite a bit faster, I think, if I spent time on the > code to eliminate changes to Less, Greater, etc. and the frequent > nesting followed by unnesting that goes on in the algorithm. It might > take twice as much code, however, so I like it as is. > > You're probably better off storing these things in a heap, of course. > > Or -- better yet -- use the built-in Sort and Ordering functions. > > Bobby Treat > > -----Original Message----- > > > > 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} > > 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? > > > Husain > > > <><><><><><><><><><><><> Johannes Ludsteck Economics Department University of Regensburg Universitaetsstrasse 31 93053 Regensburg ==== Is it possible to configure a style sheet so that functions or data shown in graphs are coloured (colored :)) in working but black in printing...without actually re-executing the function that created the graphics? thanks Mike Reply-To: kuska@informatik.uni-leipzig.de ==== no because the PostScript creation know nothing about the notebook frontend. Mathematica does its graphics in PostScript since version 1.0 but the notebook frontend was introduced in version 2.x and the actual typsetting/markup format was introduced in version 3.0. Jens > > Is it possible to configure a style sheet so that functions or data shown in > graphs are coloured (colored :)) in working but black in printing...without > actually re-executing the function that created the graphics? > > thanks > > Mike ==== A commonly used symbol for the Floor function is a square bracket with the upper indents removed. Is this symbol part of Mathematica's built-in symbols? I think not, so then, can it be constructed by hand. Jack ==== It turns out that Mathematica does have the floor symbols! Use esc l f esc for the left floor and esc r f esc for the right floor. In fact, if you type in esc l f esc a esc r f esc Mathematica will interpret the input as Floor[a]. Carl Woll Physics Dept U of Washington A commonly used symbol for the Floor function is a square bracket with the > upper indents removed. Is this symbol part of Mathematica's built-in symbols? I > think not, so then, can it be constructed by hand. Jack ==== > A commonly used symbol for the Floor function is a square bracket with > the upper indents removed. Is this symbol part of Mathematica's built-in > symbols? Sure. Just look for Floor in A.10 Listing of Major Built-In Mathematica Objects! For example, you can use [LeftFloor] and [RightFloor] to get the symbols you want. David Reply-To: kuska@informatik.uni-leipzig.de ==== what may [LeftFloor] and [RightFloor] show on screen ? It's easy to find in the complete characters palette | Operators | General Jens > > > A commonly used symbol for the Floor function is a square bracket with the > upper indents removed. Is this symbol part of Mathematica's built-in symbols? I > think not, so then, can it be constructed by hand. > > Jack ==== > > > A commonly used symbol for the Floor function is a square bracket with the > upper indents removed. Is this symbol part of Mathematica's built-in symbols? I > think not, so then, can it be constructed by hand. > > Jack [LeftFloor] and [RightFloor] can be used for this. Look at Chapter Advanced Mathematics/Mathematical and Other Notations/ Operators. Yours, Alexander -- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern / ==== Needs[Graphics`Graphics`] LogLinearPlot[Sqrt[x], {x, 1., 1000}, ImageSize -> 500]; David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Approved: Steven M. Christensen , Moderator Reply-To: ==== I don't know about elegance or simplicity, but I do have a FASTER solution, incidentally using combinations code that often comes in handy for me. Here's that code: << DiscreteMath`Combinatorica`; ClearAll[combinations]; r = Range[1, 9]; combinations::usage = combinations[list,n:{__Integer}] lists the combinations of list taken n at a time; combinations[r_List, n_Integer, {}] := If[n > Length@r, {}, DiscreteMath`Combinatorica`KSubsets[r, n]]; combinations[r_List, n_Integer, e_?VectorQ] := Join[e, #] & /@ DiscreteMath`Combinatorica`KSubsets[Complement[r, e], n]; combinations[r_List, n_Integer, e : {__?VectorQ}] := Flatten[combinations[r, n, #] & /@ e, 1]; combinations[r_List, n : {__Integer}] := Which[Plus @@ n == Length@r, Join[#, Complement[r, #]] & /@ combinations[r, Drop[n, -1]], Plus @@ n > Length@r, {}, True, Fold[combinations[r, #2, #1] &, {}, n]] The following duplicates your fLPartitions function, but is about 40% faster and uses about 15% less memory (for this example): Quit << DiscreteMath`Combinatorica` fLPartition[ksN_, r_] := With[{ks = KSubsets[ Range[r], ksN], ks1 = Partition[Range[r], 1]}, MapThread[ Complement[Append[#1, #2], (Sequence @@ {#1} & ) /@ Partition[#2, 1]] & , {Array[ks1 & , Length[ ks]], ks}]] Module[{ksN = 2}, While[ksN < r + 1, s = fLPartition[ksN, r]; ksN = ksN + 1; Print[s]]] Timing[fLPartition[3, 80]; ] {11.389999999999999*Second, Null} MaxMemoryUsed[] 233956264 Quit wantCombinations (* this loads my cominations function definition *) ClearAll[mine] mine[k_, n_] := (Join[List /@ Complement[ Range[n], #1], {#1}] & ) /@ combinations[Range[n], {k}] Timing[mine[3, 80]; ] {6.734999999999999*Second, Null} MaxMemoryUsed[] 195828264 However, I would change the storage structure to replace {{1},{2},...,{7}} with just {1,2,...7}. That cuts memory usage by 85% from your method for this example: Quit wantCombinations ClearAll[mySecond] mySecond[k_, n_] := (Join[Complement[Range[n], #1], {#1}] & ) /@ combinations[Range[n], {k}] Timing[mySecond[3, 80]; ] {2.922*Second, Null} (* versus 11.485 with your code, 6.7 with my other code *) MaxMemoryUsed[] 43996408 (* 44MB versus 234MB with your code, 196 MB with my other code *) Those comparisons include memory used during code execution; byte counts for that example are 134,742,424 for my storage method and 287,560,024 for yours. If you sometimes have to have a partition in your format, its easy enough to temporarily convert it from mine with the following function: f = Join[List /@ Drop[#1,-1], {Last[#1]}] & ; First[mySecond[2, 10]] f[%] {3, 4, 5, 6, 7, 8, 9, 10, {1, 2}} {{3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {1, 2}} First[fLPartition[2, 10]] {{3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {1, 2}} Bobby Treat -----Original Message----- [ksN<(r+1),s=fLPartition[ksN,r];ksN=ksN+1;Print[s]]] However, I do not like this solution since to my taste is to complex and rather inelegant. Nest or Fold would do better. Any Idea? Just an additional remark. Besides, I do not need the whole taxonomy, but a subset satisfying a minimizing condition on connectivity implied by some relationships among the elements. This condition is satisfied by one and only one element, or class of equivalence in each level of the hierarchy. So it is that very class which matter and consequently the procedure should give control on each class as the total structure is being generated. Once it is known which class satisfies the condition it is possible to avoid generating the whole structure and the subsequent combinatorial explosion. With just This an addition to the previous posting In fact, the thing is even worst. These are the CPU times for the following computations times1=First[Timing[fLPartition[3,10];]]/. Second->1 0.02 times2=First[Timing[fLPartition[3,20];]]/. Second->1 0.18 times3=First[Timing[fLPartition[3,30];]]/. Second->1 0.701 times4=First[Timing[fLPartition[3,40];]]/. Second->1 1.913 times5=First[Timing[fLPartition[3,50];]]/. Second->1 4.236 times6=First[Timing[fLPartition[3,60];]]/. Second->1 8.222 times7=First[Timing[fLPartition[3,70];]]/. Second->1 14.39 times8=First[Timing[fLPartition[3,80];]]/. Second->1 23.563 So far so good. But for times9=First[Timing[fLPartition[3,90];]]/. Second->1 The computation does not always end. Some times it ends some times it does not (I aborted the process four times after 1 hour of computing and running out of, 2Gbites of, virtual memory) Emilio Martin-Serrano ___________________________________ Emilio Martin-Serrano Schlumberger Oil & Gas Business Consulting Principal 1325 South Dairy Ashford Road Houston, TX 77077 ==== 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? Brian ==== This graphs f from 0 to 8 Pi on a logarithmic horizontal scale: f[x_] := 1 + Abs[Sin[x]/x] Plot[f@Exp@x, {x, 0, Log[8Pi]}, PlotRange -> All]; If you want both scales to be logarithmic, use Plot[Log@f@Exp@x, {x, 0, Log[8Pi]}, PlotRange -> All]; The first is always possible if you only have positive x to deal with, and the second is possible if x and y are BOTH positive. Bobby Treat -----Original Message----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== > This graphs f from 0 to 8 Pi on a logarithmic horizontal scale: f[x_] := 1 + Abs[Sin[x]/x] > Plot[f@Exp@x, {x, 0, Log[8Pi]}, PlotRange -> All]; The graph itself is indeed what is desired, but the labelling of the x-axis is then incorrect for a logarithmic scale. For example, regardless of the scale used, any proper graph must show that the first minimum occurs at x = Pi. But the method you suggest makes it seem that it occurs at approx. 1.14 (precisely Log[Pi]). David > -----Original Message----- > ==== Jason, On item #1 I can help you. I have a notebook that explains the basics of creating tables using either TableForm or Gridboxes. Should get you started. It can be downloaded from my Mathematica course web site: http://www.higgins.ucdavis.edu/ECH198.php Use the link for lecture 3. Brian > I'm going to try using Mathematica to typeset some mathematics > because I know that my students would benefit from being able to do > the same., and they'll need someone who can answer their questions, > etc. etc. > > I'm pretty comfortable with some things (e.g., Mathematica's > recognition of latex commands for most characters), and now I'm ready > to push the envelope a bit. > > Q1: How can I typeset a table or array of information (e.g., list of > variables with definitions) so that information in one column is > centered and information in another column is aligned flush left? I > know exactly how I would do this in LaTeX, but I find no information > on how to do this in Mathematica. > > Q2. How can I embed a Quicktime movie into a Mathematica notebook > (e.g., so someone with MathReader can play the animation)? > > That's all for now. ==== > I'm pretty comfortable with some things (e.g., Mathematica's > recognition of latex commands for most characters), and now I'm ready > to push the envelope a bit. > > Q1: How can I typeset a table or array of information (e.g., list of > variables with definitions) so that information in one column is > centered and information in another column is aligned flush left? I > know exactly how I would do this in LaTeX, but I find no information > on how to do this in Mathematica. See Section 2.8.11 of _The Mathematica Book_. http://documents.wolfram.com/v4/MainBook/2.8.11.html At the beginning of that section, you will find a description of the options that one may apply to GridBox[] objects, which are used to construct tables, matrices, and button palettes. More information on the values that these options may take can be found in the front end option documentation. http://documents.wolfram.com/v4/OtherInformation/GridBoxOptions.html With the current selection in your notebook being the table itself, you can use the Option Inspector dialog (with its scope set to selection) to change the ColumnAlignments option to {Center, Left}, which means that first column elements should be centered, and that subsequent columns should be left justified. -- User Interface Programmer paulh@wolfram.com Wolfram Research, Inc. ==== > Stefan, > > To find n digits before the decimal point of a number, we can proceed in the > following way. We compute the number in sufficiently many digits, then take > the Floor of the result (i.e. we round it downwards to an integer) and > finally take the result modulo 10^n. > > Mod[Floor[ N[(Sqrt[2] + Sqrt[3])^2002 , 1000]], 10^2] > > results in 9, so the last two digits before the decimal point are 09. > > With a slight modification we can find the first n digits after the decimal > point. Simply find the last n digits before the decimal point of 10^n times > the number. > > Mod[Floor[ N[10^2 (Sqrt[2] + Sqrt[3])^2002 , 1000]], 10^2] > > results in 99, so these are the digits you are interested in. > > But there is something curious about this number. > > Mod[Floor[N[10^1000 (Sqrt[2] + Sqrt[3])^2002 , 2000]], 10^1000] > > results in 996 digits 9 followed by 7405. > > You can also play with the following command, resulting in the digits around > the decimal point: > > Mod[ N[(Sqrt[2] + Sqrt[3])^2002, 2300], 10^6] > > The decimal expansion of (Sqrt[2]+Sqrt[3])^2002 contains a sequence of > 997 consecutive digits 9. Do you have any idea why? Not unusual. Try other even exponents and there should be large blocks of 9s . Smaller number for small exponents. Some kind of propagation of 9s as the exponent grows. Try other odd values for 3 and the same thing happens for some values. Also for other values for 2. Larry > > Fred Simons > Eindhoven University of Technology > > > > > Reply-To: kuska@informatik.uni-leipzig.de ==== Plot[{x,x^2},{x,-1,1}] may do it. Jens > > How can I plot with Mathematica two function in the same graphic? > I explain better: > compare a and b). > Reply-To: kuska@informatik.uni-leipzig.de ==== it works with any graphics NotebookWrite[SelectedNotebook[], GridBox[{Cell[GraphicsData[PostScript, DisplayString[#, MPS]], Graphics] & /@ {leftGraphics, rightGraphics}}]] Jens > > (1) Is there a way in Mathematica 4.2 to put two separate gifs into a > single, cell side by side (with some intervening space), without > having to combine them in some graphics program first? > > In particular, I'd like to do that within a text cell. > > Even in a new Input cell, if I first create a GridBox (via Inut>Create > Table/Matrix/Palette) and then try to insert the first gif (via > Edit>Insert Object>Create from File ....), Mathematica promptly > crashes. (Mathematica 4.2 under Windows 2000.) > > I just don't see how to get anything other than a single gif into a > cell. > > (2) Is there a way to cause a gif imported into a Mathematica 4.2 > notebook to become a hyperlink -- so that when the user clicks on the > gif the hyperlink's target is summoned? > > (My aim in all this is to use Mathematica to create web pages with > high mathematical content -- saving the notebook as HTML+MathML -- > without having to do any extensive editing of the resulting .xml and > related files. That way as the source Mathematica notebook changes, I > would need only to re-export without further tinkering with the .xml > file, etc.) > > -- > Murray Eisenberg Internet: murray@math.umass.edu > Mathematics & Statistics Dept. Voice: 413-545-2859 (W) > University of Massachusetts 413-549-1020 (H) Reply-To: kuska@informatik.uni-leipzig.de ==== set the PlotRange explicit PlotRange->{{0,largeX},Automatic} Jens > > I am using MultipleListPlot to plot a range of 2D graphs and have found that > the last graph, which has a much greater (by a factor of 4) x range than the > others does not plot completely but is truncated in the x direction. By > removing the Frame, I can see the points where these lie outside the Frame > but these are not joined etc. How do I get over this? > - > Malcolm Woodruff Reply-To: kuska@informatik.uni-leipzig.de ==== what may be in the *.m files? Mathematica commands ? that you can load into the kernel ? Makr all your input cells in the notebook as initialization, save it as an *.m file, add a Quit[] as the last command to the *.m file and run it with math << yourJustGeneratedMFile Jens Regardds > > > Probably a rather simple question: what is the easiest way to open a > notebook, execute it, then quit, from the command line? I would like to be > able to do this from a Makefile. > > > Sidney Reply-To: kuska@informatik.uni-leipzig.de ==== 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}] Jens > > > I've this problem with NIntegrate: > ********************************************** > In[1]=f[y_,z_]: = (y^4/( (1+(8.44*10^-4)^2 * (1+z)^2 y^2) (Exp[z]+1) ) > > In[2]=F[z_]: = NIntegrate[f[y,z], {z, 0, Infinity} > ********************************************** > > Mathematica 4.0 says: > > **************************************************************************** > * > NIntegrate: : inum : Integrand 1.07577/( 1+7.12336*10^-7 (1. + z)^2 ) is not > numerical at {y}={1.}. > **************************************************************************** > ** > > What is it?? > > > -- > Rob_jack ==== do you realy think that 1.07577/( 1+7.12336*10^-7 (1. + z)^2 ) with the z inside is numerical ? or do you mean F[z_?NumericQ]: = NIntegrate[f[y,z], {y, 0, Infinity}] > I'm a newbie, bat I mean: ************************* In[1]= NumericQ[z] Out[1]=False ************************* BTW, z is a real number. -- Rob_jack ==== There is an error in the previous message. This is the just msg: ********************************************** In[1]=f[y_,z_]: = (y^4/( (1+(8.44*10^-4)^2 * (1+z)^2 y^2) (Exp[y]+1) ) In[2]=F[z_]: = NIntegrate[f[y,z], {y, 0, Infinity} ********************************************** Mathematica 4.0 says: **************************************************************************** NIntegrate: : inum : Integrand 1.07577/( 1+7.12336*10^-7 (1. + z)^2 ) is not numerical at {y}={1.}. **************************************************************************** What is it?? Moreover, I have used the following procedure: ****************************************************** If z<<1, f[y,z]=Sum[(-1)^n*a^n*(1+z)^2n *(y^(2n+4)/(Exp[y]+1),{n, 0, N} ] here a=(8.44*10^-4)^2 therefore: F[z]:=Sum[(-1)^n*a^n*(1+z)^2n *(y^(2n+4)/(Exp[y]+1) * Gamma[2 n+5]*Zeta[2 n+5],{n, 0, N} ] this series (N<+oo) only approximates the function for small z, and me it interests the behavior of F for z in the range 800-1300. Thx in advance. Rob_jack ==== > > I've this problem with NIntegrate: > ********************************************** > In[1]=f[y_,z_]: = (y^4/( (1+(8.44*10^-4)^2 * (1+z)^2 y^2) (Exp[z]+1) ) > > In[2]=F[z_]: = NIntegrate[f[y,z], {z, 0, Infinity} > ********************************************** > > Mathematica 4.0 says: > > **************************************************************************** > * > NIntegrate: : inum : Integrand 1.07577/( 1+7.12336*10^-7 (1. + z)^2 ) is not > numerical at {y}={1.}. > **************************************************************************** > ** > > What is it?? > I doubt that you could input your equations as you stated: The first input has a missing ) The second one a missing ] In both equations there should be no space in := Apart from that the second definitions doesn't seem to make much sense, maybe it should be F[y_] := ... Have you assigned y some value before (I get a different error message, when I mix up the y and z as you did.) Good luck Alois -- Vienna University of Technology, A-1040 Wiedner Hauptstr. 8-10 Reply-To: kuska@informatik.uni-leipzig.de ==== not with Mathematica 4.2. But the problem can be the page width that may be used to convert the Cell[], if you can you should use the Graphics[]/Graphics3D[] .. inside the Cell or the PostScript string in the GraphicsData[] Jens > > The following is a button that will export a selected graphic as a JPEG, > > ButtonBox[JPEG, > ButtonFunction : Module[{sel}, > SelectionMove[InputNotebook[], All, Cell]; > sel = NotebookRead[InputNotebook[]]; > If[Head[sel] === Cell, > If[!ValueQ[dpi], dpi = Automatic]; > ImageSize -> Automatic, ImageResolution -> dpi, > ConversionOptions -> {Quality -> 75}]]], > ButtonEvaluator -> Automatic, Active -> True]//DisplayForm > > It works fine as long as the graphic is no wider than about 330 pixels. > If the graphic is wider than 330 pixels, then the size of exported > graphic is correct, but everything on the right beyond the first 330 > pixels is blank. There seems to be no problem with the height though. > > Any ideas on how to fix or get around this problem? > > --- > Selwyn Hollis Reply-To: kuska@informatik.uni-leipzig.de ==== Needs[Graphics`Graphics`] LogPlot[Exp[-x],{x,0,10}] ?? Jens > > ==== <-----Original Message----- >Sent: Wednesday, September 11, 2002 9:28 AM > >A commonly used symbol for the Floor function is a square >bracket with the >upper indents removed. Is this symbol part of Mathematica's >built-in symbols? I >think not, so then, can it be constructed by hand. > >Jack Jack, yes it is already built-in! Bring up the palette with menu: File > Palettes > CompleteCharachters; there is a section Operators > General, where you'll find what you want. Alternatively type 'esc' l f 'esc' 'esc' r f 'esc', or instead of the esc-sequence use the corresponding mark-ups. For output try TraditionalForm. If you don't like that for all of your output, you may just add a formatting rule for Floor: In[7]:= Unprotect[Floor] In[8]:= Floor /: MakeBoxes[Floor[expr_], StandardForm] := RowBox[{[LeftFloor], MakeBoxes[expr, StandardForm], [RightFloor]}] In[9]:= Protect[Floor] In[11]:= Floor /@ ([Pi] + [Lambda]) Out[11]= 3 + [LeftFloor][Lambda][RightFloor] Same thing with Ceiling, BTW. -- Hartmut ==== >-----Original Message----- >Sent: Wednesday, September 11, 2002 9:28 AM >Is it possible to configure a style sheet so that functions or >data shown in >graphs are coloured (colored :)) in working but black in >printing...without >actually re-executing the function that created the graphics? > >thanks > >Mike Mike, if for some reason you can't configure your color printer when printing, you may rerender your graphics in Mathematica with different options, such avoiding costly recalculation. You may either use something special, as in... In[1]:= ContourPlot[Sin[x]^2 Sin[y]^2, {x, 0, Pi}, {y, 0, Pi}, ColorFunction -> Hue, ContourStyle -> GrayLevel[1], PlotPoints -> 100] Out[1]= [SkeletonIndicator]ContourGraphics[SkeletonIndicator] In[2]:= Show[%, ColorFunction -> (GrayLevel[1 - #] &)] ...using a B/W color function. Or in general you may use the option ColorOutput: In[3]:= Plot3D[Sin[x]^2 Sin[y]^2, {x, 0, Pi}, {y, 0, Pi}] Out[3]= [SkeletonIndicator]SurfaceGraphics[SkeletonIndicator] ... In[5]:= Show[%%, ColorOutput -> GrayLevel] -- Hartmut Reply-To: jmt@dxdydz.net ==== mathematica -primaryModifierMask etc see man mathematica for other (very useful) options > PS: One more quick one: Why does the front end act funny when I have the > > Your X server is set up so that the NumLock key is mapped to Mod2. I > learned by accident that Mod2 is actually quite useful. Mod2-click on a > cell selects all cells of that type in the current notebook. This is an > easy way to delete all the graphics cells and output cells in a notebook to > reduce file size. An annoying aspect is that Mod2-click means press > NumLock, click, then press NumLock again to turn it off. You should be able > to map a different key to Mod2 using xmodmap. Remapping modifier keys in X > is awfully annoying, though. I recommend xkeycaps > (http://www.jwz.org/xkeycaps/). > > > Reply-To: kuska@informatik.uni-leipzig.de ==== a Mathematica profiler is described in The Mathematica Journal Volume 5, Issue 3, Summer 1995 The Mathematica Toolbox: A Mathematica Profiler by Todd Gayley The electronic material for this issue isn not on MathSource but it may be that Todd has the code some where and can make is acessible. Jens > > > I have been trying to code Sethian's Fast Marching Method in 2D but Mathematica > has been very slow (taking something like 1-2 hours for something that > should take much less than a second in C++). I am sure part of the problem > my time. > > I looked at the list archives and there was mention of an profiling > package for Mathematica but a)I can't find it & b)It may not work with Mathematica 4.*. > My questions: > 1. Any general suggestions on how to figure out which functions are taking > most of the time? I guess I could manually have each function I am > interested in monitoring keep a variable that counts the amount of CPU > time that has been spent on it by doing something like: > function[args_]:=Module[{},functionTimer+=Timing[ .... My actual function > ..... ][[1]]] > but it would very cumbersome to do this to all of the functions in my > program and I am not sure I will get accurate results anyway. > 2. Compiling functions is not always that easy. I did read the on-line > docs and the archives and it does take some work to make a function > compile usefully. Is there an FAQ or a tutorial somewhere? > 3. Am I the only one who finds the lack of a profiler really really > annoying ? Mathematica is powerful and it is usually easy to ask it to do what u > want. The challenge a lot of times is doing so without taking too long. > > Husain > PS: One more quick one: Why does the front end act funny when I have the ==== > PS: One more quick one: Why does the front end act funny when I have the Your X server is set up so that the NumLock key is mapped to Mod2. I learned by accident that Mod2 is actually quite useful. Mod2-click on a cell selects all cells of that type in the current notebook. This is an easy way to delete all the graphics cells and output cells in a notebook to reduce file size. An annoying aspect is that Mod2-click means press NumLock, click, then press NumLock again to turn it off. You should be able to map a different key to Mod2 using xmodmap. Remapping modifier keys in X is awfully annoying, though. I recommend xkeycaps (http://www.jwz.org/xkeycaps/). ==== 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 ==== Daniel Lichtblau made two suggestions that allow one to use Interpolation the way I wanted. First, to make the resulting function right-continuous, change the sign twice. Second, to make the end point return the correct value, add an extra (phantom) observation (with an extra (irrelevant) value). (The phantom observation is made at the high end because of the sign reversals.) Here's the code I cooked up based on his suggestions: MakeEmpiricalCDF::usage = MakeEmpiricalCDF[list] returns a function that 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}] --Mark > I'm trying to write a fast empirical cummulative distribution function > (CDF). Empirical CDFs are step functions that can be expressed in > terms of a Which statement. For example, given the list of > observations {1, 2, 3}, > > f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]& > > is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1} > and f is continuous from the right. > > When the number of observations is large, the Which statement > evaluates fairly slowly (even if it has been Compiled). Since > InterpolationFunction evaluates so much faster in general, I've tried > to use Interpolation with InterpolationOrder -> 0. The problem is that > the resulting InterpolatingFunction doesn't behave the way (I think) > it ought to. For example, let > > g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder - 0] > > Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}. > In addition, g is continuous from the left rather than from the right. > > Obviously I am not aware of the considerations that went into > determining the behavior of InterpolationFunction when > InterpolationOrder -> 0. > > So I have two questions: > > (1) Does anyone have any opinions about how InterpolatingFunction > ought to behave with InterpolationOrder -> 0? > > (2) Does anyone have a faster way to evaluate an empirical CDF than a > compiled Which function? > > By the way, here's my current version: > > CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := > Block[{x}, Compile[{{x, _Real}}, Evaluate[ > Which @@ Flatten[ > Append[ > Transpose[{ > Thread[x < Sort[list]], > Range[0, 1 - 1/#, 1/#] & @ Length[list] > }], > {True, 1}]] > ]]] > > --Mark ==== I am new to numerical computing. I have a equation dQ/dz = exp(-i*4*a^2*z - i*pi/4)*f(z,t)/sqrt(4*pi*z) where z is the position range from 0 to 10, t is the time range from 0 to 10 f(z,t) = integration of exp(i*(t-t1-z)^2/z)*g(t1) from t1=-100 to 100 g(t1) = d^3 sech(t1) / dt^3 I would like to solve Q(z,t), however, I am a new to mathematica. Can anyone help me? ==== I know that there is an input form. I want the output to have the same form rather than look like Floor[x]. Sorry, Jack A commonly used symbol for the Floor function is a square bracket with the > upper indents removed. Is this symbol part of Mathematica's built-in symbols? I > think not, so then, can it be constructed by hand. Jack Reply-To: kuska@informatik.uni-leipzig.de ==== does MakeBoxes[Floor[x_], fmt_:StandardForm] := RowBox[{[LeftFloor], ToBoxes[x, fmt], [RightFloor]}] help you ? Jens > > I know that there is an input form. I want the output to have the same > form rather than look like Floor[x]. Sorry, > > Jack > > A commonly used symbol for the Floor function is a square bracket with the > upper indents removed. Is this symbol part of Mathematica's built-in symbols? I > think not, so then, can it be constructed by hand. Jack ==== Recent threads about word processing and typesetting have got me dreaming again... Wouldn't it be nice if someone developed a package that provided a function like this: DisplayTeX[ some TeX code ] which would cause the kernel to generate PostScript for the typeset text, to be displayed by the front end? I doubt that WRI will ever consider this, but surely there's someone out there who's both a TeXpert and a Mathematica guru who can do it. No doubt there's money to be made. Probably just a pipe dream... --- Selwyn Hollis Reply-To: kuska@informatik.uni-leipzig.de ==== 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 ... 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. Jens > > Recent threads about word processing and typesetting have got me > dreaming again... > > Wouldn't it be nice if someone developed a package that provided a > function like this: > > DisplayTeX[ some TeX code ] > > which would cause the kernel to generate PostScript for the typeset > text, to be displayed by the front end? > > I doubt that WRI will ever consider this, but surely there's someone out > there who's both a TeXpert and a Mathematica guru who can do it. No > doubt there's money to be made. > > Probably just a pipe dream... > > --- > Selwyn Hollis ==== > > you mean the inverse of TeXForm[] ? > For what ? A TeXpert && Mathematica guru && MathLink expert > has a TeX frontend, that translate a TeXNotebook > (that is a TeX 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. > > Jens > > > >>Recent threads about word processing and typesetting have got me >>dreaming again... >>Wouldn't it be nice if someone developed a package that provided a >>function like this: >> DisplayTeX[ some TeX code ] >>which would cause the kernel to generate PostScript for the typeset >>text, to be displayed by the front end? >>I doubt that WRI will ever consider this, but surely there's someone out >>there who's both a TeXpert and a Mathematica guru who can do it. No >>doubt there's money to be made. >>Probably just a pipe dream... >>--- >>Selwyn Hollis > > ==== Mike, I don't think so. Style sheets do not control the styles used within an output graphics cell. I think you will have to set the plot style as a statement in the notebook, change it and re-evaluate for printing. This might not be all that inconvenient because you probably won't be printing that often. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== Dear MathGroup, To plot FrameTicks outward with the same style as the Frame, I use ExtendGraphics in the following way. Needs[ExtendGraphics`Ticks`]; tf[min_,max_] := TickFunction[min, max, MajorStyle -> {Thickness[0.003]}, MajorLength - > {0, 0.01}, MinorStyle -> {Thickness[0.003]}, MinorLength -> {0, 0.005}] Plot [-2.4 (x+6) (x-8), {x, -6.2, 9.2}, FrameTicks -> {tf, tf, None, None}, AspectRatio -> 18/25, Frame -> True, DefaultFont -> {Helvetica-Bold, 12}, Axes -> None, FrameStyle -> Thickness[0.003], FrameLabel -> {x, y, None, None}, PlotStyle -> Thickness[0.006], ImageSize -> 504]; (instead of the same Plot statement with FrameTicks -> {Automatic, Automatic, None, None}) This arrangement of major and minor ticks is clearly unacceptable. The minor ticks do not divide intervals of adjacent labelled major ticks into equal parts. Are there other solutions? I have noticed that some major statistical (plotting) programs don't do minor ticks at all. Tom Aldenberg RIVM Bilthoven Netherlands ==== I need to create an adjacency matrix from my data, which is currently in the form of a .txt file and is basically a two column incidence list. For example: 1 A 1 B 2 B 3 C . . . . . . m n Where 1 to m represent actors and A to n represent events. My goal is to have an (m x m) matrix where cell i,j equals 1 if two actors are incident to the same event (in the sample above, 1 and 2 are both incident to B) and 0 otherwise (w/ zeros on the diagonal). I'm new to Mathmatica, and so I'm on the steep part of the learning curve ... All I've been able to figure out so far is how to get my incidence list into the program using Import[filename.txt]. But then what? How do I convert to the adjacency matrix? I've found the ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I can't seem to get it to work ... Tom ********************************************** Thomas P. Moliterno Graduate School of Management University of California, Irvine tmoliter@uci.edu ********************************************** Reply-To: kuska@informatik.uni-leipzig.de ==== with In[]:=lst = {{1, A}, {1, B}, {2 , B}, {3, C}, {3, D}, {1, D}}; and In[]:= AdjacenceMatrix[lst : {{_, _} ..}] := Module[ {actors,events adj}, {events, actors} = Union /@ Transpose[lst]; adj = Table[0, {Length[events]}, {Length[actors]}]; Scan[(Part[adj, Sequence @@ #] = 1) &, lst /. MapIndexed[Rule[#1, First[#2]] &, actors]]; adj ] you get In[]:=AdjacenceMatrix[lst] Out[]={{1, 1, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 1}} Jens > > I need to create an adjacency matrix from my data, which is currently in > the form of a .txt file and is basically a two column incidence list. > For example: > > 1 A > 1 B > 2 B > 3 C > . . > . . > . . > m n > > Where 1 to m represent actors and A to n represent events. My goal is to > have an (m x m) matrix where cell i,j equals 1 if two actors are > incident to the same event (in the sample above, 1 and 2 are both > incident to B) and 0 otherwise (w/ zeros on the diagonal). > > I'm new to Mathmatica, and so I'm on the steep part of the learning > curve ... All I've been able to figure out so far is how to get my > incidence list into the program using Import[filename.txt]. But then > what? How do I convert to the adjacency matrix? I've found the > ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I can't > seem to get it to work ... > > > Tom > > ********************************************** > Thomas P. Moliterno > Graduate School of Management > University of California, Irvine > tmoliter@uci.edu > ********************************************** ==== >Probably a rather simple question: what is the easiest way to open a >notebook, execute it, then quit, from the command line? I would like to be >able to do this from a Makefile. actually, this is not as simple as it should be and one needs the extremely useful JLink to really manipulate Notebooks from the similar under MacOSX and even Windows. Maybe others can try this. ================================================= Execute this in the FrontEnd to create a test notebook, then quit the FrontEnd completely: NotebookSave[NotebookPut[Notebook[{ Cell[< Plot3D[Sin[x]*Cos[y], {x, 0, 10}, {y, 0, 10}, PlotLabel -> >, Input], Cell[Integrate[Log[1 - x]^2/(1 + x), {x, 0, 1}], Input] } ]],/tmp/test.nb] (* **************************** *) Next, create a file t.m : [rolf@uranus tmp]$ cat t.m nb = /tmp/test.nb; (* ***************************** *) <, Input], Cell[NotebookSave[en, Interactive -> False], Input]}]]; SelectionMove[m, All, Notebook]; SelectionEvaluate[m]; ]; Pause[1]; (* **************************************** *) Now you can run it like this in the background: [rolf@uranus tmp]$ math < t.m > t.out & This will open /tmp/test.nb , evaluate it and save it under the same name. (* ******************************* *) Maybe there is an easier and cleaner way, but the problem here is that the kernel and the FrontEnd are really two different programs, i.e., the kernel is not waiting until the FrontEnd finished certain tasks (like NotebookSave), i.e., think of it as threads. Therefore I used the trick with a second steering notebook. (One usually has similar problems when writing more intricate buttons.) If you are not, e.g. you work remotely at a Unix-box without an virtual frame buffer (Xvfb), like in webMathematica. ask Wolfram Tech Support. Rolf Mertig Mertig Consulting Efficient Software http://www.mertig.com ==== > I'm curious about the different efficiencies of Export vs. Put; Import vs. > Get. > > Eg. Saving a list called c with approx. 16,000 elements, each element > being a three element list of reals. > > Export[ac.dat,c] takes forever and consumes heaps of kernel memory > > c>>ac.dat all done in an instant (relatively speaking) and without the > transient burst of kernel memory usage. > > Ditto Import and Get. Can anyone explain this? The comparison is that of apples and oranges. Get[] and Put[] deal with reading and writing Mathematica expressions in InputForm syntax. They are implemented in C, so they are fairly fast, and the target format is human readable. However the output might not be readily parsable by other computer programs. The functions may be used with Mathematica expressions of all kinds. In the event that human readability and platform independence are not important, one can use DumpSave[] in lieu of Put[]. Export[] and Import[] for the cases you describe are using the Table target format. They are implemented in top-level Mathematica code, so they are not as fast as Get[] and Put[]. The target is a regularly formatted array of data, so not all Mathematica expressions are appropriate for this kind of conversion. In the case of Export[], the expression is formatted completely in memory using TableForm[] before being saved out to file. In the case of Import[], there are a number of heuristics that are applied to each field to determine whether the field should be converted to a number or a string. This should explain why they are slower and require more memory. If you are dealing with a large collection of machine precision numbers, then neither of these approaches may be suitable for your purposes. You might be better off using the free add-on FastBinaryFiles, which is available up on MathSource at this URL: readable by C programs. -- User Interface Programmer paulh@wolfram.com Wolfram Research, Inc. ==== > A commonly used symbol for the Floor function is a square bracket with > the upper indents removed. Is this symbol part of Mathematica's > built-in symbols? I think not, so then, can it be constructed by > hand. Is this what you're describing? In[1]:= [LeftFloor]x[RightFloor] Out[1]= Floor[x] This notation is documented in Section A.2.6 of _The Mathematica Book_ (Fourth Edition). -- User Interface Programmer paulh@wolfram.com Wolfram Research, Inc. ==== Jack, Check pages 959 and 960 in Section 3.10.4 of The Mathematica Book. You can use LeftFloor and RightFloor as bracketing operators, which in turn are intrepreted as Floor. [LeftFloor] 3.2 [RightFloor] 3 These can also be entered as esc-lf-esc and esc-rf-esc. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== Hugh Goyder and David Park gave a most elegant function to find two vectors that are orthogonal to one vector in 3D. The key to coming up with the elegant solution is an understanding of Mathematica's NullSpace function. We can easily make the version from Hugh and David much more general with the version below. ------------- OrthogonalUnitVectors[vect__?VectorQ]:= #/Sqrt[#.#]&/@NullSpace[{vect}] ------------- The version above will give a set of unit orthogonal vectors if given any number of vectors in any dimension. So besides giving it a 3D vector we can give it the following: OrthogonalUnitVectors[{2,1,0,-1,1}] or OrthogonalUnitVectors[{0,1,0,1/2,1},{1,0,-1,1/2}] ------------ But the short version above isn't very robust. (1) Clear[x,y,z];NullSpace[{{x,y,z}}] returns two vectors orthogonal to {x,y,z}, but the two vectors NullSpace returns aren't orthogonal to each other. So (OrthogonalUnitVectors) should only work with numeric vectors. (2) We should ensure all the vectors have the same dimension and length >1. I give a less concise version below that corrects these problems. ------------ OrthogonalUnitVectors[vect__?(VectorQ[#,NumericQ]&)]/; (SameQ@@Length/@{vect})&&(Length[First[{vect}]]>1):= #/Sqrt[#.#]&/@NullSpace[{vect}] -------------- Ted Ersek Get Mathematica tips, tricks from http://www.verbeia.com/mathematica/tips/Tricks.html ==== I have installed 128 MB RAM extra in my computer. I had 64 before, so now I have 3 times as much. I expected some calculations that took very long before, to be executed in less time. To the contrary, my computer still goes to the hard drive fro memory for its calculations, and Mathematica stops with an out of memory message. Windows is recognizing this new memory. I dont know if Mathematica is. How can I find out about this? Julio ==== > It seems there is an error in the BinCounts function of Mathematica's > standard < returns one more than the expected number of histogram bins. An example > of this is shown in the notebook code below where the comment in the > last notebook cell explicitly describes the problem. If anyone can > explain this behavior it would be appreciated, otherwise Wolfram > Research should be made aware of this feature of the function when it > is called as: BinCounts[{x1, x2, ...}, {xmin, xmax, dx}] A developer of Mathematica's Standard Packages has requested that this response be posted to the forum: [begin developer's comments] Note that if you don't apply N when computing datBinWidth, you will always get the expected number of bins; i.e., datBinWidth = (datMax - datMin)/datBins (assuming datMax and datMin are also exact numbers). Given input {xmin, xmax, dx}, BinCounts determines the number of bins to be computed via Ceiling[(xmax - xmin)/dx]. For numericalized values, it's possible for dx to end up such that the Ceiling forces an additional bin to be added; presumably, it's better to have too many rather than too few bins -- for example, if the dx was deliberately given such that the xmax is not at an integer bin boundary... If you use exact values for bin bounds and increment, then there will be no problem. [end developer's comments] -- User Interface Programmer paulh@wolfram.com Wolfram Research, Inc. ==== I would like to create a 3D chart from an ASCII file using Mathematica 3.0. Can anyone give me some help? ==== You might want to tell us how to find A.10. Anyway, it's easier to simply go to Floor in the help browser (in version 4.2, anyway). Bobby Treat -----Original Message----- David ==== I doubt there's any money to be made here. Lots of people have created very valuable additions to Mathematica, but they're all being given away, so far as I can tell. It's too bad, too. And here we are, giving away our time. Sigh... Bobby -----Original Message----- there who's both a TeXpert and a Mathematica guru who can do it. No doubt there's money to be made. Probably just a pipe dream... --- Selwyn Hollis ==== OK, I give up; how would I find Chapter Advanced Mathematics/Mathematical and Other Notations/Operators in the Help Browser? Bobby Treat -----Original Message----- > think not, so then, can it be constructed by hand. > > Jack [LeftFloor] and [RightFloor] can be used for this. Look at Chapter Advanced Mathematics/Mathematical and Other Notations/ Operators. Yours, Alexander -- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern / ==== > You might want to tell us how to find A.10. Open your fourth edition of _The Mathematica Book_ to page 1065. That's where part 10 of the Appendix starts. > Anyway, it's easier to simply go to Floor in the help browser (in > version 4.2, anyway). I suppose you're right. But I -- call me old-fashioned if you wish -- prefer to use the book. David ==== I'll assume you have the information in a matrix like x: TableForm[x = {{1, A }, {1, B }, {2, B}, {3, D}, {4, D}, {5, C}}] First find the highest actor number (or use what you've input elsewhere): m = Last[Union[x[[All,1]]]] 5 Define the incidence function: f[x_, a_, b_] /; a == b := 0 f[x_, a_, b_] := If[{} $B!b(B Intersection[Cases[x, {a, y_} -> y], Cases[x, {b, y_} -> y]], 1, 0] Here's the incidence matrix: Array[f[x, #1, #2] &, {m, m}] {{0, 1, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, { 0, 0, 0, 0, 0}} Once you have the incidence function, the only reason to store the incidence matrix is to avoid computing over again the same answers, and that can be accomplished in other ways. If you won't have other x matrices, it's convenient to define f this way: f[a_, b_] /; a == b := f[a, b] = 0 f[a_, b_] /; a < b := f[a, b] = If[{} $B!b(B Intersection[Cases[x, {a, y_} -> y], Cases[x, {b, y_} -> y]], 1, 0] f[a_, b_] := f[b, a] Array[f, {m, m}] {{0, 1, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}} Whenever you would want the {j,k} element of the adjacency matrix, just use f[j,k] instead. Each pair is computed only once. In this version, I've taken advantage of the symmetry of the problem, too, to cut the work in half. Bobby Treat -----Original Message----- . . . . m n Where 1 to m represent actors and A to n represent events. My goal is to have an (m x m) matrix where cell i,j equals 1 if two actors are incident to the same event (in the sample above, 1 and 2 are both incident to B) and 0 otherwise (w/ zeros on the diagonal). I'm new to Mathmatica, and so I'm on the steep part of the learning curve ... All I've been able to figure out so far is how to get my incidence list into the program using Import[filename.txt]. But then what? How do I convert to the adjacency matrix? I've found the ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I can't seem to get it to work ... Tom ********************************************** Thomas P. Moliterno Graduate School of Management University of California, Irvine tmoliter@uci.edu ********************************************** ==== Well, I don't know how fast, but it is fairly simple, anyway. Suppose you have a series of values s for which you wish to obtain the edf. In[1]:= s = Table[Random[Integer, {0, 3}], {10}] Out[1]= {2,2,1,2,0,0,1,1,1,3} If no specification is made about their position on the x-axis, we assume that they correspond to the integers from 1 to 10. What we have then is the collection of pairs In[2]:= porig = Transpose[{Range[10], s}] Out[2]= {{1, 2}, {2, 2}, {3, 1}, {4, 2}, {5, 0}, {6, 0}, {7, 1}, {8, 1}, {9, 1}, {10, 3}} The edf gives, for each x, the proportion of points in s that are less than or equal to x, for all x. We obtain these proportions through the cumulative sums In[3]:= N[CumulativeSums[s]/Plus @@ s] Out[3]= {0.153846,0.307692,0.384615,0.538462,0.538462,0.538462,0.615385,0.692308,0. 769231,1.} so that for each of the pairs (x, y) below, y gives the proportion of points in s that are less than or equal to x: In[4]:= cumporig = Transpose[{Range[10], N[CumulativeSums[s]/Plus @@ s]}] Out[4]= {{1, 0.15384615384615385}, {2, 0.3076923076923077}, {3, 0.38461538461538464}, {4, 0.5384615384615384}, {5, 0.5384615384615384}, {6, 0.5384615384615384}, {7, 0.6153846153846154}, {8, 0.6923076923076923}, {9, 0.7692307692307693}, {10, 1.}} Now shift the x values one unit to the left, by dropping the last value and prepending 0 to them: In[5]:= ps = Transpose[{Prepend[Drop[Range[1, 10], -1], 0], CumulativeSums[s]/Plus @@ s}] Out[5]= {{0, 2/13}, {1, 4/13}, {2, 5/13}, {3, 7/13}, {4, 7/13}, {5, 7/13}, {6, 8/13}, {7, 9/13}, {8, 10/13}, {9, 1}} Then use Interpolation on this shifted set of points: In[6]:= ips=Interpolation[ps,InterpolationOrder[Rule]0] Out[6]= InterpolatingFunction[{{0,9}},<>] ips[x-1] is the edf you are looking for, as you may check by plotting it and displaying in the same graph together with the ListPlot of cumporig above. Tomas Garza Mexico City ----- Original Message ----- > and f is continuous from the right. When the number of observations is large, the Which statement > evaluates fairly slowly (even if it has been Compiled). Since > InterpolationFunction evaluates so much faster in general, I've tried > to use Interpolation with InterpolationOrder -> 0. The problem is that > the resulting InterpolatingFunction doesn't behave the way (I think) > it ought to. For example, let g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder - 0] Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}. > In addition, g is continuous from the left rather than from the right. Obviously I am not aware of the considerations that went into > determining the behavior of InterpolationFunction when > InterpolationOrder -> 0. So I have two questions: (1) Does anyone have any opinions about how InterpolatingFunction > ought to behave with InterpolationOrder -> 0? (2) Does anyone have a faster way to evaluate an empirical CDF than a > compiled Which function? By the way, here's my current version: CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := > Block[{x}, Compile[{{x, _Real}}, Evaluate[ > Which @@ Flatten[ > Append[ > Transpose[{ > Thread[x < Sort[list]], > Range[0, 1 - 1/#, 1/#] & @ Length[list] > }], > {True, 1}]] > ]]] --Mark ==== I have no opinion on the behavior associated with InterpolationOrder->0, except that it should be DOCUMENTED, but isn't. Meanwhile, try this: lst = {{1, 1/3}, {2, 2/3}, {3, 1}}; ClearAll[empiricalCDF] empiricalCDF[{x_List, y_List}] := Compile[ {{z, _Real}}, Evaluate[ Which @@ Flatten[ Transpose[ {(z < #1 & ) /@ x, y}]]]] empiricalCDF[v:{{_, _}..}] := empiricalCDF[v] = empiricalCDF[ ({Join[#1[[1]], {Infinity}], Join[{0}, #1[[ 2]]]} & )[Transpose[ lst]]] empiricalCDF[lst] Plot[empiricalCDF[lst][x], {x, 1, 3}]; I split the work into two definitions for readability. If you evaluate: ?empiricalCDF after doing the plot above, you'll see that empiricalCDF[{{1, 1/3}, {2, 2/3}, {3, 1}}] has been compiled and saved for later use, and that it takes precedence over the SetDelayed rules listed after it. Hence, the compilation only occurs once for each list. As written, your CompileEmpiricalCDF would be compiled all over again every time it's used -- for each and every point you plot -- so of course it's slow. There are other problems, too. For instance, the pattern list_?(VectorQ[#, NumericQ] &) makes no sense at all. Maybe you meant list_?And[VectorQ[#],NumericQ[#]]& Bobby Treat -----Original Message----- 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 ==== Try deleting ... Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nb > Your machine information and OS EXACTLY matches mine (except that my pagefile > is NOT on a separate physical drive -- perhaps this is a clue as to where to start), > and I had no problem building the help file. Hence, as you say, this must > be a problem for Wolfram to address. Perhaps, someone from WRI will enlighten > us via this newsgroup. > ....Terry I too have been unable to get the help browser functioning. I have > exactly the same problem. When trying to open the help browser it gets > to the point where it says scanning index file and freezes. I tried > all the suggestions in the faq and the links provided here to no > avail. I'm running Winows 2000 with service pack 3. I have 512mb of > memory with a 768mb pagefile on a separate drive, so I don't think > that's an issue. Mathematica 4.1 ran just fine on this setup, so > judging by the number of other people affected by this, I'd say it's > some kind of bug with 4.2. Hopefully Wolfram will address this with > either a link that will provide a fix that actually works, or a patch. >What is your operating system? How much memory do you have in your machine? > >Also, how big is your pagefile? Sounds to me like the rebuild ran out > >of room to do its thing in. I just installed Mathematica 4.2, and had no problem rebuilding the help index. > >Subsequently, I ahd no problem using the Help browser either. > >Hope that helps! >....Terry >> >I'd start with the following FAQ. >> >http://support.wolfram.com/mathematica/interface/helpbrowser/howrebuildinde x.html >>-Dale >> Sorry that i failed say it immediately in a first place, but of course >> i did try it FAQ at first, and both tried to delete cache and rebuild >> index, but results where the same - whenever i try to invoke help >> browser (or rebuild index, for that matter), mathematica stops >> responding (i did read your answer to the same question asked >> a week ago before - actually that is why i turned to the FAQ). > ==== >Try deleting ... >Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nb > > ==== Simplify: 5nth sqrt (3)/sqrt (6) 5nth Sqrt(3) ------------ Sqrt(6) 1st.. is this the correct notation for use on a computer 2nd.. how is the solution solved, step by step please. Reply-To: kuska@informatik.uni-leipzig.de ==== > Simplify: > > 5nth sqrt (3)/sqrt (6) > > 5nth Sqrt(3) > ------------ > Sqrt(6) > > 1st.. is this the correct notation for use on a computer No. May be you mean 3^(1/5)/Sqrt[6] ?? > > 2nd.. how is the solution solved, step by step please. 3^(1/5)/Sqrt[6] // FullSimplify Jens ==== I want to make a list of all symbols in the Global context, as 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 Reply-To: kuska@informatik.uni-leipzig.de ==== whats wrong with ToExpression[#, StandardForm, Hold] & /@ Names[Global`*] /. Hold[a_] :> ByteCount[OwnValues[a]] Jens > > I want to make a list of all symbols in the Global context, as in > > Names[Global`*] > > and compute a ByteCount for each symbol's OwnValues -- without > evaluating the symbols. > > It seems possible in principle, but I haven't found a way. > > Bobby Treat ==== with the following Java comands you can execute any Mathematica commands: ml.putFunction(EnterTextPacket, 1); ml.put(string); See JLinkUserGuide p. 164. Hermann Schmitt ----- Original Message ----- > I've checked the documentation on Wolfram, but did not find the 'hook' > for ReadList from java. Any help would be appreciated. thanks. > > Pete > > > ==== I want to use the capability of mathematica from java. This is what I want to do: I want to read a data set and use ReadList to structure it into an array and then plot that data set with the output as a .gif. Any ideas? I've checked the documentation on Wolfram, but did not find the 'hook' for ReadList from java. Any help would be appreciated. thanks. Pete ==== Dear Mark, I suggest trying the following code before you put further energy in speeding up your functions. My code is very short and seems to be fast in my first test with a random array of 100000 integers. cdf[li_List]:= FoldList[#1+Length[#2]&, 0.0, Split[Sort[li]]]/Length[li] t=Table[Random[Integer,{1,1000}],{100000}]; Timing[cdf[t];] {0.44 Second,Null} Probably the speed could be increased further generating a compiled version. But this would require additional programming effort. Then you had to write a function which counts the number of equal data 'by hand' while scanning through the data list. Johannes > I'm trying to write a fast empirical cummulative distribution function > (CDF). Empirical CDFs are step functions that can be expressed in > terms of a Which statement. For example, given the list of > observations {1, 2, 3}, > > f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]& > > is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1} > and f is continuous from the right. > > When the number of observations is large, the Which statement > evaluates fairly slowly (even if it has been Compiled). Since > InterpolationFunction evaluates so much faster in general, I've tried > to use Interpolation with InterpolationOrder -> 0. The problem is that > the resulting InterpolatingFunction doesn't behave the way (I think) > it ought to. For example, let > > g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder - 0] > > Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}. > In addition, g is continuous from the left rather than from the right. > > Obviously I am not aware of the considerations that went into > determining the behavior of InterpolationFunction when > InterpolationOrder -> 0. > > So I have two questions: > > (1) Does anyone have any opinions about how InterpolatingFunction > ought to behave with InterpolationOrder -> 0? > > (2) Does anyone have a faster way to evaluate an empirical CDF than a > compiled Which function? > > By the way, here's my current version: > > CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := > Block[{x}, Compile[{{x, _Real}}, Evaluate[ > Which @@ Flatten[ > Append[ > Transpose[{ > Thread[x < Sort[list]], > Range[0, 1 - 1/#, 1/#] & @ Length[list] > }], > {True, 1}]] > ]]] > > --Mark > <><><><><><><><><><><><> Johannes Ludsteck Economics Department University of Regensburg Universitaetsstrasse 31 93053 Regensburg ==== >-----Original Message----- >Sent: Wednesday, September 11, 2002 7:28 PM >Dear MathGroup, > >To plot FrameTicks outward with the same style as the Frame, I use >ExtendGraphics in the following way. > >Needs[ExtendGraphics`Ticks`]; > >tf[min_,max_] := TickFunction[min, max, MajorStyle -> >{Thickness[0.003]}, > MajorLength - > {0, 0.01}, MinorStyle -> {Thickness[0.003]}, >MinorLength -> {0, 0.005}] > >Plot [-2.4 (x+6) (x-8), {x, -6.2, 9.2}, FrameTicks -> {tf, tf, >None, None}, >AspectRatio -> 18/25, Frame -> True, DefaultFont -> >{Helvetica-Bold, 12}, >Axes -> None, >FrameStyle -> Thickness[0.003], FrameLabel -> {x, y, None, None}, >PlotStyle -> Thickness[0.006], >ImageSize -> 504]; (instead of the same Plot statement with FrameTicks -> {Automatic, >Automatic, None, None}) > >This arrangement of major and minor ticks is clearly unacceptable. The >minor ticks do not divide > intervals of adjacent labelled major ticks into equal parts. > >Are there other solutions? I have noticed that some major statistical >(plotting) programs don't do minor ticks at all. > >Tom Aldenberg >RIVM >Bilthoven >Netherlands Several alternatives (if the default ticks of Plot, Show that is, wouldn't do): (1) generate the ticks explicitly (to get control over supplied min, max values for TickFunction): yticks = tf[-40., 120.] xticks = tf[-6.2, 9.2] Plot[-2.4 (x + 6) (x - 8), {x, -6.2, 9.2}, FrameTicks -> {xticks, yticks, None, None}, ...] (2) try the Option TickNumbers, e.g. tf[min_, max_] := TickFunction[min, max, MajorStyle -> {Thickness[0.005]}, MajorLength -> {0, 0.01}, MinorStyle -> {Thickness[0.003]}, MinorLength -> {0, 0.005}, TickNumbers -> {5, 25}] gives an acceptable result, or TickNumbers -> {6, 18}; with TickNumbers -> {8, 8} you'll have no minor ticks. (3) redefine the tick function's helper Begin[ExtendGraphics`Ticks`Private`] ?? TickPosition TickPosition[ min, max, num] returns a list of at most num nicely rounded positions between min and max. These can be used for tick mark positions. TickPosition[x0_Real, x1_Real, (num_Integer)?Positive] := Block[{dist, scale, min, max, i, delta, space}, space = {1., 2., 2.5, 5., 10.}; dist = (x1 - x0)/num; scale = 10.^Floor[Log[10, dist]]; dist = dist/scale; If[dist < 1., dist *= 10.; scale /= 10.]; If[dist >= 10., dist /= 10.; scale *= 10.]; delta = First[Select[space, #1 >= dist & ]]*scale; min = Ceiling[x0/delta]*delta; Table[Floor[x/delta + 0.5]*delta, {x, min, x1, delta}]] End[] There are some things to play with: space, scale, the definition for delta, to get at more nicely rounded positions; or rewrite completely. (4) for best control, define the ticks all by yourself, e.g. yticks1 = Table[{t, t, {0, 0.01`}, {Thickness[0.003`]}} , {t, -25, 100, 25}] yticks2 = DeleteCases[ Table[{t, , {0, 0.005`}, {Thickness[0.003`]}} , {t, -25, 100, 12.5}], {t_, __} /; Mod[t, 25] == 0] xticks = Join[xticks1, xticks2] xticks1 = Table[{t, t, {0, 0.01`}, {Thickness[0.003`]}} , {t, -5, 7.5, 2.5}] xticks2 = DeleteCases[ Table[{t, , {0, 0.005`}, {Thickness[0.003`]}} , {t, -7.5, 8.5, 1.25}], {t_, __} /; Mod[t, 2.5] == 0] yticks = Join[yticks1, yticks2] -- Hartmut Wolf ==== > I need to create an adjacency matrix from my data, which is currently in > the form of a .txt file and is basically a two column incidence list. > For example: > > 1 A > 1 B > 2 B > 3 C > . . > . . > . . > m n Past the following notebook into Mathematica. Tom Burton Notebook[{ Cell[CellGroupData[{ Cell[Preparing an adjacency matrix, Section], Cell[< This notebook was prepared with the default cell output format type set to TraditionalForm. Then the output cells were removed to saved space. I recommend that execute this entire notebook before editing it. >, Text], Cell[CellGroupData[{ Cell[Introduction, Subsection], Cell[< Given the list of pairs of actors and events, it appears that most of the work is in preparing the associated list of undirected edges. So if you want only an adjacency matrix, it is perhaps more trouble that it's worth to prepare the associated graph. But the graph is nice, so I am showing both methods. >, Text] }, Open ]], Cell[CellGroupData[{ Cell[The structure of a graph, Subsection], Cell[< We need to investigate the structure of a graph so we can make our own graph. >, Text], Cell[BoxData[ (<< DiscreteMath`Combinatorica`)], Input], Cell[Start with the simplest graph:, Text], Cell[BoxData[ (aa = CompleteGraph[2])], Input], Cell[BoxData[ (InputForm[aa])], Input], Cell[< It appears to be a list of undirected edges followed by a list of vertices, each element of which is wrapped in an extra pair of braces. Let's try it: >, Text], Cell[BoxData[ (bb = Graph[{{{1, 2}}}, {{{(-1. ), 0}}, {{1. , 0}}}])], Input], Cell[BoxData[ (ToAdjacencyMatrix[aa])], Input], Cell[BoxData[ (ToAdjacencyMatrix[bb])], Input] }, Open ]], Cell[CellGroupData[{ Cell[Example of a list of actor-event pairs, Subsection], Cell[BoxData[ (data = {{1, }, {4, }, {3, }, {1, }, {1, }, {3, }, {2, }, {2, }})], Input], Cell[< Get the number of actors, which will be the dimension of the matrix and the number of vertices in the graph. >, Text], Cell[BoxData[ (d = Max[data[([All, 1])]])], Input] }, Open ]], Cell[CellGroupData[{ Cell[Getting the list of edges, Subsection], Cell[TextData[{ Given the list of actors and actions, this is most of the work. I'll do it in baby steps, as I would like to see were I new to , StyleBox[Mathematica, FontSlant->Italic], . It could be done more directly. }], Text], Cell[Put events first., Text], Cell[BoxData[ (data2 = Reverse /@ data)], Input], Cell[Group by event, with increasing actors within each event., Text], Cell[BoxData[ (data3 = Sort[data2])], Input], Cell[BoxData[ (data4 = Split[data3, First[#1] == First[#2] &])], Input], Cell[Remove isolated pairs., Text], Cell[BoxData[ (data5 = DeleteCases[data4, {{_, _}}])], Input], Cell[Drop the actions., Text], Cell[BoxData[ (data6 = data5[LeftDoubleBracket]All, All, 2[RightDoubleBracket])], Input], Cell[< Edges are all subsets of connected vertices taken two at a time: >, Text], Cell[BoxData[ (data7 = (KSubsets[#, 2] &) /@ data6)], Input], Cell[Collect edges into one list, Text], Cell[BoxData[ (data8 = Flatten[data7, 1])], Input], Cell[and remove duplicates, Text], Cell[BoxData[ (onedir = Union[data8])], Input] }, Open ]], Cell[CellGroupData[{ Cell[Adjacency matrix via a list of edges using MapAt, Subsection], Cell[Convert to directed edges, Text], Cell[BoxData[ (bothdir = Join[onedir, Reverse /@ onedir])], Input], Cell[< and finally, construct the adjacency matrix, putting 1's into elements corresponding to directed edges: >, Text], Cell[BoxData[ (emptymat = Table[0, {d}, {d}])], Input], Cell[BoxData[ (adjmat = MapAt[1 &, emptymat, bothdir])], Input] }, Open ]], Cell[CellGroupData[{ Cell[Adjacency matric via ToAdjacencyMatrix, Subsection], Cell[Construct a set of vertices for display, Text], Cell[BoxData[ (verts = Table[{Cos[2 [Pi] j/d], Sin[2 [Pi] j/d]}, {j, d}])], Input], Cell[< Prepare graph, adding extra braces and making the coordinates of the vertices real numbers (this appears to be necessary) >, Text], Cell[BoxData[ (g = Graph[List /@ onedir, N[List /@ verts]])], Input], Cell[Check our handiwork:, Text], Cell[BoxData[ (InputForm[g])], Input], Cell[BoxData[ ((ShowGraph[g];))], Input], Cell[BoxData[ (ToAdjacencyMatrix[g])], Input] }, Open ]] }, Open ]] }, ScreenRectangle->{{43, 1152}, {0, 746}}, WindowSize->{565, 624}, WindowMargins->{{243, Automatic}, {48, Automatic}} ] ==== I have a notebook that will become a web page. I want to have a logo GIF at the top. My first thought was that I could drag and drop a GIF into a cell in the notebook, but that does not work. I can Import a GIF and Show it. This creates an input cell, the GIF, and an output cell. I don't want the input cell and the output cell to show when the HTML code is created. How can I do this? Tom Compton ==== Instead of using Legend in plots with multiple series is there a way to have arrows with a text at the end identifying the different series? The reason I'd like this is that the legend is a bit 'bulky' looking and I'd want something tidier. I know there is an Arrow package but I think you'd need to manually enter each start and end point of each arrow - is there a simple command to do this? Also - is there a way to adjust the legend font size? I.e. make it small so that it doesn't interfere with data series. _ | thankyou Reply-To: kuska@informatik.uni-leipzig.de ==== Needs[Graphics`Arrow`] Plot[{Sin[x], Cos[x]}, {x, 0, 2Pi}, Epilog -> {{GrayLevel[0.9], Rectangle[{3.75, 0.25}, {5.2, 0.9}]}, Arrow[{4, 0.75}, {2, Sin[2]}], Text[Sin[x], {4, 0.75}, {-1, 0}], Arrow[{4, 0.5}, {2, Cos[2]}], Text[Cos[x], {4, 0.5}, {-1, 0}]}] Jens > > Instead of using Legend in plots with multiple series is there a way > to have arrows with a text at the end identifying the different > series? The reason I'd like this is that the legend is a bit 'bulky' > looking and I'd want something tidier. > > I know there is an Arrow package but I think you'd need to manually > enter each start and end point of each arrow - is there a simple > command to do this? > > Also - is there a way to adjust the legend font size? I.e. make it > small so that it doesn't interfere with data series. > _ > | > > > > > thankyou ==== >-----Original Message----- >I'm trying to write a fast empirical cummulative distribution function >(CDF). Empirical CDFs are step functions that can be expressed in >terms of a Which statement. For example, given the list of >observations {1, 2, 3}, > >f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]& > >is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1} >and f is continuous from the right. > >When the number of observations is large, the Which statement >evaluates fairly slowly (even if it has been Compiled). Since >InterpolationFunction evaluates so much faster in general, I've tried >to use Interpolation with InterpolationOrder -> 0. The problem is that >the resulting InterpolatingFunction doesn't behave the way (I think) >it ought to. For example, let > >g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder -0] > >Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}. >In addition, g is continuous from the left rather than from the right. > >Obviously I am not aware of the considerations that went into >determining the behavior of InterpolationFunction when >InterpolationOrder -> 0. > >So I have two questions: (1) Does anyone have any opinions about how InterpolatingFunction >ought to behave with InterpolationOrder -> 0? (2) Does anyone have a faster way to evaluate an empirical CDF than a >compiled Which function? > >By the way, here's my current version: > >CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := > Block[{x}, Compile[{{x, _Real}}, Evaluate[ > Which @@ Flatten[ > Append[ > Transpose[{ > Thread[x < Sort[list]], > Range[0, 1 - 1/#, 1/#] & @ Length[list] > }], > {True, 1}]] > ]]] --Mark > Mark, as to (1) I don't know, but following your observation, and regarding ff = CompileEmpiricalCDF[{1, 2, 3}] Plot[ff[x], {x, 0, 4}, PlotRange -> {All, {0, 1}}] as a correct CDF, we get something quite similar with obs = {1, 2, 3} t = With[{n = Length[obs]}, Transpose[{Append[obs, Last[obs] + 1], Range[0, 1, 1/n]}]] g = Interpolation[t, InterpolationOrder -> 0] Off[InterpolatingFunction::dmval] Plot[g[x], {x, -1, 5}, PlotRange -> All] See that all values are shifted by one place, zero must be defined and one point added to the right. Now, comparing ff /@ ({0, 1, 2, 3, 4}) {0., 0.333333, 0.666667, 1., 1.} g /@ ({0, 1, 2, 3, 4}) {0, 1/3, 1/3, 2/3, 1} We get something wrong for g, but for g /@ ({0, 1, 2, 3, 4} + 2$MachineEpsilon) {0, 1/3, 2/3, 1, 1} obviously is all right. So we ran into problems of numerical precision. Now, what is the sense of the CDF at the point of jump? None I'd say, at some point above the jump it must count for the fraction of all events below in respect to over all. And this is done within the limits of numerical precision. Conceptionally the CDF is function used to integrate as a Stieltjes Integral, so only interpretations in this contex are possible, and you have to look at the limit from above (within the confines of numerical precision), all ok, I think. To dig up a bigger sample: << Statistics`ContinuousDistributions` gdist = GammaDistribution[3, 1] cdfunction = CDF[gdist, x] pTheory = Plot[cdfunction, {x, 0, 10}, PlotStyle -> Hue[.7]] data = RandomArray[gdist, 1000]; t = With[{n = Length[data], obs = Sort[data]}, Transpose[{Append[obs, Last[obs] + 1], Range[0, 1, 1/n]}]]; g = Interpolation[t, InterpolationOrder -> 0] pExperiment = Plot[g[x], {x, 0, 10}, PlotPoints -> 200] Show[pExperiment, pTheory] Nice comparison! ff = CompileEmpiricalCDF[Sort[data]]; pExperiment2 = Plot[ff[x], {x, 0, 10}, PlotStyle -> {Hue[.4, 1, .5], Thickness[.003]}, PlotPoints -> 200] Show[pTheory, pExperiment2, pExperiment] I couldn't see any differences between pExperiment and pExperiment2 enlarged. Timings: rx = Table[Random[Real, {0, 10}], {10000}]; (s1 = g /@ rx); // Timing {1.082 Second, Null} (s2 = ff /@ rx); // Timing {28.39 Second, Null} s1 == s2 True So, I think, with deliberate use, your observation can be well exploited as (2)! -- Hartmut Wolf ==== First of all, Import is not really meant for this sort of situation; it is better to use ReadList. Suppose your file is: 1 A 1 B 2 B 3 C 4 B 5 D 5 E 6 F 7 A and its name is adj.txt. Here is one way you can deal with this case. First, read in the file: In[1]:= ss=ReadList[adj.txt,{Number,Word}] Out[1]= {{1,A},{1,B},{2,B},{3,C},{4,B},{5,D},{5,E},{6,F},{7,A}} Next, find how many actors there are: In[2]:= l=Length[Union[First[Transpose[ss]]]] Out[2]= 7 Construct the adjacency matrix: In[3]:= Table[If[Intersection[Cases[ss,{i,x_}->x,{1}], Cases[ss,{j,x_}->x,{1}]]=!={},1,0](1-KroneckerDelta[i,j]),{i, l},{j,l}]//MatrixForm Out[3]//MatrixForm= 0 1 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 The function ToAdjacencyMatrix form the Combinatorica package constructs the adjacency matrix from a graph, so it has no direct application to your problem. Andrzej Kozlowski Toyama International University JAPAN > I need to create an adjacency matrix from my data, which is currently > in > the form of a .txt file and is basically a two column incidence list. > For example: 1 A > 1 B > 2 B > 3 C > . . > . . > . . > m n Where 1 to m represent actors and A to n represent events. My goal is > to > have an (m x m) matrix where cell i,j equals 1 if two actors are > incident to the same event (in the sample above, 1 and 2 are both > incident to B) and 0 otherwise (w/ zeros on the diagonal). I'm new to Mathmatica, and so I'm on the steep part of the learning > curve ... All I've been able to figure out so far is how to get my > incidence list into the program using Import[filename.txt]. But then > what? How do I convert to the adjacency matrix? I've found the > ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I can't > seem to get it to work ... > Tom ********************************************** > Thomas P. Moliterno > Graduate School of Management > University of California, Irvine > tmoliter@uci.edu > ********************************************** > ==== When I click on The Mathematica Book, I see no chapters, no chapter already fully expanded and there were chapter numbers next to the chapter names. Anyway, what is Floor doing in a chapter on Advanced Mathematics? Why isn't there a chapter on notation? I suppose that's why an unexpanded If you Go To notation or notations, there's no link to Mathematical and Other Notations. notation and notations yield different links, too. Very strange. As for looking for LeftFloor -- that makes sense only if you already know about LeftFloor. (Now I do.) Links from Floor to LeftFloor and RightFloor would make a lot of sense, but that's probably why they're not there. very kindly helping to make up for it. Bobby Treat -----Original Message----- I'm reaching it by clicking on The Mathematica Book and then clicking die chapter and subchapters as mentioned above. It's chapter 3.10.4 (in You can also find it by looking for [LeftFloor] in the Master index. Yours, Alexander Dreyer -- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern / ==== One can make my original code (below) much faster by adding an auxiliary function and using dynamic programming: In[1]:= ss=ReadList[adj.txt,{Number,Word}] Out[1]= {{1,A},{1,B},{2,B},{3,C},{4,B},{5,D},{5,E},{6,F},{7,A}} In[2]:= l=Length[Union[First[Transpose[ss]]]] Out[2]= 7 a[i_] := a[i] = Cases[ss, {i, x_} -> x, {1}] In[4]:= Table[If[Intersection[a[i],a[j]]=!={},1,0](1- KroneckerDelta[i,j]),{i,l},{j, l}]//MatrixForm Out[4]//MatrixForm= 0 1 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 For large lists you will see a large difference in speed. Andrzej Kozlowski Toyama International University JAPAN > First of all, Import is not really meant for this sort of situation; > it is better to use ReadList. Suppose your file is: 1 A > 1 B > 2 B > 3 C > 4 B > 5 D > 5 E > 6 F > 7 A and its name is adj.txt. Here is one way you can deal with this > case. First, read in the file: > In[1]:= > ss=ReadList[adj.txt,{Number,Word}] Out[1]= > {{1,A},{1,B},{2,B},{3,C},{4,B},{5,D},{5,E},{6,F},{7,A}} Next, find how many actors there are: In[2]:= > l=Length[Union[First[Transpose[ss]]]] Out[2]= > 7 Construct the adjacency matrix: In[3]:= > Table[If[Intersection[Cases[ss,{i,x_}->x,{1}], > > Cases[ss,{j,x_}->x,{1}]]=!={},1,0](1-KroneckerDelta[i,j]),{i, > l},{j,l}]//MatrixForm Out[3]//MatrixForm= > 0 1 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 The function ToAdjacencyMatrix form the Combinatorica package > constructs the adjacency matrix from a graph, so it has no direct > application to your problem. Andrzej Kozlowski > Toyama International University > JAPAN > I need to create an adjacency matrix from my data, which is currently >> in >> the form of a .txt file and is basically a two column incidence list. >> For example: >> 1 A >> 1 B >> 2 B >> 3 C >> . . >> . . >> . . >> m n >> Where 1 to m represent actors and A to n represent events. My goal is >> to >> have an (m x m) matrix where cell i,j equals 1 if two actors are >> incident to the same event (in the sample above, 1 and 2 are both >> incident to B) and 0 otherwise (w/ zeros on the diagonal). >> I'm new to Mathmatica, and so I'm on the steep part of the learning >> curve ... All I've been able to figure out so far is how to get my >> incidence list into the program using Import[filename.txt]. But then >> what? How do I convert to the adjacency matrix? I've found the >> ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I >> can't >> seem to get it to work ... >> Tom >> ********************************************** >> Thomas P. Moliterno >> Graduate School of Management >> University of California, Irvine >> tmoliter@uci.edu >> ********************************************** ==== script. Unfortunately when I start Mathreader I get the error message No file exists for resource 318 while the programme is initialising the text resource manager. It is not possible to click this message away. Can anybody help me with this problem? The only hint I found was the which I didn't find very useful. Best, M. ==== I have written the following in a JLink program: drawArea=JavaNew[com.wolfram.jlink.MathCanvas]; then I perform an analysis of some data with output of this form.... plot = DisplayTogether[ListPlot[],ListPlot[].etc...]; Unfortunately, at this point I dont know how to associate 'plot' 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 blimbaum NSWC panama city, fl ==== Somehow, we at WRI seem to have completely neglected to make any slide shows with internal hyperlinks (probably because slide show content, by its very nature, is just less likely to need internal hyperlinks), and so we never saw this problem. We'll fix it in a future version of Mathematica, but in the mean time, here's a workaround. The workaround is not exactly perfect...it can cause flashing on screen and may not put the scrollbar in exactly the right place...but it does work. With the slide show you're editing open, perform the following steps: * Format->Edit Style Sheet... Choose Import Private Copy (unless you want to modify the global style sheet, which I wouldn't recommend unless you need this in a lot of notebooks). * In the stylesheet, open the Hyperlinks group. Open the group for the Hyperlink style with that. * Place the cell insertion point after the prototype for the Hyperlink style and copy/paste the following in (pressing Yes when asked whether to interpret the cell): Cell[StyleData[Hyperlink, SlideShow], ButtonBoxOptions->{ButtonFunction:>(FrontEndExecute[ { CompoundExpression[ FrontEnd`SetOptions[ FrontEnd`ButtonNotebook[ ], ScrollingOptions -> { PagewiseDisplay -> False}], FrontEnd`NotebookLocate[ #2], FrontEnd`SetOptions[ FrontEnd`ButtonNotebook[ ], ScrollingOptions -> { PagewiseDisplay -> Inherited}]]}]&)}] * Close the style sheet, then save your slideshow notebook. Internal hyperlinks should now work. Sincerely, John Fultz jfultz@wolfram.com User Interface Group Wolfram Research, Inc. >I am interested in creating a slide presentation using slide view >mode in Mathematica 4.2. I would like to have hyperlinks between >different slides ( e.g., a hyperlink in say slide 6 takes me back to >slide 3). > >I have no 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? >Brian ==== BRIEF Mathematica seems to support 3 levels of nesting: section, subsection, and subsubsection. Q: how can I obtain more levels of nesting? I typically go 6-7 levels deep. DETAIL = Config = I am using Mathematica 4 on a Sun Sparc at work. = Good Style or Not = I *know*, good style guides say that you should never go more than 3 levels of section deep. I disagree, and don't care. After editting my documents may only end up with three levels of subsection nesting, but while I am editting, moving stuff around, I frequently want more. (Often, I move a whole subtree of the document around, so that all sections become subsubsections, subsections become subsubsections, etc.) E.g. HTML originally had only H1, H2, H3, but now it goes all the way up to H10. = How are Sections Indicated? = I had hoped to define my own styles, section, subsection, sub2section, sub3section, etc. (ideally, section(level) if styles can be parameterized). But, I cannot see how to indicate how deeply nested a style is. In particular, I want to use the folding or hiding feature, so that after I have defined sub6section, etc. I can hide everything below a sub4section. == Nesting Level or Bracket? == It appears that Mathematica's sections have the level hardwired into them. section is at level 0 subsection at level 1 subsubsection at level 2 This means that the next section at the same level terminates a nesting group. The alternative implementation is to use brackets, e.g. XML
level 1
level 2
level3
level 2
level 1
This does not require the section level to be hardwired into the style. Obviously, Mathematica supports the first, hardwired or explicit level scheme. But, I cannot figure out how to extend it to multiple levels. I woulds be especially happy if the second approach were available, but, again, do not know how to create a Mathematica notebook style that accomplishes it. APOLOGIES I'm sorry if this is a frequently asked question. I have searched the FAQ and the MathGroup archives to no avail. I did find stuff on section numbering, which is related - I usually like Dewey decimal section numbers extended to the same arbitrary depth - but none on deeper nesting than subsubsection. ==== Perhaps, it is a stupid question, but somehow, I was not able to find any help on the following: I have a notebook, which does some calculations and saves results onto disk. All I need is to execute this notebook somewhere within another notebook. Sometimes it is nice to keep some parts of the code separated in different notebook files, which depending on the circumstances could be run manually via FrontEnd or within an automated loop from a notebook. To a certain extent this philosophy resembles, for example, what they have for scripts in another system. Please, reply directly to akolzine@uiuc.edu Sincerely, Alexei. ==== 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 permutation and manipulation, and having it still crash, I am still worried that upgrading to 4.2 won't solve my problem. Can anyone else with 4.2 try running this program for me a good number of times, say 3 or 4, and see if they get similar good results? Bernard Gress Dear Group, I have a program to take the local polynomial non parametric regression of two variables. It uses Compile, unfortunately, and regularly, but inconsistently, causes Mathematica to crash (in Win2K, with I forget what error, and in Win98/Mathematica4.0 with an invalid memory access from MathDLL.dll). I am running Mathematica 4.1, and have this problem consistently 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) *) ==== I ran it 10 times on 4.2 with no crashes. > Jens-Peer Kuska tells me that he gets no crash with Mathematica 4.2, however after working > with this program for more than a month, trying every possible permutation and > manipulation, and having it still crash, I am still worried that upgrading to 4.2 > won't solve my problem. Can anyone else with 4.2 try running this program for me a > good number of times, say 3 or 4, and see if they get similar good results? > Bernard Gress Dear Group, I have a program to take the local polynomial non parametric regression > of two variables. It uses Compile, unfortunately, and regularly, but > inconsistently, causes Mathematica to crash (in Win2K, with I forget > what error, and in Win98/Mathematica4.0 with an invalid memory access from > MathDLL.dll). I am running Mathematica 4.1, and have this problem consistently > 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) > *) > Reply-To: kuska@informatik.uni-leipzig.de ==== my Mathematica 4.2 does not crash and you may upgrade your version. Jens > > Dear Group, > > I have a program to take the local polynomial non parametric regression > of two variables. It uses Compile, unfortunately, and regularly, but > inconsistently, causes Mathematica to crash (in Win2K, with I forget > what error, and in Win98/Mathematica4.0 with an invalid memory access from > MathDLL.dll). I am running Mathematica 4.1, and have this problem consistently > on 4 different machines. > > Here is the code, if it doesn't crash the 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) > *) > > I have followed Ted Ersek's tips and tricks > (http://www.verbeia.com/mathematica/tips/tip_index.html) about Compile, > and have tried changing all variable names (works sometimes), removing > any hidden spaces, restructuring the formulas, changing all 0's to 0. 's > and all 1's to 1. 's, etcetera etcetera, but I still can't comprehend > what the problem might be. Doing w[[-2]] shows a list of op-code > numbers, and one function name, Inverse[#1]&, so it seems to me that > there are no problems with the use of Compile here. Would anyone have > any thoughts??? > > > Bernard Gress > burnthebiscuit@netscape.net ==== Mr Kuska, 4.2, I thought I had solved this problem so many times and still it would suddenly start crashing again our of the blue, after 20 or 30 executions. Bernard my Mathematica 4.2 does not crash and you may upgrade > your version. > ==== >Is it possible to configure a style sheet so that functions or data shown in >graphs are coloured (colored :)) in working but black in printing...without >actually re-executing the function that created the graphics? > >thanks > >Mike There is no way do this, but with a couple of tricks you can create the same effect. First, we generate 2 graphics. One is the normal graphic. The other uses all black colors. This process is automated by changing $DisplayFunction. $DisplayFunction = ( (* first the normal graphic *) Display[$Display, #1]; (* then a new B&W graphic *) CellPrint[ Cell[GraphicsData[PostScript, DisplayString[#1 /. {_RGBColor | _CMYKColor -> GrayLevel[0]}]], GraphicsPrintout]]; #1 ) &; If you set this and do a plot you will see the two graphics. The second graphic will look strange because it's in a different cell style. We're going to use the cell styles to control which graphic is shown. Next, open the style sheet (menu item Format>Edit Style Sheet). Replace the Graphics/Printout style with the following cell. Cell[StyleData[Graphics, Printout], ShowCellBracket->False, CellMargins->{{0, 0}, {0, 0}}, CellElementSpacings->{CellMinHeight->0}, CellGroupingRules->NormalGrouping, CellFrameMargins->False, CellSize->{Inherited, 0}, Background->None] It hides the colored cell in the Printout environment. Then, add the following styles. Cell[StyleData[GraphicsPrintout], CellMargins->{{4, Inherited}, {Inherited, Inherited}}, CellGroupingRules->GraphicsGrouping, CellHorizontalScrolling->True, PageBreakWithin->False, GeneratedCell->True, CellAutoOverwrite->True, ShowCellLabel->False, DefaultFormatType->DefaultOutputFormatType, LanguageCategory->None, FormatType->InputForm, ImageMargins->{{43, Inherited}, {Inherited, 0}}, StyleMenuListing->None, FontFamily->Courier, FontSize->10] Cell[StyleData[GraphicsPrintout, Printout], ImageMargins->{{30, Inherited}, {Inherited, 0}}, Magnification->0.8] Cell[StyleData[GraphicsPrintout, Working], ShowCellBracket->False, CellMargins->{{0, 0}, {0, 0}}, CellElementSpacings->{CellMinHeight->0}, CellGroupingRules->NormalGrouping, CellFrameMargins->False, CellSize->{Inherited, 0}, Background->None] It hides the B&W cell in the Working environment and shows the cell in the Printout environment. Finally, try it out. Plot[x, {x, 0, 1}, PlotStyle -> RGBColor[1, 0, 0], TextStyle -> {FontColor -> RGBColor[0, 0, 1]}] -------------------------------------------------------------- Omega Consulting The final answer to your Mathematica needs Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html ==== I was completely wrong about the pattern list_?(VectorQ[#, NumericQ] &). I had forgotten about that notation and didn't think to look it up. Sorry! Bobby -----Original Message----- evaluates fairly slowly (even if it has been Compiled). 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 was wondering if a way exists to move the main menu bar of the front end. I am talking about the bar that occupies the top of the screen and extends, by default, from the left end of the screen to the right. It has a lot of blank space to the right of the menus. Making it narrower frees up some important screen real estate, if you want to reach icons under it. How could I make Mathematica do that automatically? I cannot seem to find it in the Preferences or in the sections on manipulating notebooks. Nicholas ==== The various Intro/Mathematica Programming books I've seen (e.g. Gray: Mastering Mathematica -- now out of print but have a copy on order) and Mathematical Navigator and other books I've seen are based on V3. Is there any Intro/Programming book based on V4 (or even updated for 4.2) that is available besides the on-line book? Does someone have notes that update the V3 books? ==== I puzzled over this and came up with an explanation. The phenomenon somebody noticed is that the fractional part of (Sqrt[3] + Sqrt[2])^(2*n) approaches 1 from below as n (integer) gets large. Hence, for instance, Mod[ N[(Sqrt[2] + Sqrt[3])^2002, 2000], 100] has a string of 996 nines after the decimal point. Well, here's the reason for that. Let x and y be the square roots of any integers and let n be an even integer power. Then (x + y)^n == Sum[Binomial[n, m]*y^m*x^(n - m), {m, 0, n}]; and (x - y)^n == Sum[(-1)^m*Binomial[n, m]*y^m*x^(n - m), {m, 0, n}]; so, adding the two equations, we have (x + y)^n + (x - y)^n == Sum[Binomial[n, m]*y^m*x^(n - m)* (1 + (-1)^m), {m, 0, n}]; 1 + (-1)^m is 0 when m is odd and 2 when m is even, so (x + y)^n + (x - y)^n == 2*Sum[Binomial[n, 2*k]*y^(2*k)*x^(n - 2*k), {k, 0, n/2}]; Since n is even, all powers of x and of y are even in this expression. Since x and y are the square roots of integers, it follows that all the terms are integers. Hence (x + y)^n + (x - y)^n is integer. Now we assume, in addition to our other conditions, that 0 < x - y < 1 In that case, (x - y)^n approaches 0 from above as n gets large, and FractionalPart[(x + y)^n] == 1 - (x - y)^n which approaches one from below as n gets large. The number of nines after the decimal point can be calculated as Floor[(-n)*Log[10, Sqrt[3] - Sqrt[2]]] For n=2002 (the example we started with, this is indeed) Floor[-2002*Log[10, Sqrt[3] - Sqrt[2]]] 996 Bobby Treat -----Original Message----- > finally take the result modulo 10^n. > > Mod[Floor[ N[(Sqrt[2] + Sqrt[3])^2002 , 1000]], 10^2] > > results in 9, so the last two digits before the decimal point are 09. > > With a slight modification we can find the first n digits after the decimal > point. Simply find the last n digits before the decimal point of 10^n times > the number. > > Mod[Floor[ N[10^2 (Sqrt[2] + Sqrt[3])^2002 , 1000]], 10^2] > > results in 99, so these are the digits you are interested in. > > But there is something curious about this number. > > Mod[Floor[N[10^1000 (Sqrt[2] + Sqrt[3])^2002 , 2000]], 10^1000] > > results in 996 digits 9 followed by 7405. > > You can also play with the following command, resulting in the digits around > the decimal point: > > Mod[ N[(Sqrt[2] + Sqrt[3])^2002, 2300], 10^6] > > The decimal expansion of (Sqrt[2]+Sqrt[3])^2002 contains a sequence of > 997 consecutive digits 9. Do you have any idea why? Not unusual. Try other even exponents and there should be large blocks of 9s . Smaller number for small exponents. Some kind of propagation of 9s as the exponent grows. Try other odd values for 3 and the same thing happens for some values. Also for other values for 2. Larry > > Fred Simons > Eindhoven University of Technology > > > > > ==== >I have written the following in a JLink program: >drawArea=JavaNew[com.wolfram.jlink.MathCanvas]; > >then I perform an analysis of some data with output of this form.... > >plot = DisplayTogether[ListPlot[],ListPlot[].etc...]; >Unfortunately, at this point I dont know how to associate 'plot' with >drawArea so that > >draw.Area@RepaintNow[]; repaints the math screen to show the plots I've >computed... >I've tried draw.Area@update[plot] and draw.Area@setImage[plot] but these >dont work........how to 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. Todd Gayley Wolfram Research ==== try: (((((3^(1/2))^(1/2))^(1/2))^(1/2))^(1/2))/(6^(1/2)) Out: 1/(Sqrt[2]*3^(15/32)) You can see what happened: 1st: 6^(1/2) = 2^(1/2)*3^(1/2); 2nd: subtraction of the 3's exponents (1/2)^5 - 1/2 = 1/32 - 16/32 = - 15/32. MATHEMATICA does these straightforward simplifications without you having to invoke Simplify[]. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de -----UrsprÌ.b9ngliche Nachricht----- Gesendet: Freitag, 13. September 2002 07:14 An: mathgroup@smc.vnet.net Betreff: nth roots Simplify: 5nth sqrt (3)/sqrt (6) 5nth Sqrt(3) ------------ Sqrt(6) 1st.. is this the correct notation for use on a computer 2nd.. how is the solution solved, step by step please. ==== Dear all, I want to include some Mathematica code in some lecture notes I am writing. For that purpose, I use the LaTeX style provided with Mathematica. It seems to be working fine when I produce a document that is just Mathematica code. The problem - as expected - is that when I include the Mathematica code as a part of a larger document, there are (1) clashes with existing packages (2) some LaTeX elements, such as the equations, start to use the Mathematica fonts too. My objective would be to typeset a document in standard LaTeX, where only the Mathematica code has the Mathematica feeling. Does anyone know of any style available that is completely seperated from all other LaTeX definitions? Best Kyriakos _____+**+____+**+___+**+__+**+_ Kyriakos Chourdakis Lecturer in Financial Economics URL: http://www.qmw.ac.uk/~te9001 tel: (++44) (+20) 7882 5086 Dept of Economics University of London, QM London E1 4NS U.K. Reply-To: kuska@informatik.uni-leipzig.de ==== a) you must change the fonts, because the Mathematica symbols are designed to fit to Times/Helvetica/Courier and not to Computer Modern ! Mixing Computer Modern and the Mathematica fonts look not very nice because Comuter Modern has smaler strokes. You need atleast wrisym.sty, i.e. usepackage[monospacemath]{wrisym} but this will switch the main document font to Times and the mono-space font to courier. With Mathematica 4.2 you can use Adobe-Garamond and Janson as document fonts too, with usepackage[monospacemath,garamond]{wrisym} but this are commercial fonts and you have to buy it from Adobe. b) If you like the narrow monotype fonts similar to Computer Modern you can use the CMTT fonts, now included in Mathematica 4.2 Just use the package option usepackage[cmtt]{wrisym} c) I have a TeX frontend that use only the wrisym package and a preprocessor. It run fine with the most style files But you have to use TeX notebooks that are essential TeX files with mathinput environments. The TeX frontend send the contents of the mathinput environments to the kernel and paste the output into the final TeX file. It also does some fancy formating with the Mathematica input and replace -> with Rule, :> with RuleDelayed .. You can have the program and the style files if you like. Jens > > Dear all, > > I want to include some Mathematica code in some lecture notes I am writing. > For that purpose, I use the LaTeX style provided with Mathematica. It seems > to be working fine when I produce a document that is just Mathematica code. > > The problem - as expected - is that when I include the Mathematica code as > a part of a larger document, there are > (1) clashes with existing packages > (2) some LaTeX elements, such as the equations, start to use the > Mathematica fonts too. My objective would be to typeset a document in > standard LaTeX, where only the Mathematica code has the Mathematica feeling. > > Does anyone know of any style available that is completely seperated from > all other LaTeX definitions? > > Best > > Kyriakos > > _____+**+____+**+___+**+__+**+_ > > Kyriakos Chourdakis > Lecturer in Financial Economics > > URL: http://www.qmw.ac.uk/~te9001 > tel: (++44) (+20) 7882 5086 > Dept of Economics > University of London, QM > London E1 4NS > U.K. ==== What about this problem? I have tried the previous suggestions but none of them worked. Will Wolfram help us in this problem? ==== Have you tried deleting ... Mathematica4.2DocumentationEnglishMainBookBrowserIndex.nb 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? > ==== First a thank you to all those who pointed out to me (and others apparently) 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 on how to use Mathematica to write a technical document. The number of questions that appear on this board concerning the details of how to do it suggests the need for such documentation. I'm speculating when I say that many users give up in frustration and go back to (or learn) Latex. At least 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 a document is, for most of us, not worth the effort. 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! Jack Reply-To: kuska@informatik.uni-leipzig.de ==== does help you ? Jens > > > I often run into this difficulty: when designing a program, say as a > module, and testing it for various inputs, I get wrong answers. What to > do? I use a method that works for me but may not be the best available. > I want to show my method and then ask a question about how it can be > imporved. (Oh yes, I abandoned Trace a long time ago!) > > myFunction[f_] := Module[ {L1,L2,L3}, > > L1 = ... ; > L2 = ... ; > l3 = ... ; > final step > > ] > > To see what went wrong, I use (* *) selectively as follows: > > Stage 1 > > myFunction[f_] := Module[ {L1,L2,L3}, > > L1 = ... (*; > L2 = ... ; > L3 = ... ; > final step *) > > ] > > Thus I see if L1 worked as expected. The next step is to put (* after L2 > and see if this works. I continue this til the bitter end and I usually > find my errors. > > My question; The process of moving (* *) step by step through the > program is quite tedious when the code has lots more lines. What I would > like is a meta-program which (like FoldList) does this job for me. The > output of this meta-program is the list of outputs of each line in the > module, probably best printed as a column. > This sounds like Trace but my problem with Trace is it is terribly > difficult to read. For the not-so-subtle programming I do, the only thing > I need is what expression is returned line by line. > > Any advice? All remarks are appreciated! > > Jack ==== I've enhanced the code for PartialEvaluation (see my post, which I incorrectly attaced to someone else's reply). It is somewhat more flexible now and does more error checking. It finds the rule in DownValues that matches f[args] (allowing for more than one rule in DownValues); it allows the user to specify the position of the main CompoundExpression; and it allows the user to specify an expression that gets appended to the truncated CompoundExpression (and hence evaluated and returned). The package is just a bit too large to post here. It can be downloaded from my web site at http://www.markfisher.net/~mefisher/mma/mathematica.html Nevertheless, I can give an outline of the code here (absent the error checking stuff). PartialEvaluation[f[args], n, expr]: (* get the DownValues and turn them off *) dv = DownValues[f]; DownValues[f] = {}; (* find the rule that matches *) matches = Position[MatchQ[f[args], #]& /@ dv[[All, 1]], True]; match = dv[[ matches[[1, 1]] ]]; (* find the main CompoundExpression *) ppos = Position[match, HoldPattern[CompoundExpression[__]]]; pos = First[Sort[ppos]]; (* extract, truncate, append to, and reinsert it *) held = Extract[match, pos, Hold]; held = ReplacePart[held, Sequence, {1, 0}]; held = Take[held, n]; held = Join[held, Hold[expr]]; held = ReplacePart[Hold[Evaluate[held]], CompoundExpression, {1, 0}]; match = ReplacePart[match, held, pos, 1]; (* apply the modified rule and restore DownValues *) result = f[args] /. match; DownValues[f] = dv; result --Mark > > I often run into this difficulty: when designing a program, say as a > module, and testing it for various inputs, I get wrong answers. What to > do? I use a method that works for me but may not be the best available. > I want to show my method and then ask a question about how it can be > imporved. (Oh yes, I abandoned Trace a long time ago!) > > myFunction[f_] := Module[ {L1,L2,L3}, > > L1 = ... ; > L2 = ... ; > l3 = ... ; > final step > > ] > > To see what went wrong, I use (* *) selectively as follows: > > Stage 1 > > myFunction[f_] := Module[ {L1,L2,L3}, > > L1 = ... (*; > L2 = ... ; > L3 = ... ; > final step *) > > ] > > Thus I see if L1 worked as expected. The next step is to put (* after L2 > and see if this works. I continue this til the bitter end and I usually > find my errors. > > My question; The process of moving (* *) step by step through the > program is quite tedious when the code has lots more lines. What I would > like is a meta-program which (like FoldList) does this job for me. The > output of this meta-program is the list of outputs of each line in the > module, probably best printed as a column. > This sounds like Trace but my problem with Trace is it is terribly > difficult to read. For the not-so-subtle programming I do, the only thing > I need is what expression is returned line by line. > > Any advice? All remarks are appreciated! > > Jack ==== JM, You are certainly correct in wanting to make a tidier plot! Legends are often poor because they actually distract from the message of the data. However, the best solution will depend on the particular nature of your data. If there are not too many curves you could perhaps put Text labels right on top of each curve. If there are many curves, or some of them are close 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 labeled arrows because the best placement would depend upon the particular nature of the 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 coordinates off the graph to put into the Arrow and Text statements. If you want to actually show me your plot, I could try to make some suggestions. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ _ | thankyou ==== >I am interested in creating a slide presentation using slide view >mode in Mathematica 4.2. I would like to have hyperlinks between >different slides ( e.g., a hyperlink in say slide 6 takes me back to >slide 3). > >I have no 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? >Brian If you set PagewiseScrolling->True, then your hyperlink will work. Go to the Option Inspector and set the scope to Notebook. Then go to the option NotebookOptions|Window Properties|ScrollingOptions|PagewiseScrolling And set it to True. The disadvantage to this setting is that you can now only have one screen's worth of contents per slide. (But then it is a slide show after all, so maybe that's not so bad.) -Dale ==== Does anybody know how to calculate in Mathematica: a)empirical CDF, b)empirical PDF, c)normal QQ-plot; d)QQ-plot two different random samples?! Swidrygiello. ==== DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent the loading of a large file in routine cases. However, when ThisPackage` defines its functions, inside the Private` area, it includes a conditional call to BigVariable. It turns out that OtherPackage is loaded when that function is defined. I was wondering if there is a way to avoid this. Roughly speaking, here is the setting: BeginPackage[ OtherPackage` ] BigVariable::usage=example Begin[Private`] BigVariable=Table[x y,{x,1000},{y,1000}] End[ ] EndPackage[ ] BeginPackage[ ThisPackage` ] function::usage=example Begin[Private`] function[x_]:=Module[{y}, y=If[x>1000,BigVariable[[x]],x] ] End[ ] EndPackage[ ] I don't want OtherPakage to be loaded unless function[x] is called with x>1000 but it loads when function is defined. Any ideas? Nicholas Reply-To: kuska@informatik.uni-leipzig.de ==== BeginPackage[ OtherPackage` ] BigVariable::usage=example Begin[`Private`] BigVariable=Table[x y,{x,1000},{y,1000}] End[ ] EndPackage[ ] Print[Loading ...]; and BeginPackage[ ThisPackage` ] function::usage=example Begin[`Private`] function[x_]:=Module[{y}, y=If[x>1000, Needs[OtherPackage`]; OtherPackage`BigVariable[[x]], x] ] End[ ] EndPackage[ ] should do that. Jens > > DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent > the loading of a large file in routine cases. However, when ThisPackage` > defines its functions, inside the Private` area, it includes a conditional > call to BigVariable. It turns out that OtherPackage is loaded when that > function is defined. I was wondering if there is a way to avoid this. > Roughly speaking, here is the setting: > > BeginPackage[ OtherPackage` ] > BigVariable::usage=example > Begin[Private`] > BigVariable=Table[x y,{x,1000},{y,1000}] > End[ ] > EndPackage[ ] > > BeginPackage[ ThisPackage` ] > function::usage=example > Begin[Private`] > function[x_]:=Module[{y}, > y=If[x>1000,BigVariable[[x]],x] ] > End[ ] > EndPackage[ ] > > I don't want OtherPakage to be loaded unless function[x] is called with > x>1000 but it loads when function is defined. Any ideas? > > > Nicholas ==== Dynamic programming might help: replace the line defining BigVariable with BigVariable:=BigVariable=Table[x y,{x,1000},{y,1000}] Then the table will not be calculated unless it is needed. (See the section on Functions that Remember Values They Have Found, 2.4.9 in the Mathematica Book). John Jowett > DeclarePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent > the loading of a large file in routine cases. However, when ThisPackage` > defines its functions, inside the Private` area, it includes a conditional > call to BigVariable. It turns out that OtherPackage is loaded when that > function is defined. I was wondering if there is a way to avoid this. > Roughly speaking, here is the setting: BeginPackage[ OtherPackage` ] > BigVariable::usage=example > Begin[Private`] > BigVariable=Table[x y,{x,1000},{y,1000}] > End[ ] > EndPackage[ ] BeginPackage[ ThisPackage` ] > function::usage=example > Begin[Private`] > function[x_]:=Module[{y}, > y=If[x>1000,BigVariable[[x]],x] ] > End[ ] > EndPackage[ ] > I don't want OtherPakage to be loaded unless function[x] is called with > x>1000 but it loads when function is defined. Any ideas? Nicholas > ==== Could you send a sample example of your file -- just a few records. Tomas Garza Mexico City ----- Original Message ----- > 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. > 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? ==== I've got to extract some numbers from a file that are in lines of text. Since the line contents are not numbers, I presume I must pull the line out as a string. Here I start by pulling out just one line: inFile = OpenRead[197-tst.txt] y = ReadList[inFile, String, 1, RecordLists -> True] Close[inFile]; This appears to pull in a line. Now I want to take characters 25 to 110 to get just the stuff I want: y1=StringTake[y ,{25,110}]; Here's the output. StringTake doesn't seem to work. It doesn't take loading another package as far as I can tell from the help. I'm thinking that it doesn't work because it's trying to work on a list rather than a string. I've tried Flatten, and other stuff to try to get to just a string and not a list but nothing has worked so far. I'm a long way from getting to those numbers in there but heck, I can't even get to the string. Can anyone point me in the right direction? ==== this thing. Here is what I'm using now: In[1]:= a=ReadList[197-tst.txt,Word,RecordLists->True, WordSeparators->None]; In[2]:= flds={{25,31}, {32,39},{40,46},{47,54},{55,62},{63,70},{71,78},{79,86},{87, 94},{95,102},{103,110}}; Define this function: In[3]:= f[x_]:=ToExpression[StringTake[x[[1]],#]]&/@flds Now, map this function onto a: In[8]:= f/@a Out[8]= {{5935.8,5946.66,27.06,-1281.9,-229.,321.,317.,367.,-115.,126.,146.},{5935.8 .... ************ The data is now in a matrix of numbers and each variable is in a column. Now I just transpose this to get each variable in a row for easy access (apparently Mathematica has no way to directly access a column in a matrix, you gotta transpose I think) Rob > I've got to extract some numbers from a file that are in lines of text. Since the line contents are not numbers, I presume I must pull the line out as a string. Here I start by pulling out just one line: inFile = OpenRead[197-tst.txt] > y = ReadList[inFile, String, 1, RecordLists -> True] > Close[inFile]; This appears to pull in a line. Now I want to take characters 25 to 110 to get just the stuff I want: > y1=StringTake[y ,{25,110}]; Here's the output. StringTake doesn't seem to work. > It doesn't take loading another package as far > as I can tell from the help. I'm thinking that it doesn't work because it's trying to work on a list > rather than a string. I've tried Flatten, and other stuff to try to get to just a string and not a list but > nothing has worked so far. I'm a long way from getting to those numbers in there but heck, I > can't even get to the string. Can anyone point me in the right direction? > ==== > The data is now in a matrix of numbers and each variable is in a column. > Now I just transpose this to get each variable in a row for easy access > (apparently Mathematica has no way to directly access a column in a matrix, > you gotta transpose I think) You can use All: In[1]:= mat = {{a,b,c},{d,e,f}}; In[2]:= mat[[All,2]] Out[2]= {b, e} -- Bhuvanesh, Wolfram Research. ==== > inFile = OpenRead[197-tst.txt] > y = ReadList[inFile, String, 1, RecordLists -> True] > Close[inFile]; > > This appears to pull in a line. Now I want to take characters > 25 to 110 to get just the stuff I want: > y1=StringTake[y ,{25,110}]; > > Here's the output. StringTake doesn't seem to work. > > -1281.9 -229. 321. 317. 367. -115. 126. > 146. -410. -426.000000EF 75.}, {25, 110}] > > It doesn't take loading another package as far > as I can tell from the help. I'm thinking that it doesn't > work because it's trying to work on a list > rather than a string. I've tried Flatten, and other stuff to > try to get to just a string and not a list but > nothing has worked so far. I'm a long way from getting to > those numbers in there but heck, I > can't even get to the string. Can anyone point me in the > right direction? You might try lst = Read[StringToStream[y1], {Word, Table[Number, {16}], Word, Number}]//Flatten; You can then pick the numbers (or words) from the list lst. A quicker alternative might be as follows:- ifile = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}]; Dave. ========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au =========================================== ==== First of all, I used ReadList directly, with Word instead of String, and with the option WordSeparators -> None, like this (I presume your file is adequately 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 way each record comes out as a list of length 1: In[2]:= Head[a[[1]]] Out[2]= List In[3]:= Length[a[[1]]] Out[3]= 1 That is, In[3]:= a[[1]] Out[3]= 317. 367. -115. 126. 146. -410. -426.000000EF 75.} In[4]:= StringLength[a[[1,1]]] Out[4]= 140 and the characters you want are In[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 problem now, I think, is that this is just a string and I can think of no easy way to convert it precisely into a list of 11 real numbers. Then, I suggest you read 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]= 115.,126.,146.,-410.,-426.000000EF,75.} In[8]:= Head[b[[1]]] Out[8]= List In[9]:= Length[b[[1]]] Out[9]= 19 so that each record is now a list of 19 strings. What you want is strings 6 to 16, but converted to reals (unless I'm being presumptuous). This will achieve 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 for the whole file like this: In[11]:= ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem. Tomas Garza Mexico City > ----- Original Message ----- > Sent: Friday, September 13, 2002 12:14 AM 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. > -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? -------------------------------------------------------------------- ==== > BRIEF > > Mathematica seems to support 3 levels of nesting: > section, subsection, and subsubsection. > > Q: how can I obtain more levels of nesting? > I typically go 6-7 levels deep. Well, I started by editting the notebook in a text editor (having used Edit Style Sheet to unshare), and I created styles Sub3section ... Sub9section, with Dewey decimal numbering 1.2.3.4.5.6.7.8.9.10 I got collapsable group working, by mucking with CellGroupingRules->{SectionGrouping, 100}, changing the number. I am not sure what the number is, but I'm guessing it may be a pixel count for the nesting boxes at 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 a common operation is to push down or pull up a whole subtree - e.g. a Subsection becomes a Subsubsection, a Subsubsection becomes a Sub3section, etc. The sort of thing that Microsoft Word does with Outline mode. Q: has anyone got something like Outline mode for Mathematica? I'm tempted to go the other way, and ask if anyone has a front end that allows Mathematica to be embedded in Word documents. But that might be a hassle, since Word runs on Windows, and the Mathematica licence I have access to runs on Suns. ==== > inFile = OpenRead[197-tst.txt] > y = ReadList[inFile, String, 1, RecordLists -> True] > Close[inFile]; > > This appears to pull in a line. Now I want to take characters > 25 to 110 to get just the stuff I want: > y1=StringTake[y ,{25,110}]; > > Here's the output. StringTake doesn't seem to work. > > -1281.9 -229. 321. 317. 367. -115. 126. > 146. -410. -426.000000EF 75.}, {25, 110}] > > It doesn't take loading another package as far > as I can tell from the help. I'm thinking that it doesn't > work because it's trying to work on a list > rather than a string. I've tried Flatten, and other stuff to > try to get to just a string and not a list but > nothing has worked so far. I'm a long way from getting to > those numbers in there but heck, I > can't even get to the string. Can anyone point me in the > right direction? You might try lst = Read[StringToStream[y1], {Word, Table[Number, {16}], Word, Number}]//Flatten; You can then pick the numbers (or words) from the list lst. A quicker alternative might be as follows:- ifile = ReadList[197-tst.txt, {Word, Table[Number, {16}], Word, Number}]; Dave. ========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au =========================================== ==== I was and do have problems reading files Exported files in Adobe Illustrator format (.ai) from Adobe Illustrator 10.0.3. With an upgrade to Adobe Illustrator 10.0.3, I can read EPS files created by Mathematica 4.0.1. A message from tech support at Wolfram implies that Adobe Illustrator format files can be read ONLY if you are using the correct Adobe and Wolfram programs. Additionally, Mathematica is going to favor the export of EPS files (is that clear enough?). My approach to using Mathematica as a source of images for Adobe Illustrator 10.0.3 is: Create the image in Mathematica Export[ImageFileName.eps, theMathematicaImageCreated, EPS] Open the file ImageFileName.eps within Adobe Illustrator 10.0.3 Save the file as a .ai file Be sure to check the ImageSize as it is not often what you told Mathematica. ==== In his not-so-subtle way, Jens-Peer is trying to tell you that since you see z in the error message, that's what NIntegrate saw too. z is a symbol, and NIntegrate needs numbers. Now I'll have to search online for your original problem, since I deleted my copy long ago... (Excuse me a few minutes...) Hmm... OK, I'm back. Well... there's still a missing (or extra) parenthesis in the definition of f and a missing bracket in the definition of F, but I also can't see that you've given z a numerical value. The error shouldn't occur until you use F though, since you used SetDelayed. So, the error message goes with a line you didn't include in your post. However, in your latest post, the lines NumericQ[z] False tell me z is NOT a real number. For instance, NumericQ[1.2] True So, proceeding with the theory that z needs to be numeric, let's try F[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 an iterator. As you see, in the definition of F, you've used z as an iterator. No matter what the argument z to F is -- number, symbol, whatever -- you can't use it as an iterator, because it already has an identity, and iterators are stand-ins -- temporary variables that don't exist outside (in this case) NIntegrate. So, as Jens-Peer pointed out, y should have been your iterator. (Probably. We don't actually know what you were trying 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 be F[z_] := NIntegrate[f[y, z], {y, 0, Infinity}] But... F[z] will still give you an error if z doesn't have a numerical value, 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 I don't know where to add or subtract that pesky parenthesis. (I asked still isn't.) Bobby Treat -----Original Message----- > 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 ==== I'm learning the fine art of patterns and Hold one tricky example at a time. Bobby -----Original Message----- > I want to make a list of all symbols in the Global context, as in > > Names[Global`*] > > and compute a ByteCount for each symbol's OwnValues -- without > evaluating the symbols. > > It seems possible in principle, but I haven't found a way. > > Bobby Treat ==== Here's the fairly useful bit of code I came up with, using Jens-Peer's brilliant solution: names = Names[Global`*]; counts = ToExpression[#, StandardForm, Hold] & /@ names /. Hold[a_] :> ByteCount[OwnValues[a]]; Select[Transpose[{names, counts}], Last@# > 16 &] // TableForm It tells me how some of my memory is being spent. Bobby Treat -----Original Message----- > I want to make a list of all symbols in the Global context, as in > > Names[Global`*] > > and compute a ByteCount for each symbol's OwnValues -- without > evaluating the symbols. > > It seems possible in principle, but I haven't found a way. > > Bobby Treat ==== Jack, Often, what I do when developing a slightly complicated module is to 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/ l3 = ... ; final step ] To see what went wrong, I use (* *) selectively as follows: Stage 1 myFunction[f_] := Module[ {L1,L2,L3}, L1 = ... (*; L2 = ... ; L3 = ... ; final step *) ] Thus I see if L1 worked as expected. The next step is to put (* after L2 and see if this works. I continue this til the bitter end and I usually find my errors. My question; The process of moving (* *) step by step through the program is quite tedious when the code has lots more lines. What I would like is a meta-program which (like FoldList) does this job for me. The output of this meta-program is the list of outputs of each line in the module, probably best printed as a column. This sounds like Trace but my problem with Trace is it is terribly difficult to read. For the not-so-subtle programming I do, the only thing I need is what expression is returned line by line. Any advice? All remarks are appreciated! Jack ==== The following code is my attempt to provide the functionality you requested. It does some rudimentary error checking, but I haven't tried very hard to fool it. The code manipulates the DownValues, locating the highest CompoundExpression (see the lines in which pos is defined), keeping only those expressions specified. DownValues are restored after the expression is evaluated. The tricky part is keeping the CompoundExpression from evaluating while it is being manipulated. (See the lines in which held and new are defined.) I'm not sure I'm doing this part the most elegant way, but it seems to work. (* code starts here *) PartialEvaluation::usage = PartialEvaluation[f[args], n] returns f[args] where only the first n expressions are evaluated in the main CompoundExpression in DownValues[f]. For example:nt Clear[f]nt f[x_] := Module[{a,b}, a=3; b=4; a b x]nt PartialEvaluation[f, 2]n returns 4. PartialEvaluation::dvprob = DownValues[``] is either empty or has more than one element. PartialEvaluation::toobig = There are only `1` expressions in the CompoundExpression in `2`. PartialEvaluation::noce = There are no CompoundExpressions in DownValues[``]. 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 newsreader didn't show up, so I'm reposting (a slightly improved version) from Google. > 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/ > > > > I often run into this difficulty: when designing a program, say as a > module, and testing it for various inputs, I get wrong answers. What to > do? I use a method that works for me but may not be the best available. > I want to show my method and then ask a question about how it can be > imporved. (Oh yes, I abandoned Trace a long time ago!) > > myFunction[f_] := Module[ {L1,L2,L3}, > > L1 = ... ; > L2 = ... ; > l3 = ... ; > final step > > ] > > To see what went wrong, I use (* *) selectively as follows: > > Stage 1 > > myFunction[f_] := Module[ {L1,L2,L3}, > > L1 = ... (*; > L2 = ... ; > L3 = ... ; > final step *) > > ] > > Thus I see if L1 worked as expected. The next step is to put (* after L2 > and see if this works. I continue this til the bitter end and I usually > find my errors. > > My question; The process of moving (* *) step by step through the > program is quite tedious when the code has lots more lines. What I would > like is a meta-program which (like FoldList) does this job for me. The > output of this meta-program is the list of outputs of each line in the > module, probably best printed as a column. > This sounds like Trace but my problem with Trace is it is terribly > difficult to read. For the not-so-subtle programming I do, the only thing > I need is what expression is returned line by line. > > Any advice? All remarks are appreciated! > > Jack ==== Mathematica often produces complex resluts. But the problem is not complex: Try Solve[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 in http://www.verbeia.com/mathematica/tips/Links/Tricks_lnk_41.html I thin, one has to to replace the pattern i Sqrt[-a_] by Sqrt[(i Sqrt[-a_])^2] and then one has to simplify it? Peter Klamser ==== There has been an interesting discussion about using InterpolatingFunction for an empirical CDF. If one is willing to sacrifice some theoretical soundness, an empirical CDF may 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 some interpretation. 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 some textbooks) 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.4 375},{0.56,0.5},{0.58,0.5625},{0.59,0.625},{0.66,0.6875},{0.72,0.75},{0.73,0 ..8125},{0.78,0.875},{0.9,0.9375},{0.96,1.}} A plot may be given with: simpleEmpiricalCDFPlot[distr_/;VectorQ[distr,NumberQ]] := Module[{res,x,p}, res=simpleEmpiricalCDF[distr]; x=({#,#}& /@ Transpose[res][[1]])//Flatten; p=({#,#}& /@ Transpose[res][[2]])//Flatten; p= Join[{0},Drop[p,-2],{1}]; ListPlot[Transpose[{x,p}], c]] Again, this plot does not reflect theoretical considerations at the lower and upper end. With regard Hermann Meier ==== Caution: where right- and left-continuity are concerned, Daniel's relying on undocumented behavior that may change in the next version. Bobby -----Original Message----- that evaluates the empirical CDF given the observations in the list. The function is 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}] --Mark > I'm trying to write a fast empirical cummulative distribution function > (CDF). Empirical CDFs are step functions that can be expressed in > terms of a Which statement. For example, given the list of > observations {1, 2, 3}, > > f = Which[# < 1, 0, # < 2, 1/3, # < 3, 2/3, True, 1]& > > is the empirical CDF. Note that f /@ {1, 2, 3} returns {1/3, 2/3, 1} > and f is continuous from the right. > > When the number of observations is large, the Which statement > evaluates fairly slowly (even if it has been Compiled). Since > InterpolationFunction evaluates so much faster in general, I've tried > to use Interpolation with InterpolationOrder -> 0. The problem is that > the resulting InterpolatingFunction doesn't behave the way (I think) > it ought to. For example, let > > g = Interpolation[{{1, 1/3}, {2, 2/3}, {3, 1}}, InterpolationOrder - 0] > > Then, g /@ {1, 2, 3} returns {2/3, 2/3, 1} instead of {1/3, 2/3, 1}. > In addition, g is continuous from the left rather than from the right. > > Obviously I am not aware of the considerations that went into > determining the behavior of InterpolationFunction when > InterpolationOrder -> 0. > > So I have two questions: > > (1) Does anyone have any opinions about how InterpolatingFunction > ought to behave with InterpolationOrder -> 0? > > (2) Does anyone have a faster way to evaluate an empirical CDF than a > compiled Which function? > > By the way, here's my current version: > > CompileEmpiricalCDF[list_?(VectorQ[#, NumericQ] &)] := > Block[{x}, Compile[{{x, _Real}}, Evaluate[ > Which @@ Flatten[ > Append[ > Transpose[{ > Thread[x < Sort[list]], > Range[0, 1 - 1/#, 1/#] & @ Length[list] > }], > {True, 1}]] > ]]] > > --Mark ==== Hey, How can I duplicate those nifty 'More' hyperlinks in my usage statements? That is the hyperlinks that appears at the end of text that is generated after invoking a '?' to get more information about a function. Lawrence ==== >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 ReadList Try y = 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. ==== > > > I am trying to implement a very simple sorted tree to quickly store some > real numbers I need. I have written an add, delete, minimum, and pop > (delete the lowest value) function and they seem to work ok but are very > slow. Let's just look @ my implementation of the add part: > nums=Null;(*my initial blank Tree) > In[326]:= > Clear[add] > > In[327]:= > add[Null,x_Real]:=node[x,Null,Null] > > add[Null,node[x_Real,lower_,higher_]]=node[x,lower,higher] > > In[328]:= > add[node[x_Real,lower_,higher_],y_Real]:= > If[x>y,node[x,add[lower,y],higher],node[x,lower,add[higher,y]]] > > In[288]:= > add[node[x_Real,lowerx_,higherx_],node[y_Real,lowery_,highery_]]:=If[x>y, > node[x,add[lowerx,node[y,lowery,highery]],higherx], > node[x,lowerx,add[higherx,node[y,lowery,highery]]] > ] > > Now this is my attempt to test how fast my add works: > > SeedRandom[5]; > Do[nums=add[nums,Random[]],{5000}];//Timing > > Out[333]= > {13.279 Second,Null} > > running on an 1.4GHz Athlon with 1GB of ram). > > Questions: > 1. Is this as fast as I can get my code to run? > 2. Am I doing something obviously stupid? > 3. would Compiling things help? > > Husain I'll respond to your third question first. No, use of Compile will not help. You do not have a tensor structure and moreover it will copy its arguments. Hence invoking it within a loop would be quite slow for a problem where the argument grows in size. One thing you did not check is the actual run-time complexity of your code. 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 I would 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'll give some different code that has the desired complexity. Note that some of this, and code very similar to that below, is discussed 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 they are flattened the tree is automatically sorted. You might (or might not) regard this as an added benefit. leftsubtree[node[left_, _, _]] := left rightsubtree[node[_, _, right_]] := right nodevalue[node[_, val_, _]] := val emptyTree = 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 Second We 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]= True Also we will observe that the maximum depth is reasonable. In[43]:= Depth[ff1k] Out[43]= 23 In 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 Second In[45]:= tt4k = First[Timing[ff4k = node[]; Do[ff4k = treeInsert[ff4k, ee[[j]]], {j,4000}];]] Out[45]= 0.73 Second In[47]:= tt8k = First[Timing[ff8k = node[]; Do[ff8k = treeInsert[ff8k, ee[[j]]], {j,8000}];]] Out[47]= 1.58 Second In[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 Second This is not of blinding speed but it has the advantage of exhibiting the appropriate run-time complexity. One can, with careful coding, cut down on tree size but if you check with LeafCount you will find that the version above is already not too wasteful (3x larger than #values stored). Moreover the code needed would run a bit slower as it would have more cases to check. As for removing nodes, I think you will need to use some form of held attribute so as to avoid copying the entire tree when you alter elements. Daniel Lichtblau Wolfram Research ==== Johannes, I wasn't trying to write a truly efficient algorithm -- I consciously tried not to change the algorithm (or even the storage method) a lot, so that Husain could move along from where he was. Of course a heap would be more efficient. In fact, given the built-in Sort and Ordering functions, I see no reason to build sorted binary trees in Mathematica at all (as I said in my first post) -- except as a step in the process of learning. Your solution (on my machine) is equivalent in speed to Mihajlo's simple modification of Husain's original -- just by replacing Null with anything else -- and using instead of {} in your code makes no difference. The following code is Husain's, but uses List rather than node and {} rather than Null, and builds precisely the same tree as your code. Yet it's 10% slower than your code. I think that's simply because there are more rules -- the same reason my code is slower, because I have even more rules, so that more time is spent on pattern-matching. Clear[add] add[{}, x_Real] := {x, {}, {}} add[{}, {x_Real, lower_, higher_}] = {x, lower, higher}; add[{x_Real, lower_, higher_}, y_Real] := If[x > y, {x, add[ lower, y], higher}, {x, lower, add[higher, y]}] add[{x_Real, lowerx_, higherx_}, { y_Real, lowery_, highery_}] := If[x > y, {x, add[lowerx, {y, lowery, highery}], higherx}, {x, lowerx, add[higherx, {y, lowery, highery}]}] In fact, using List instead of node slowed the algorithm compared to Mihajlo's solution, by the same 10%. I think that's because it requires more pattern matching, to distinguish {} from other List forms in the tree at each call. As for the inefficiency inherent in copying trees, how would you avoid that, other than using something like a heap? Even with a heap, it has to be a global variable (not a function argument) to avoid copying. Bobby -----Original Message----- than yours on my computer though it uses twice as much memory as your representation. myadd[{},x_]:={x,{},{}}; myadd[{v_,a_,b_},x_]:=If[v>x, {v,myadd[a,x],b}, {v,a,myadd[b,x]}] t={}; Timing[Do[t=myadd[t,Random[]],{5000}];] {1.98 Second,Null} The real problem with the implementation is probably that the tree structure has to be 'copied' each time when add is called. You have to write tree = add[tree, x] t2 = add[t1, x] then you have *two* trees t1 and t2 which differ by the one element inserted by add. To the best of my knowledge, the internal representation of t1 and t2 in Mathematica is a tree too. But in principle the user code is duplicated in Mathematica. A further problem of all direct implementations is that they cannot be compiled (since they use pattern matching and the tree is a nested structure). Thus I guess that the efficient way to implement tree data structures is the indirect one using heaps (i.e. a combination of contiguous arrays with length known in advance and hashing). Johannes Ludsteck > You're not doing anything dumb as far as I can see, but you're using far > more memory than necessary. Here are statistics for your algorithm on > my machine: > > SeedRandom[5]; > nums = Null > Do[nums = add[nums, Random[]], {5000}]; // Timing > nums // LeafCount > nums // ByteCount > Count[nums, Null, Infinity] > Count[nums, node[_, Null, _], Infinity] > Count[nums, node[_, _, Null], Infinity] > Count[nums, node[_, Null, Null], Infinity] > Count[nums, node[___], Infinity] > Count[nums, node[_, _node | _?NumericQ, _node | _?NumericQ], Infinity] > Depth[nums] > > {4.406000000000001*Second, Null} > 15001 > 240000 > 5001 (* Null values in the tree *) > 2458 (* nodes without left offspring *) > 2543 (* nodes without right offspring *) > 1669 (* leaf nodes *) > 4999 (* total nodes *) > 1667 (* nodes with both left and right offspring *) > 28 (* minus one, makes 27 levels in the tree *) > > It's clearly not ideal to store 5001 Nulls for 5000 actual values! > > Here's a method that doesn't change the algorithm much, but changes the > storage method a great deal: > > First of all, I'm lazy, so I'll redefine <,>,<=,>=, etc. to make the > code simpler: > > Unprotect[Less, Greater, LessEqual, GreaterEqual]; > Less[a : _node ..] := Less @@ (First /@ {a}) > LessEqual[a : _node ..] := LessEqual @@ (First /@ {a}) > Greater[a : _node ..] := Greater @@ (First /@ {a}) > GreaterEqual[a : _node ..] := GreaterEqual @@ (First /@ {a}) > Protect[Less, Greater, LessEqual, GreaterEqual]; > > Again because I'm lazy, I'll define node so that I don't have to > consciously avoid leaf nodes and unnecessary nesting: > > ClearAll[node] > node[a___, node[b_], c___] = node[a, b, c]; > node[node[a__]] = node[a]; > > Here's my add function: > > Clear[add] > add[Null, x_] = node[x]; > add[x_, (y_)?NumericQ] := add[node[x], node[y]] > add[(x_)?NumericQ, y_] := add[node[x], node[y]] > add[node[x_], node[y_]] := If[x > y, node[x, y], node[y, x]] (* <-- > THERE! *) > add[node[x_, lower_], y_node] := > Which[y >= node[x], node[x, lower, y], > y <= node[lower], node[lower, y, x], True, node[y, lower, x]] > add[node[x_, lower_, higher_], y_node] /; > node[y] <= node[x] := node[x, add[lower, y], higher] > add[node[x_, lower_, higher_], y_node] := node[x, lower, add[higher, > y]] > > Where I have a pointer is the code that prevents adding right-offspring > to a leaf node. That avoids nodes like your node[a,Null,c]. When you > would have node[a,b,Null], I have node[a,b]. When you would have > node[a,Null,Null], I use a itself. > > Timing and space requirements are much better now: > > SeedRandom[5]; > nums = Null > Timing[Do[nums = add[nums, Random[]], {5000}]; ] > > {2.109*Second, Null} > > LeafCount[nums] > ByteCount[nums] > Count[nums, Null, Infinity] > Count[nums, node[_], Infinity] > Count[nums, node[_, _], Infinity] > Count[nums, node[_, _, _], Infinity] > Count[nums, node[___], Infinity] > Depth[nums] > > 7852 (* 48% fewer leaf expressions, > mostly due to Nulls and right-offspring eliminated *) > 165624 (* 31% less storage *) > 0 (* no Nulls, versus 5001 *) > 0 (* no leaf nodes, versus 1669 *) > (* no nodes without left-offspring, versus 2458 *) > 705 (* nodes without right offspring, versus 2543 *) > 2146 (* nodes with both left and right offspring, versus 1667 *) > 2851 (* total nodes *) > 21 (* 21 tree levels versus 27 *) > > The logical structure is identical to yours except that there are no > nodes with only right-offspring. This incidentally tends to reduce tree > depth. > > The storage format is far different: there are no trivial (childless) > nodes, and nodes with left-offspring but no right-offspring are stored > without a Null on the right. > > I could make this quite a bit faster, I think, if I spent time on the > code to eliminate changes to Less, Greater, etc. and the frequent > nesting followed by unnesting that goes on in the algorithm. It might > take twice as much code, however, so I like it as is. > > You're probably better off storing these things in a heap, of course. > > Or -- better yet -- use the built-in Sort and Ordering functions. > > Bobby Treat > > -----Original Message----- So Slow? > > > > 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} > > 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? > > > Husain > > > <><><><><><><><><><><><> Johannes Ludsteck Economics Department University of Regensburg Universitaetsstrasse 31 93053 Regensburg ==== >>So far, so good. It seems that you want these 11 numbers, OK? The problem now, I think, is that this is just a string and I can think of no easy way to convert it precisely into a list of 11 real numbers. You could try StringToStream followed by a Read from that stream. Bobby Treat -----Original Message----- None]; This allowed me to examine your records and I found out that in this way each record comes out as a list of length 1: In[2]:= Head[a[[1]]] Out[2]= List In[3]:= Length[a[[1]]] Out[3]= 1 That is, In[3]:= a[[1]] Out[3]= 317. 367. -115. 126. 146. -410. -426.000000EF 75.} In[4]:= StringLength[a[[1,1]]] Out[4]= 140 and the characters you want are In[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 problem now, I think, is that this is just a string and I can think of no easy way to convert it precisely into a list of 11 real numbers. Then, I suggest you read 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]= .,- 115.,126.,146.,-410.,-426.000000EF,75.} In[8]:= Head[b[[1]]] Out[8]= List In[9]:= Length[b[[1]]] Out[9]= 19 so that each record is now a list of 19 strings. What you want is strings 6 to 16, but converted to reals (unless I'm being presumptuous). This will achieve 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 for the whole file like this: In[11]:= ToExpression[Take[#,{6,16}]&/@b]; I hope this will solve your problem. Tomas Garza Mexico City > ----- Original Message ----- > Sent: Friday, September 13, 2002 12:14 AM 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 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. > -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? -------------------------------------------------------------------- ==== 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 to x.*Button[More[Ellipsis], ButtonData :> Floor, Active -> True, ButtonStyle -> RefGuideLink] OK. Change ButtonData :> Floor to ButtonData :> Ceiling, and push Ctrl-Shift-E again. Push the More... button, and you should go to Ceiling in the Help Browser, not Floor. Another method is to click Input>Create Button>RefLink and type in Ceiling. 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 clues to your options. Clues are all you get in Mathematica, so get used to it! Bobby Treat -----Original Message----- ==== Since r1 and r2 only appear squared, you can do it this way: Simplify[Solve[FR == Pi*r1Sq - Pi*r2Sq, r1Sq]] {{r1Sq -> FR/Pi + r2Sq}} or Simplify[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 numbers have two square roots, but we usually ignore that. Bobby Treat -----Original Message----- http://www.verbeia.com/mathematica/tips/Links/Tricks_lnk_41.html I thin, one has to to replace the pattern i Sqrt[-a_] by Sqrt[(i Sqrt[-a_])^2] and then one has to simplify it? Peter Klamser ==== > My question; The process of moving (* *) step by step through the > program is quite tedious when the code has lots more lines. What I would > like is a meta-program which (like FoldList) does this job for me. The > output of this meta-program is the list of outputs of each line in the > module, probably best printed as a column. Beside the Print statements, sometimes I do the following. Put the function to 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 global within the new context. Then I can examine the values of all these variables after execution of the function and can often find the error. If the error is caused by a complex expression of nested functions, then I unwind the complex expression, adding more temporary variables, until I see the problem. Then I think twice before recomplexifying. The two advandages of a special context are (1) I don't get the previously local symbols mixed up with other symbols and (2) I can examine all of them and only them with TableForm[{#,ToExpression[#]}&/@Names[mynewcontext`*]] Once I do this, I often leave the new context in place. Mathematica seems to be able to handle a large number of contexts efficiently. Tom Burton ==== I have quite an easy and annoying problem with mathematica: I need to define a function f(x,y) which takes some values for x=0,2pi,4pi (indepently of y) and has a different expression for all the other values of y. This is easily done for one-dimensional functions but I am in serious troubles for my two-dimensional problem: any suggestion? Fabio Reply-To: kuska@informatik.uni-leipzig.de ==== Clear[f] f[0, _] := q f[Pi, _] := p f[2Pi, _] := r f[x_, y_] := x^2*y^2 ??? Jens > > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio There were some typos in my last message. It should have read: Let the known values of the function at x={0,2Pi,4Pi} be {f0,f2,f4}. Your conditions can be met by f(x,y)=x(x-2Pi)(x-4Pi)g(y)+h(x), where {h(0),h(2Pi),h(4Pi)}={f0,f2,f4}. An h(x) can be found by quadratic interpolation: h[x]= a + bx + cx^2; Solve[{a==f0,a+2Pi b +(2Pi)^2 c==f2, a+4Pi b+(4Pi)^2 c==f4},{a,b,c}] {{b -> -(3*f0 - 4*f2 + f4)/(4*Pi), c -> -(-f0 + 2*f2 - f4)/(8*Pi^2), a -> f0}} ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio Let the known values of the function at x={0,2Pi,4Pi} be {f0,f2,f4}. Your conditions can be met by f(x,y)=x(x-2Pi)(x-4Pi)g(y)+h(x), where {h(0),h(2Pi),h(4Pi)}={f0,f2,f4}. An h(x) can be found by quadratic interpolation: h[x]= a + bx + cx^2; Solve[{a==f0,a+2Pi b +(2Pi)^2+(2Pi)^2 c==f2, a+4Pi b+(4Pi)^2 c==f4] {{b -> -(3*f0 - 4*f2 + f4)/(4*Pi), c -> -(-f0 + 2*f2 - f4)/(8*Pi^2), a -> f0}} Maurice ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio Something like this? In[1]:= f[x_,y_] := If[Mod[x,2*Pi] === 0, Exp[x], Sin[y]+x] In[2]:= f[4*Pi, y] 4 Pi Out[2]= E In[3]:= f[1, y] Out[3]= 1 + Sin[y] -- Bhuvanesh, Wolfram Research. ==== > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio > f[0, y_] := 5 f[2 Pi, y_] := 7 f[4 Pi, y_] := -3 f[x_ /; x < 0, y_] := x y f[x_ /; 0 < x < 2 Pi, y_] := x + y f[x_ /; 2Pi < x < 4 Pi, y_] := x - y f[x_ /; 4Pi < x, y_] := 2x y ==== >-----Original Message----- >Sent: Monday, September 16, 2002 6:34 AM >I have quite an easy and annoying problem with mathematica: >I need to define a function f(x,y) which takes some values for >x=0,2pi,4pi (indepently of y) and has a different expression for all >the other values of y. This is easily done for one-dimensional >functions but I am in serious troubles for my two-dimensional problem: >any suggestion? >Fabio It's difficult to guess what you wanted to attain and what your problems were. Perhaps this example might help you: In[11]:= f[x_, _] /; Mod[x, 2Pi] == 0 := x/(2Pi) In[12]:= f[x_, y_] := x + y In[13]:= epsilon = $MachineEpsilon Out[13]= 2.220446049250313*^-16 In[14]:= f[6Pi(1 + epsilon Sin[#]), #] & /@ Range[0, 4Pi, Pi 10^-1] Out[14]= {3, 3., 19.4779, 19.792, 20.1062, 20.4204, 20.7345, 21.0487, 21.3628, 3., 3, 22.3053, 22.6195, 22.9336, 23.2478, 23.5619, 23.8761, 24.1903, 24.5044, 24.8186, 3, 3., 25.7611, 26.0752, 26.3894, 26.7035, 27.0177, 27.3319, 27.646, 3., 3, 28.5885, 28.9027, 29.2168, 29.531, 29.8451, 30.1593, 30.4734, 30.7876, 31.1018, 3} Look close at the values returned (compare with epsilon Sin[Range[0, 4Pi, Pi 10^-1]]), also to recognize the dangers of such a definition. -- Hartmut ==== I am new with Mathematica, I have one question, I know that the sollution might be very easy, but I wasn't able to find it by now. I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 Maciej ==== Although it is not outstanding, I prefer to write your equation in the form: 9*x^2+4*x*y+6*y^2==400 In order to plot the ellipse you can use the package Graphics`ImplicitPlot` in this way: In[1]:= << Graphics`ImplicitPlot` In[2]:= ImplicitPlot[ 9*x^2 + 4*x*y + 6*y^2 == 400, {x, -7, 7}, PlotStyle -> RGBColor[1, 0, 0]]; Germ.87n Buitrago A. ----- Original Message ----- > 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > Maciej > ==== first this in not an ellipse. the ellipse generic formula is : (x^2)/(a^2)+(y^2)/(b^2) = 0. I guest that you want report a graph of the solution y of the equation: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 for x varying into a given range. As you can veryfing using: Solve[0.09 x^2 + 0.04 x y + 0.06 y^2 == 4, y] the solutins are two: {{y -> 8.333333333333334*(-0.04*x - 0.1414213562373095*Sqrt[48.00000000000001 + 0.*x - 1.*x^2])}, {y -> 8.333333333333334*(-0.04*x + 0.1414213562373095*Sqrt[48.00000000000001 + 0.*x - 1.*x^2])}} than you can construct a function: function1[x_] = 8.333333333333334*(-0.04*x - 0.1414213562373095*Sqrt[48.00000000000001 - *x^2])}, that is a real value only if (48.00000000000001 - *x^2)>0, i.e. if approximatively -6 True] the same for the other soluztion. good luck -u pimak ha scritto nel messaggio > I am new with Mathematica, I have one question, > I know that the sollution might be very easy, but I wasn't able to > find it by now. > I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > Maciej > Reply-To: murray@math.umass.edu ==== One way is: ContourPlot[0.09 x^2 + 0.04 x y + 0.06 y^2, {x, -10, 10}, {y, -10, 10}, Contours -> {4}, PlotPoints -> 50, ContourShading -> False]; > I am new with Mathematica, I have one question, > I know that the sollution might be very easy, but I wasn't able to > find it by now. > I would like to draw an ellipse, the formula let's say is as follows: > > > > 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > > > Maciej > > > > > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 Reply-To: kuska@informatik.uni-leipzig.de ==== Needs[Graphics`ImplicitPlot`] ImplicitPlot[0.09 x^2 + 0.04 x y + 0.06 y^2 == 4, {x, -10, 10}, {y, -10, 10}] may help. Jens > > I am new with Mathematica, I have one question, > I know that the sollution might be very easy, but I wasn't able to > find it by now. > I would like to draw an ellipse, the formula let's say is as follows: > > 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 > > > Maciej ==== I pretend to know how many times the function f has to be evaluated when using NDSolve to solve a differential equation. I've tried : cont=0; f[x_]:=(cont++;x^2); NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number of funtion evaluations. How can I obtain it? ==== > I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : > > cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] > > I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? > you need to make sure that the function f[x] is evaluated only when it gets a numeric argument. Otherwise, Mathematica expands f[x] symbolically to the expression x^2 before NDSolve is called. Writing your code as follows will solve your problem: cont=0; f[x_?NumericQ]:=(cont++;x^2); NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] Eckhard Hennig ==== > I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : > > cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] > > I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? cont=0; f[x_?NumericQ]:=(cont++;x^2) NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] -> cont = 94 -Jim ==== Try the following: Clear[f] cont=0; f[x_?NumericQ]:=(cont++;x^2); NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] The problem you are encountering occurs because NDSolve evaluates it's inputs first, and so NDSolve is trying to solve the differential equation y''[x]+y[x]==x^2 instead of y''[x]+y[x]==f[x]. By restricting the definition of f to evaluate only when it's input is numeric, NDSolve will keep the f[x] in the differential equation. I've included a Clear[f] statement just in case the old definition of f was still there. Carl Woll Physics Dept U of Washington I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? > Reply-To: kuska@informatik.uni-leipzig.de ==== and after cont = 0; f[x_?NumericQ] := (cont++; x^2); NDSolve[{y''[x] + y[x] == f[x], y[0] == 1, y'[0] == 0}, y, {x, 0, 6}] cont is 93. Thats because *you* gave only a blank pattern for f[x_] and NDSolve[] evaluate it to compile the right hand sides or translate it to an internal function. So *your* function is only once when Mathematica can include it into it's internal function for the right hand sides. Jens > > I pretend to know how many times the function f has to be evaluated when > using NDSolve to solve a differential equation. > I've tried : > > cont=0; > f[x_]:=(cont++;x^2); > NDSolve[ {y''[x]+y[x]==f[x],y[0]==1,y'[0]==0},y,{x,0,6}] > > I obtain the solution of the ODE but cont returns 1 instead the number > of funtion evaluations. > How can I obtain it? > ==== Fabio, f[x_ /; IntegerQ[Rationalize[x/(2Pi)]], y] := g[x] f[x_, y_] := h[x, y] f[# Pi, y] & /@ Range[10] {h[Pi, y], g[2*Pi], h[3*Pi, y], g[4*Pi], h[5*Pi, y], g[6*Pi], h[7*Pi, y], g[8*Pi], h[9*Pi, y], g[10*Pi]} f[2.0Pi, y] g[6.28319] f[3.5, y] h[3.5, y] f[4.01Pi, 5] h[12.5978, 5] You can use a second argument in Rationalize to control how small a rationalization error is allowed and there is always the question about what domain around 2nPi you want to include in the first definition. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ ==== yes, this is a comon problem. You can either do: y=If[x>1000, ToExpression[BigVariable][[x]],x] ] or, maybe more readable, declare at the begging of ThisPackage: bigvar := bigvar = ToExpression[OtherPackage`BigVariable]; and then y=If[x>1000, bigvar, x] (* ************************** *) Alternatively you can create .mx files which load much quicker than .m files. It would be really nice if WRI could investigate why loading larger .m files is so slow ( I suspect it has to do something with the speed of side effects like DownValues declarations etc., but I don't know ). Rolf Mertig Mertig Consulting http://www.mertig.com ================================== DeclareePackage[OtherPackage`, {BigVariable} ]. The idea was to prevent the loading of a large file in routine cases. However, when ThisPackage` defines its functions, inside the Private` area, it includes a conditional call to BigVariable. It turns out that OtherPackage is loaded when that function is defined. I was wondering if there is a way to avoid this. Roughly speaking, here is the setting: BeginPackage[ OtherPackage` ] BigVariable::usage=example Begin[Private`] BigVariable=Table[x y,{x,1000},{y,1000}] End[ ] EndPackage[ ] BeginPackage[ ThisPackage` ] function::usage=example Begin[Private`] function[x_]:=Module[{y}, y=If[x>1000,BigVariable[[x]],x] ] End[ ] EndPackage[ ] I don't want OtherPakage to be loaded unless function[x] is called with x>1000 but it loads when function is defined. Any ideas? Nicholas ==== I was looking for a function that can convert numbers between bases. For example, going from Base 3 to Base 9, or from Base 16 to Base 8. It seems like I have to a few steps and then use BaseForm to convert to the desired end base. Is there a single command or simple function to do such conversions? For example, ConvertBase[from_, to_, num_] would convert from base to base 9 using the number num as the number to convert (it would best be allowed to let users input in that specific base since they'd be going from base 3 to base 9, for example so maybe num is needed at all). ==== Dear NG Mabye this is too simple, but I cant just figure it out I want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]] and R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= Dear NG > Mabye this is too simple, but I cant just figure it out I want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]] > and > R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= > after that I hope to be able to calculate the integral : a = (1/y[T])* > NIntegrate[R[InvFunction[y[t]]*Cos[y[t]], {y[t], 0, y[T]}] it works with a constant instead of R[t]. Hope you can help, and that the above is understandable. > Martin Skogstad ==== Martin, In a post a while ago, I introduced a function called NInverse which ought to be able to help you out. The message can be found at http://library.wolfram.com/mathgroup/archive/2001/Jun/msg00125.html The output of NInverse (in your case) is a function which given a value of y returns the corresponding value of t. In your case, you would use NInverse something like the following: NInverse[y, {t0,y0}, {yy, ymin, ymax}] You will probably get some error messages, but the answer should be okay. The function NInverse can be improved (witness the inclusion of yy above), and I will post an improved version sometime. Carl Woll Physics Dept U of Washington > Dear NG > Mabye this is too simple, but I cant just figure it out I want to get an inverse function for y[t] where y[t_]:=NIntegrate[R[x]^4,{x,0,t}] /. ndsolution[[1]] > and > R[t] is an interpolatingfunction(R>0 from NDSolve) on the interval 0= NIntegrate[R[InvFunction[y[t]]*Cos[y[t]], {y[t], 0, y[T]}] it works with a constant instead of R[t]. Hope you can help, and that the above is understandable. > Martin Skogstad > ==== There is a very nice java applet at http://statman.stat.sc.edu/~west/javahtml/classes/ , in which you can include your own data by replacing what is in the Applet with your own, which gives you a real time histogram plot and lets you alter the bin width and see how this effects the histogram....it wasnt until I saw this that i understood the significance of choosing the bin width......jerry blimbaum -----Original Message----- http://www.mathstatica.com for details. Obviously, it is less expensive to write your own functions. Just recently in message Mark Fisher posted code that addresses the empirical CDF. However, in this code you may want to replace 1/n with 1/(n+1) or (j-0.5)/n depending on your application. Note, these will have no significant effect for large data sets. The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. ==== A while back someone asked if Mathematica could plot data one point at a time....most answers were no, with one exception, where someone showed how to use the same Graphic Cell repeatedly....here is some Mathematica, JLink program that will do just that... << JLink` InstallJava[CommandLine -> c:j2sdk1.4.1binjava.exe] (* or set command line to where your java.exe is *) UseFrontEndForRendering = False; createWindow[] := Module[{frame}, frame = JavaNew[com.wolfram.jlink.MathFrame, Drawing Sine Wave Animation One Point at a Time]; drawArea = JavaNew[com.wolfram.jlink.MathCanvas]; drawArea@setUsesFE[UseFrontEndForRendering]; drawArea@setSize[800, 600]; JavaBlock[frame@setLayout[JavaNew[java.awt.BorderLayout]]; frame@add[drawArea, ReturnAsJavaObject[BorderLayout`CENTER]]; frame@pack[]; points = Range[data // Length] frame@setSize[800, 600]; frame@setLocation[200, 200]; JavaShow[frame]]; frame ] data = Table[{x, Sin[x]}, {x, -0.0000000000001, 2 Pi, .1}]; frame[n_] := ListPlot[Take[data, {1, n}], PlotRange -> {{0, 2 Pi}, {-1.5, 1.5}}, PlotStyle -> {PointSize[.005], Hue[0]}, DisplayFunction -> Identity] drawPoints[ptNow_] := Show[frame[ptNow], AspectRatio -> Automatic]; points = Range[data // Length]; AnimationPlot[pt_List] := JavaBlock[ Block[{frm}, frm = createWindow[]; Map[(obj = drawPoints[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; Pause[0.0001];) &, pt]; ] ] AnimationPlot[points] jerry blimbaum NSWC panama city, fl ==== I never liked the function, but now I have need of it. I hope someone can help me see the way to implement it. For a class I am teaching I want to write a simple function that does a random search for a function's maxima. I feed the function N randomly generated inputs and look at the outputs. Provided N is large enough, the largest of the outputs I obtain should be near the function's maximum value. What I want to be able to do is to identify the input that gave me that largest output. Any ideas? My only idea is this: create a table of pairs {output, input{ and find the element of the table that has the largest first entry. This will give me the input I seek. Is there a slick way of doing this in mathematica? -- Jason Miller, Ph.D. Division of Mathematics and Computer Science Truman State University 100 East Normal St. Kirksville, MO 63501 http://vh216801.truman.edu 660.785.7430 ==== Here's one way: argMax::usage = argMax[f, domain] returns the element of domain for which f of that element is maximal -- breaks ties in favor of first occurrence.; SetAttributes[argMax, HoldFirst]; argMax[f_, dom_List] := Fold[If[f[#1]>=f[#2], #1, #2]&, First[dom], Rest[dom]] And here's another way (defining it in terms of tupleMax)... tupleMax::usage = tupleMax[list] returns the tuple that is lexicographically maximal.; tupleMax[l_List] := Fold[If[OrderedQ[{#1, #2}], #2, #1]&, First[l], Rest[l]] argMax[f_, dom_List] := tupleMax[{f[#],#}& /@ dom][[2]] --- / FROM Jason Miller AT 02.09.18 06:18 (Today) / --- > I never liked the function, but now I have need of it. I hope > someone can help me see the way to implement it. > > For a class I am teaching I want to write a simple function that does > a random search for a function's maxima. I feed the function N > randomly generated inputs and look at the outputs. Provided N is > large enough, the largest of the outputs I obtain should be near the > function's maximum value. > > What I want to be able to do is to identify the input that gave me > that largest output. Any ideas? > > My only idea is this: create a table of pairs {output, input{ and > find the element of the table that has the largest first entry. This > will give me the input I seek. Is there a slick way of doing this in > mathematica? -- -- -- -- -- -- -- -- -- -- -- -- Daniel Reeves http://ai.eecs.umich.edu/people/dreeves/ In science it often happens that scientists say, 'You know that's a really good argument; my position is mistaken,' and then they would actually change their minds and you never hear that old view from them again. They really do it. It doesn't happen as often as it should, because scientists are human and change is sometimes painful. But it happens every day. I cannot recall the last time something like that happened in politics or religion. -- Carl Sagan, 1987 CSICOP Keynote Address Reply-To: kuska@informatik.uni-leipzig.de ==== fun[x_, y_] := x^2 + y^2 RandomMin[n_Integer] := First[Sort[ {#, fun @@ #} & /@ Table[{Random[], Random[]}, {n}], Last[#1] < Last[#2] &]] should do it. Jens > > I never liked the function, but now I have need of it. I hope > someone can help me see the way to implement it. > > For a class I am teaching I want to write a simple function that does > a random search for a function's maxima. I feed the function N > randomly generated inputs and look at the outputs. Provided N is > large enough, the largest of the outputs I obtain should be near the > function's maximum value. > > What I want to be able to do is to identify the input that gave me > that largest output. Any ideas? > > My only idea is this: create a table of pairs {output, input{ and > find the element of the table that has the largest first entry. This > will give me the input I seek. Is there a slick way of doing this in > mathematica? > > -- > Jason Miller, Ph.D. > Division of Mathematics and Computer Science > Truman State University > 100 East Normal St. > Kirksville, MO 63501 > http://vh216801.truman.edu > 660.785.7430 Reply-To: murray@math.umass.edu ==== The same principles that allow particular cases for defining a function of a single variable would apply here, because Mathematica applies particular rules before it applies general ones. For example: f[0, y_] := 0 f[2 Pi, y_] := y - 2 f[4 Pi, y_] := y - 4 f[x_, y_] := x^2 + y^3 This will do exactly what it looks like it does! If you have a general family of particular cases, say at all even integral multiples of Pi, then you could use something like the following in place of the first three lines above: f[k_ Pi, y_] := y - k /; IntegerQ[k] && EvenQ[k] There are variants as to where to place the condition IntegerQ[k] && EvenQ[k], for example: f[k_ Pi , y_] /; IntegerQ[k] && EvenQ[k] := y - k f[k_ Pi /; IntegerQ[k] && EvenQ[k], y_] := y - k > I have quite an easy and annoying problem with mathematica: > I need to define a function f(x,y) which takes some values for > x=0,2pi,4pi (indepently of y) and has a different expression for all > the other values of y. This is easily done for one-dimensional > functions but I am in serious troubles for my two-dimensional problem: > any suggestion? > Fabio > > > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 ==== >>and has a different expression for all the other values of y. Do you mean all the other values of x? You can't expect to make yourself understood to Mathematica, if you don't say what you mean. Mathematica can't guess, like we can. If that's what you meant, it's really easy: f[0 | N[0], y_] := y f[2*Pi | N[2*Pi], y_] := y^2 f[4*Pi | 4.*Pi, y_] := y^3 f[x_, y_] := y^4 If the first three of those expressions are supposed to be the same, you can substitute f[0 | N[0] | 2*Pi | N[2*Pi] | 4*Pi | 4.*Pi, y_] := y^3 Bobby Treat -----Original Message----- Fabio ==== How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f How can I do that? Please suggest. Raj ==== Well, you can just solve for h. However, in this case there isn't a symbolic solution. How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f > How can I do that? Please suggest. Raj > Reply-To: kuska@informatik.uni-leipzig.de ==== Solve[ f=Exp[-h](a*h+b*h^2),h] will not help you but you can try to invert the series expansion as long as the function is monoton ser = Series[Exp[-h](a*h + b*h^2), {h, 0, 4}]; InverseSeries[ser, f] Jens > > > How can I invert a funcion? For example > > In:=f[h_]:=Exp[-h](a*h+b*h^2); > > I want to invert it as > > h as a function of f > > How can I do that? > > Please suggest. > > Raj ==== I don't have any idea about how to solve next problem. Back space key when I am in the front end don't work correctly. It advances instead of go back and there is pointer mark of the mouse looks like a hand instead of an arrow, and this don't work fine too. Configuration one? How can I solve this? Note: This problem seems to appear just in my workspace i mean this not happen for other users. Cesar. __________________________________________________ Do you Yahoo!? Yahoo! News - Today's headlines http://news.yahoo.com ==== > I don't have any idea about how to solve next problem. > > Back space key when I am in the front end don't work > correctly. It advances instead of go back and there is > pointer mark of the mouse looks like a hand instead > of an arrow, and this don't work fine too. > Configuration one? How can I solve this? > Note: This problem seems to appear just in my > workspace > i mean this not happen for other users. > > Cesar. > > > __________________________________________________ > Do you Yahoo!? > Yahoo! News - Today's headlines > http://news.yahoo.com > Pressing the 'Num'-Key maybe solves your problem: If you switch off the 'Num Lock' your 'hand pointer mark' should turn into an 'arrow pointer mark' and you can place the cursor in a notebook. You get more details on -- Rainer Gruber ==== Help! After using SetOptions[Graphics3D, ...] I am trying to set the default options of Graphics3D back to what they were when I started up Mathematica. I cannot find a command to do this. Is this possible? ==== o = Options[Graphics3D]; (* save the original options *) SetOptions[Graphics3D, ...]; (* mess with them *) SetOptions[Graphics3D, Sequence@@o]; (* restore them *) --- / FROM David Sagan AT 02.09.18 06:29 (Today) / --- > Help! > > After using SetOptions[Graphics3D, ...] I am trying to set the default > options of Graphics3D back to what they were when I started up > Mathematica. I cannot find a command to do this. Is this possible? > -- -- -- -- -- -- -- -- -- -- -- -- Daniel Reeves http://ai.eecs.umich.edu/people/dreeves/ The idea of programming in a low level language like C will seem as specialized and esoteric as programming in microcode or assembler seems today. -- Stephen Wolfram, creator of Mathematica Reply-To: kuska@informatik.uni-leipzig.de ==== Hmm, oldOptions=Options[Graphics3D]; SetOptions[Graphics3D,Boxed->False] (* do something with it *) SetOptions[Graphics3D, Sequence @@ oldOptions] works fine. Jens > > Help! > > After using SetOptions[Graphics3D, ...] I am trying to set the default > options of Graphics3D back to what they were when I started up > Mathematica. I cannot find a command to do this. Is this possible? > ==== > > This code is almost identical to yours in principle, yet 30% faster: > > (compared with the code in your notebook, not the code in the post > below) > > ClearAll[emptyTree, treeInsert]; > emptyTree = {}; > > treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] /; SameQ[tree[[2]], elem] := tree > treeInsert[tree_, elem_] /; OrderedQ[{tree[[2]], elem}] := > {First[tree], tree[[2]], treeInsert[Last[tree], elem]} > treeInsert[tree_, elem_] := {treeInsert[First[tree], elem], tree[[2]], > Last[tree]} > > Here's an even simpler version, same speed: > > ClearAll[emptyTree, treeInsert]; > emptyTree = {}; > > treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] := Which[ > SameQ[tree[[2]], elem], tree, OrderedQ[{tree[[2]], elem}], > {First@tree, tree[[2]], treeInsert[Last@tree, elem]}, > True, {treeInsert[First@tree, elem], tree[[2]], Last@tree}] I had tried variations on this but they all seemed ever so slightly slower. Might be version an OS dependent. > I see one obvious advantage of your algorithm over Husain's and my > earlier code; though I'm not sure it explains its better behavior. That > is, while my algorithm made pattern matching more burdensome, yours > virtually eliminated it. > > Also, the biggest improvement I've seen comes simply from replacing Null > with anything else in Husain's code. Again, that seems to suggest that > time spent on pattern matching is the problem. All the algorithms do > approximately the same real work on the tree structure. > > I really like how Flatten changes your tree into a sorted list. Very > nice! Goes by the name of tree sort. Using Flatten is basically a shortcut for walking the tree left-to-right. > Bobby Treat It seems I did not look hard enough at the original post or the follow-ups. In point of fact, regarding speed, there IS no obvious advantage of my code over that first version. The advantage is there, of course, as timing checks indicate. But it is quite far from obvious. The reason is related to the (rare) need for Update. It is pointed out in the manual that infinite evaluation is not in fact possible (no surprise thus far). A consequence is that Mathematica requires internal optimization features to keep reevaluation to a minimum. Update may be required in cases where such optimizations are overzealous. What we have in the case of this example is, roughly, the opposite. The code that determines need for reevaluation is simply not working sufficiently well. It does make the correct determination, but only after looking over the entire structure that is being evaluated. As we have a structure growing linearly in the number of iterations, and it gets mostly traversed each iteration, the algorithmic complexity becomes at least O(n^2). Not a disaster unless the appropriate complexity is smaller, which was the case for this example. This is not a bug insofar as it is a (regretably) necessary consequence of Mathematica evaluation semantics. The problems it can cause are all the same quite undesirable. We've made some inroads on this problem by enlarging substantially the class of expressions for which reevaluation may be quickly short-circuited, with the idea of fixing all but the most pathological of examples. The status of that work is unfortunately not known to me at present, though I'll try to find out about it. Daniel Lichtblau Wolfram Research ==== 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 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! Bobby Treat -----Original Message----- > (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} > 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? > > Husain I'll respond to your third question first. No, use of Compile will not help. You do not have a tensor structure and moreover it will copy its arguments. Hence invoking it within a loop would be quite slow for a problem where the argument grows in size. One thing you did not check is the actual run-time complexity of your code. 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 I would 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'll give some different code that has the desired complexity. Note that some of this, and code very similar to that below, is discussed 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 they are flattened the tree is automatically sorted. You might (or might not) regard this as an added benefit. leftsubtree[node[left_, _, _]] := left rightsubtree[node[_, _, right_]] := right nodevalue[node[_, val_, _]] := val emptyTree = 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 Second We 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]= True Also we will observe that the maximum depth is reasonable. In[43]:= Depth[ff1k] Out[43]= 23 In 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 Second In[45]:= tt4k = First[Timing[ff4k = node[]; Do[ff4k = treeInsert[ff4k, ee[[j]]], {j,4000}];]] Out[45]= 0.73 Second In[47]:= tt8k = First[Timing[ff8k = node[]; Do[ff8k = treeInsert[ff8k, ee[[j]]], {j,8000}];]] Out[47]= 1.58 Second In[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 Second This is not of blinding speed but it has the advantage of exhibiting the appropriate run-time complexity. One can, with careful coding, cut down on tree size but if you check with LeafCount you will find that the version above is already not too wasteful (3x larger than #values stored). Moreover the code needed would run a bit slower as it would have more cases to check. As for removing nodes, I think you will need to use some form of held attribute so as to avoid copying the entire tree when you alter elements. Daniel Lichtblau Wolfram Research ==== Daniel, I'd say your algorithm (as an ALGORITHM) is precisely the same as Husain's. The implementation is different, but the logical steps are the same (except perhaps for <= vs. <), and so is the logical structure of the tree produced. Even the storage method is pretty much the same. Using {} instead of Null and List instead of 'node', and putting values in the middle position, doesn't add up to a change that could affect algorithmic complexity. Even the fact that Flatten gives a sorted List with your implementation is something you get for free, and the advantage comes only when it's time to output a sorted list. It has nothing to do with the work of building the tree. Algorithmic complexity (absent hidden factors under the kernel's control) is precisely the same for your solution and Husain's (mine too, I think). The speed differences we're seeing have to do with nuances of the kernel, pattern matching costs, etc. Our three nearly equivalent algorithms simply incur different hidden costs. That's the case with many of the problems that turn into speed wars among us. We compare implementation speed (including hidden costs), not pure algorithmic complexity. Compiled code or packed arrays often make all the difference, and it usually happens in the background where we can't see it. As you've hinted below, the vagaries of Update can make a linear algorithm quadratic, but may NOT so plague a slightly different implementation of the very same algorithm. So... I'm suggesting we might want to be careful when we leap to conclusions about algorithmic complexity based on a few timed experiments. Bobby Treat -----Original Message----- > ClearAll[emptyTree, treeInsert]; > emptyTree = {}; > > treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] /; SameQ[tree[[2]], elem] := tree > treeInsert[tree_, elem_] /; OrderedQ[{tree[[2]], elem}] := > {First[tree], tree[[2]], treeInsert[Last[tree], elem]} > treeInsert[tree_, elem_] := {treeInsert[First[tree], elem], tree[[2]], > Last[tree]} > > Here's an even simpler version, same speed: > > ClearAll[emptyTree, treeInsert]; > emptyTree = {}; > > treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree} > treeInsert[tree_, elem_] := Which[ > SameQ[tree[[2]], elem], tree, OrderedQ[{tree[[2]], elem}], > {First@tree, tree[[2]], treeInsert[Last@tree, elem]}, > True, {treeInsert[First@tree, elem], tree[[2]], Last@tree}] I had tried variations on this but they all seemed ever so slightly slower. Might be version an OS dependent. > I see one obvious advantage of your algorithm over Husain's and my > earlier code; though I'm not sure it explains its better behavior. That > is, while my algorithm made pattern matching more burdensome, yours > virtually eliminated it. > > Also, the biggest improvement I've seen comes simply from replacing Null > with anything else in Husain's code. Again, that seems to suggest that > time spent on pattern matching is the problem. All the algorithms do > approximately the same real work on the tree structure. > > I really like how Flatten changes your tree into a sorted list. Very > nice! Goes by the name of tree sort. Using Flatten is basically a shortcut for walking the tree left-to-right. > Bobby Treat It seems I did not look hard enough at the original post or the follow-ups. In point of fact, regarding speed, there IS no obvious advantage of my code over that first version. The advantage is there, of course, as timing checks indicate. But it is quite far from obvious. The reason is related to the (rare) need for Update. It is pointed out in the manual that infinite evaluation is not in fact possible (no surprise thus far). A consequence is that Mathematica requires internal optimization features to keep reevaluation to a minimum. Update may be required in cases where such optimizations are overzealous. What we have in the case of this example is, roughly, the opposite. The code that determines need for reevaluation is simply not working sufficiently well. It does make the correct determination, but only after looking over the entire structure that is being evaluated. As we have a structure growing linearly in the number of iterations, and it gets mostly traversed each iteration, the algorithmic complexity becomes at least O(n^2). Not a disaster unless the appropriate complexity is smaller, which was the case for this example. This is not a bug insofar as it is a (regretably) necessary consequence of Mathematica evaluation semantics. The problems it can cause are all the same quite undesirable. We've made some inroads on this problem by enlarging substantially the class of expressions for which reevaluation may be quickly short-circuited, with the idea of fixing all but the most pathological of examples. The status of that work is unfortunately not known to me at present, though I'll try to find out about it. Daniel Lichtblau Wolfram Research ==== I'm curious, why the built-in boolean functions And and Or aren't commutative? Attributes/@{Or,And}//ColumnForm {Flat, HoldAll, OneIdentity, Protected} {Flat, HoldAll, OneIdentity, Protected} However, the arithmetical functions are Orderless: Attributes/@{Plus,Times}//ColumnForm {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} ------------------- Evgeni Trifonov Vladivostok, Russia ==== Evgeni, Note that both And and Or can return a value without evaluating all of their arguments. For example, if the first argument to And is False, there is no reason to look at the other arguments. Suppose a user knows that one of the arguments is usually false, and so would like to look at that argument before any of the others, to avoid unneeded computations of the other arguments. He would put that argument first. If Mathematica turned around and sorted the arguments (which is what happens when a function is orderless), then that argument might end up being evaluated last. If the arguments take a significant amount of time to compute, then sorting first may cause the function to take much longer to evaluate. At any rate, if the above is not a concern for you, you may always change the attributes of And and Or to anything you want. Carl Woll Physics Dept U of Washington ----- Original Message ----- > However, the arithmetical functions are Orderless: Attributes/@{Plus,Times}//ColumnForm {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} > {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} ------------------- > Evgeni Trifonov > Vladivostok, Russia > ==== I have defined two functions (Math 4.1) In[1]:= integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t]; In[2]:= integrate[Exp[(a_.)*tau], t_]:=(E^(a*t)-1)/a/; FreeQ[a,t]&&FreeQ[a,tau]; when I applied these functions the solution is different if the coefficient is the letter d or lower (solution fine) or f or higher (solution wrong) . Here is an example: Using letter f In[3]:=integrate[f Exp[-0.8316*tau], t] Out[3]:=integrate[f, t]/E^(0.8316*tau) (*wrong*) Using letter a (the solution is rigth In[4]:=integrate[a Exp[-0.8316*tau], t] Out[4]:=-1.20250*a*(-1 + E^(-0.8316*t)) What it wrong? Guillermo Sanchez --------------------------------------------- This message was sent using Endymion MailMan. ==== Neither of your solutions are wrong according to your rules. Lets step through them In[3]:=integrate[f Exp[-0.8316*tau], t] lexographical (sp) order as In[3]:=integrate[Exp[-0.8316*tau] f, t] It then applies rule 1: integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t] Well, The term Exp[-0.8316*tau] contains no t, so according to your rule it is equal to Exp[-0.8316*tau] integrate[f, t] At this point none of your rules apply, so the kernel stops. When you use a instead of f the ordering of the constant and the exponential are reversed, and you get the behaviour that you actually desired. A simple fix is to replace the condition in rule 1 by FreeQ[c,t]&&FreeQ[c,tau] You may however want to think carefully about exactly what you want your function integrate to do. For example, with the rules given, the variable t and the variable tau seem to be playing the same role. Erich > I have defined two functions (Math 4.1) > In[1]:= integrate[c_ y_,t_]:=c*integrate[y,t]/;FreeQ[c,t]; > In[2]:= integrate[Exp[(a_.)*tau], t_]:=(E^(a*t)-1)/a/; > FreeQ[a,t]&&FreeQ[a,tau]; when I applied these functions the solution is different if the coefficient is > the letter d or lower (solution fine) or f or higher (solution wrong) . Here is > an example: Using letter f > In[3]:=integrate[f Exp[-0.8316*tau], t] Out[3]:=integrate[f, t]/E^(0.8316*tau) (*wrong*) Using letter a (the solution is rigth In[4]:=integrate[a Exp[-0.8316*tau], t] Out[4]:=-1.20250*a*(-1 + E^(-0.8316*t)) What it wrong? Guillermo > Sanchez --------------------------------------------- > This message was sent using Endymion MailMan. > > ==== << Graphics`ImplicitPlot` does the job. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de -----UrsprÌ.b9ngliche Nachricht----- Gesendet: Mittwoch, 18. September 2002 08:09 An: mathgroup@smc.vnet.net Betreff: Drawing an ellipse I am new with Mathematica, I have one question, I know that the sollution might be very easy, but I wasn't able to find it by now. I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 Maciej ==== Solve[eqn, var] and InverseFunction are designed to do what you want, in principle. Try Solve[(a*h+b*h^2) == f, h] For your eqn, however, it is impossible to solve for h since h appears as a factor in a sum *and* as an exponent. Try Solve[Exp[-h]*(a*h+b*h^2) == f, h] and study Mathematica's message. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de -----UrsprÌ.b9ngliche Nachricht----- Gesendet: Mittwoch, 18. September 2002 08:10 An: mathgroup@smc.vnet.net Betreff: Invert a function How can I invert a funcion? For example In:=f[h_]:=Exp[-h](a*h+b*h^2); I want to invert it as h as a function of f How can I do that? Please suggest. Raj ==== > Map[(obj = drawMembrane[#]; > drawArea@setMathCommand[obj]; > drawArea@repaintNow[]; > Pause[.0001];) &, t ] This is the exact code you use? Maybe I am missing something here, but you seem to pass only the String obj to the setMathCommand method, not the content of the obj variable; > public class My_DisplayGraphicsViaJava { > public void displayGraphics(String cmds[]) { > for (int i = 0; i < cmds.length-1; i++) > drawArea.setMathCommand(cmds[i]); > drawArea.repaintNow(); > Thread.sleep(200);} } er... this won't work; you are using the drawArea variable, without ever declaring or assigning something to it! pff... hm... you could try this: import com.wolfram.jlink.MathCanvas; public class My_DisplayGraphicsViaJava { public static void displayGraphics(String cmds[], MathCanvas drawArea){ for (int i = 0; i < cmds.length-1; i++){ drawArea.setMathCommand(cmds[i]); drawArea.repaintNow(); Thread.sleep(200); } } } save this to a file called My_DisplayGraphicsViaJava.java and compile it. Put the class file in a directory that is in your CLASSPATH (or look up how the CLASSPATH works in J/Link 2.0 in the J/Link documentation, its properly explained there); If all that has worked, load the class: LoadJavaClass[My_DisplayGraphicsViaJava]; then use the static method displayGraphics, by passing it the String array and the drawArea variablen (which is the MathCanvas object, you have instantiated in your Mathematica Notebook): My_DisplayGraphicsViaJava`displayGraphics[obj, drawArea]; obj being the String array (or string List in M_) that holds your Graphics Expressions (or what you want to show); > But needless to say this dont work....LoadJavaClass responds by saying Class > not Found.....so what should I do to correct this? Also , on the java > routine, was i supposed to add: Extends MathFrame, etc....how will my > java routine know what drawArea.setMathCommand is, etc..... > am I also supposed to compile my java routine? Yes! ... use the Java code I proposed above, that should at least compile properly; Place the compiled class file in a directory on your CLASSPATH (consult J/Link docu if you don't know about CLASSPATH) and then try the Mathematica code again. I hope this was not too confusing; I don't have a working Mathematica here, so I can't verify, if my proposed code would really work; there migth be typos/errors in my code. murphee ==== I am trying to write an animation using JLink.....basically as follows...(using Mathematica 4.1, JLink 2.01 and java 1.4.1)... frm = createWindow[]; (* basically to create a MathFrame and a drawArea = MathCanvas *) Here is my drawing routine.... Map[(obj = drawMembrane[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; Pause[.0001];) &, t ] t = time list ={0,.25,etc}.... and drawMembrane is a function that uses the time value to make a graphics plot......unfortunately, this routine draws the next time plot very slowly, plus I also notice that without the Pause[] statement, Mathematica only draws the graph for the final time value... Following an example in the JLink documentation, I have written the following java routine....which I saved in the same dir as MathFrame, etc.... public class My_DisplayGraphicsViaJava { public void displayGraphics(String cmds[]) { // declare String Array for Graphics Objects for (int i = 0; i < cmds.length-1; i++) drawArea.setMathCommand(cmds[i]); drawArea.repaintNow(); Thread.sleep(200);} } and then in Mathematica I have LoadJavaClass[My_DisplayGraphicsViaJava]; My_DisplayGraphicsViaJava`displayGraphics[obj]; (* where obj is the array of Graphics plots created *) But needless to say this dont work....LoadJavaClass responds by saying Class not Found.....so what should I do to correct this? Also , on the java routine, was i supposed to add: Extends MathFrame, etc....how will my java routine know what drawArea.setMathCommand is, etc.....am I also supposed to compile my java routine? thanks....jerry blimbaum NSWC panama city, fl ==== Dear colleagues, I'm trying to plot the next exponential function Plot[Exp[1/(Abs[x-1]-Abs[x-2])],Range] If the Range is positive there aren«t problems. However if the Range is negative Mathematica plots a strange beast... Have anyone found anything of this sort? I would apreciate to know how to resolve this problem. Juan Egea Garcia Bullas - Murcia - Espa.96a ==== The function you are plotting is constant for negative x. You might want to specify a plotrange, such as PlotRange->{0,2}, or Mathematica may try to zoom in on the line and show you a picture of numerical noise. Erich > Dear colleagues, I'm trying to plot the next exponential function Plot[Exp[1/(Abs[x-1]-Abs[x-2])],Range] If the Range is positive there aren«t problems. However if the Range is > negative Mathematica plots a strange beast... Have anyone found anything of this sort? I would apreciate to know how to > resolve this problem. Juan Egea Garcia > Bullas - Murcia - Espa.96a > ==== I need to solve algebraic-differential-equations (some of index 1, maybe some of higher index as well) from within Mathematica 4.2. Is there an implementation of numerical (like DASSL) or symbolic algorithms capable of doing that around? I know that some numerical software systems which may have DASSL-routines that do what I want. Has anybody suggestions on which of these systems is easy to interface with Mathematica? Is there a C++ library that contains such routines and can be interfaced with Mathematica? Yours, Reinhard Oldenburg ==== > I need to solve algebraic-differential-equations > (some of index 1, maybe some of higher index as well) > from within Mathematica 4.2. > Is there an implementation of numerical (like DASSL) > or symbolic algorithms capable of doing that around? > > I know that some numerical software systems which > may have DASSL-routines that do what > I want. Has anybody suggestions on which of these > systems is easy to interface with Mathematica? > Is there a C++ library that contains such routines and can be > interfaced with Mathematica? Reinhard, have you tried the NDAESolve package that comes with the circuit analysis toolbox Analog Insydes? You can get a free evaluation version of Analog Insydes from www.analog-insydes.de. Eckhard Hennig ==== Dear Colleagues, I intend to make an animation in which ball A rolls down on an inclined plane from the left whilst ball B - starting from the same height - rolls down Cosh[t]'s path from the right. x-axis is time t, y-axis is height h. Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my means. Matthias Bode Sal. Oppenheim jr. & Cie. KGaA Koenigsberger Strasse 29 D-60487 Frankfurt am Main GERMANY Mobile: +49(0)172 6 74 95 77 Internet: http://www.oppenheim.de ==== Matthias, The simplest way to get the equation of motion is to set up the Lagrangian. Let's assume a 1 kg mass. Then the kinetic energy is KE = Simplify[(1/2)*(x'[t]^2 + D[Cosh[x[t]],t]^2)] and the potential energy is PE = 9.8*Cosh[x[t]] The Lagrangian is L = KE - PE and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, > > I intend to make an animation in which > > ball A rolls down on an inclined plane from the left whilst > > ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. > > x-axis is time t, y-axis is height h. > > Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > > > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de > > ==== Having noticed your statement ... BEYOND MY MEANS I thing you aren't yet familiar with Lagrangian formalism. It's quite easy to derive a general equation of motion for a point mass, subjected to gravity and to moving on a curve f = y(x) (i.e. f = Cosh[#]&). 1) I'll leave re-deriving equation to you, here is what I've got (just copy paste it).: !(getEq[ f_] := [IndentingNewLine](x'')[ t] + (x')[t]^2 (2 (f')[x[t]] (f'')[x[t]])/(1 + (f' )[x[t]]^2) + (g (f')[x[t]])/(1 + (f')[x[t]]^2) == 0 /. g -> 1) 2) Next, you integrate it .: getSol[f_, x0_] := Module[{tStop}, NDSolve[{getEq[f], x[0] == x0, x'[0] == 0} , x , {t, 0, 10} , MaxStepSize -> 1/100 , StoppingTest :> If[x0 < 0, x > 0, x < 0] ] // First ] 3) Here follows animation code, specially for linear versus cosh case, apply my initial conditions (below) makeDuo[f_, g_, x0_, fpt_] := Module[{ solf = getSol[f, x0], solg = getSol[g, x0], tf, tg, maxT, minT }, tf = solf[[1, 2, 1, 1, 2]]; tg = solg[[1, 2, 1, 1, 2]]; maxT = Max[{tf, tg}]; minT = Min[{tf, tg}]; Do[ Plot[{f@x, g@x} , {x, 0, x0} , AspectRatio -> Automatic , Frame -> True , Axes -> False , Epilog -> { AbsolutePointSize[10], Hue[0], Point[{x[t], f@x[t]} /. solf], Hue[.6], Point[{x[t], g@x[t]} /. solg] } ] , {t, 0, minT, minT/fpt} ] ] 4) My initial conditions. In my opinion, you weren't true on this. Saying STARTING FROM THE SAME HEIGHT is not enough - you should specify x as well, thus specifing starting POINT and not just height y. makeDuo[(Cosh[1.] - 1) # &, Cosh[#] - 1 &, 1, 23] Feel free to modify the code, it should be easy. bye, Borut | Dear Colleagues, | | I intend to make an animation in which | | ball A rolls down on an inclined plane from the left whilst | | ball B - starting from the same height - rolls down Cosh[t]'s path from the | right. | | x-axis is time t, y-axis is height h. | | Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my | means. | | | Matthias Bode | Sal. Oppenheim jr. & Cie. KGaA | Koenigsberger Strasse 29 | D-60487 Frankfurt am Main | GERMANY | Mobile: +49(0)172 6 74 95 77 | Internet: http://www.oppenheim.de | | ==== As I derived a generalization for a 3D parameterized curve yesterday, I'd noticed a mistake in my equation posted below, a factor '2' in expression involving x'[t]^2, should be '1'. Since this forum is of an alt. type, I've published the whole notebook at http://www2.arnes.si/~gljpoljane22/math/FallingCurve3D.nb Bye, Borut p.s. A 'fill-the-gap' riddle for those interested in physics lore. Richard Feynman once said: Science is like _ _ _, sometimes something useful comes out, but that is not the reason why we are doing it. | ... | 1) I'll leave re-deriving equation to you, here is what I've got (just copy | paste it).: | | !(getEq[ | f_] := [IndentingNewLine](x'')[ | t] + (x')[t]^2 (2 (f')[x[t]] (f'')[x[t]])/(1 + | (f' | )[x[t]]^2) + (g (f')[x[t]])/(1 + (f')[x[t]]^2) == 0 /. g -> | 1) | ... ==== David, There is no command such as RestoreDefaults. But you can do the following: saveGraphics3DOptions = Options[Graphics3D]; SetOptions[Graphics3D, Boxed -> False]; (say) Make your plots. SetOptions[Graphics3D, Sequence @@ saveGraphics3DOptions]; The example in the Help for SetOptions shows a similar example. My own personal preference would be to not change the Graphics3D options, but to add the option change to the plot itself. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== I have the following code and am trying to include a legend. The BarChart appears, but with no legend. I have followed the 'help files', but I think I'm missing something. In my code, SortTime and SessTime are value pairs. Photog is a string array containing labels. /* *Begin code here */ ShowLegend[BarChart[SortTime, SessTime, BarSpacing -> -.3,, BarGroupSpacing -> .5, BarLabels -> Photog, BarStyle -> {RGBColor[1, 0, 0], RGBColor[0.5, 0.5, 1]}, PlotLabel -> Photographer Time , DefaultFont -> {Helvetica, 9}], {{{RGBColor[1, 0, 0], Sort Time }, {RGBColor[0.5, 0.5, 1], Session Time }}, LegendLabel -> Mean Time}] pete ==== How's this: maxima[f_, x_List] := Last@Sort@({f[#], #} & /@ x) maxima[Sin,Range[0,2Pi,0.1]] {0.999574,1.6} That gives you both f[x] and x at the maximum. Bobby Treat -----Original Message----- that largest output. Any ideas? My only idea is this: create a table of pairs {output, input{ and find the element of the table that has the largest first entry. This will give me the input I seek. Is there a slick way of doing this in mathematica? -- Jason Miller, Ph.D. Division of Mathematics and Computer Science Truman State University 100 East Normal St. Kirksville, MO 63501 http://vh216801.truman.edu 660.785.7430 ==== want base 12 numbers, for instance, stored in -- a List of digits? A character string? A list of digits, highest power to lowest, is easy to handle: ClearAll[convertBase] convertBase[(from_Integer)? (#1 > 1 & ), (to_Integer)?(#1 > 1 & ), n:{_Integer..}] /; Max[n] < from := from], to] convertBase[5, 3, {1, 2}] {2, 1} Bobby Treat -----Original Message----- example, ConvertBase[from_, to_, num_] would convert from base to base 9 using the number num as the number to convert (it would best be allowed to let users input in that specific base since they'd be going from base 3 to base 9, for example so maybe num is needed at all). ==== This came up some time ago. Can't remember exactly what my reply was but I discovered later that it is because the number lock is on. Turn it off and the hand will disappear. May even fix the back space trouble. Yas > I don't have any idea about how to solve next problem. Back space key when I am in the front end don't work > correctly. It advances instead of go back and there is > pointer mark of the mouse looks like a hand instead > of an arrow, and this don't work fine too. > Configuration one? How can I solve this? > Note: This problem seems to appear just in my > workspace > i mean this not happen for other users. Cesar. > __________________________________________________ > Do you Yahoo!? > Yahoo! News - Today's headlines > http://news.yahoo.com ==== I believe that's not the adjacency matrix Thomas asked for. It doesn't have zeroes on the diagonal (it isn't square) and it doesn't have ones to indicate that two actors are associated with the same event. Instead, it shows connections between actors and events, which is actually more useful, as I'll demonstrate. (In addition -- though it doesn't really matter -- Jens-Peer switched the 'actors' and 'events' nomenclature within the function.) If you multiply it by its transpose, you get something else that's useful: lst = {{1, A}, {1, B}, {2, B}, {3, C}, {3, D}, {1, D}, {1, C}}; AdjacenceMatrix[lst : {{_, _} ..}] := Module[{actors, events, adj}, {actors, events} = Union /@ Transpose[lst]; adj = Table[0, {Length[actors]}, {Length[events]}]; Scan[(Part[adj, Sequence @@ #] = 1) &, lst /. MapIndexed[Rule[#1, First[#2]] &, events]]; adj] MatrixForm[a = AdjacenceMatrix[lst]] MatrixForm[b = a.Transpose[a]] Matrix 'b' records how many events two actors have in common. On the diagonal, it shows the total number of events each actor is connected to. It's easy to put zeroes on the diagonal: MatrixForm[c = b (1 - IdentityMatrix[Length[b]])] To get the originally intended incidence matrix, this works: d = c /. {_?Positive -> 1} However, I think matrices 'a' and 'b' are actually more useful, and 'a' easily leads to all the others. Bobby -----Original Message----- AdjacenceMatrix[lst : {{_, _} ..}] := Module[ {actors,events adj}, {events, actors} = Union /@ Transpose[lst]; adj = Table[0, {Length[events]}, {Length[actors]}]; Scan[(Part[adj, Sequence @@ #] = 1) &, lst /. MapIndexed[Rule[#1, First[#2]] &, actors]]; adj ] you get In[]:=AdjacenceMatrix[lst] Out[]={{1, 1, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 1}} Jens > > I need to create an adjacency matrix from my data, which is currently in > the form of a .txt file and is basically a two column incidence list. > For example: > > 1 A > 1 B > 2 B > 3 C > . . > . . > . . > m n > > Where 1 to m represent actors and A to n represent events. My goal is to > have an (m x m) matrix where cell i,j equals 1 if two actors are > incident to the same event (in the sample above, 1 and 2 are both > incident to B) and 0 otherwise (w/ zeros on the diagonal). > > I'm new to Mathmatica, and so I'm on the steep part of the learning > curve ... All I've been able to figure out so far is how to get my > incidence list into the program using Import[filename.txt]. But then > what? How do I convert to the adjacency matrix? I've found the > ToAdjacencyMatrix[] command in DiscreteMath`Combinatorica`, but I can't > seem to get it to work ... > > > Tom > > ********************************************** > Thomas P. Moliterno > Graduate School of Management > University of California, Irvine > tmoliter@uci.edu > ********************************************** ==== Maybe this will help. I had to do some guessing, and I fabricated my own R function (r). I never start user-defined symbols with capital letters. ClearAll[r] t = Pi/2.; r = Interpolation[{#, Abs@Cos@#} & /@ Range[0, N@t, Pi/100.]]; y[z_] := NIntegrate[r[x]^4, {x, 0, z}] Timing[yInverse = Interpolation[{y[#], #} & /@ Range[0, N@t, Pi/100.]];] {0.030999999999998806*Second, Null} a = NIntegrate[r[yInverse[z]*Cos[z]], {z, 0, y[t]}]/y[t] 0.9249048118568042 Bobby Treat -----Original Message----- a = (1/y[T])* NIntegrate[R[InvFunction[y[t]]*Cos[y[t]], {y[t], 0, y[T]}] it works with a constant instead of R[t]. Hope you can help, and that the above is understandable. Martin Skogstad ==== << Graphics`ImplicitPlot` eqn = 0.09*x^2 + 0.04*x*y + 0.06*y^2 == 4; maxX = 1.1*Sqrt[4/0.09]; ImplicitPlot[eqn, {x, -maxX, maxX}]; You could also use ParametricPlot: polarEqn = eqn /. {x -> r Sin[t], y -> r Cos[t]} radius[t_] = r /. Last@Solve[polarEqn, r] ParametricPlot[radius[x]{Cos[x], Sin[x]}, {x, 0, 2Pi}, AspectRatio -> 1]; I tried and failed with InequalityGraphics: << Graphics`InequalityGraphics` InequalityPlot[{LessEqual @@ eqn}, {x, -xMax, xMax}, {y, -yMax, yMax}] InequalityPlot::region:The region defined by [LeftSkeleton]1[RightSkeleton] could not be broken down into cylinders. InequalityPlot[ 0.09*x^2 + 0.04*x*y + 0.06*y^2 <= 4, {x, -xMax, xMax}, {y, -yMax, yMax}] Plot can be used very neatly, if you first figure out the true extent of the x-values: positiveX[y_] = x /. Last@Solve[eqn, x] Solve[positiveX'[y] == 0] xMax = First@(positiveX[y] /. %) Plot[Evaluate[y /. Solve[eqn, y]], {x, -xMax, xMax}, AspectRatio -> 1]; Bobby Treat -----Original Message----- ==== That function isn't easily inverted and, in fact, has no inverse unless you limit the range of h. In this plot, for instance, you see that the same f[h] values are taken on for two different values of h: Plot[f@h /. {a -> 3, b -> 0.2}, {h, 0, 10}] The peak of the graph depends on the parameters a and b, so the domain of an inverse (if it exists) also depends on a and b. That's exactly the kind of situation Solve can't handle. For specific a, b and y, FindRoot can find h for you: FindRoot[Evaluate[f[h] == 1 /. {a -> 3, b -> 0.2}], {h, 2}] {h -> 1.799292219454869} FindRoot[Evaluate[f[h] == 1 /. {a -> 3, b -> 0.2}], {h, 0.5}] {h -> 0.5654110956582447} Bobby Treat -----Original Message----- ==== I'd say the applet demonstrates that histograms are useless unless we choose a pretty small bin-width. Choosing a bin-width of significant size that doesn't yield a misleading histogram is an unlikely accident. Bobby -----Original Message----- understood the significance of choosing the bin width......jerry blimbaum -----Original Message----- very nice package that does all of the above and more is mathStatica. See http://www.mathstatica.com for details. Obviously, it is less expensive to write your own functions. Just recently in message Mark Fisher posted code that addresses the empirical CDF. However, in this code you may want to replace 1/n with 1/(n+1) or (j-0.5)/n depending on your application. Note, these will have no significant effect for large data sets. The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. ==== > I'm curious, why the built-in boolean functions And and Or > aren't commutative? The on-line help explains why. (Look up And or Or and then link A.4.2.) You are assured that the argments of And or Or are evaluated left to right, stopping on the first False (for And) or True (for Or). Tom Burton ==== True, but in this case, excitement means being misled far too often. I've never favored histograms much, except when there are lots of bars and little apparent noise. Otherwise, unless you're very lucky, a histogram doesn't even locate the mode well. Bobby Treat -----Original Message----- Bobby -----Original Message----- blimbaum -----Original Message----- very nice package that does all of the above and more is mathStatica. See http://www.mathstatica.com for details. Obviously, it is less expensive to write your own functions. Just recently in message Mark Fisher posted code that addresses the empirical CDF. However, in this code you may want to replace 1/n with 1/(n+1) or (j-0.5)/n depending on your application. Note, these will have no significant effect for large data sets. The key issue with an empirical PDF is deciding the bin width. A simple approach would be to use the functions in Statistics`DataManipulation` and BinListCounts. More sophisticated approaches involve kernel methods. These methods will generate smoother estimates for the PDF. Again, the key is bandwidth. There is no apriori choice for bin width or bandwith. Bad choices will obscure significant features in the data set. ==== Could someone calculate the number Pi to 67,108,864 (2^26) decimal places I made the calculation in another program and would like to verify its ==== > Could someone calculate the number Pi to 67,108,864 (2^26) decimal places > > > I made the calculation in another program and would like to verify its Does it really matter what program is used to verify it? If not, here's the digits (computed with the fastest pi crunching program for a PC): 33863220896223409803 ==== >I am trying to write an animation using JLink.....basically as >follows...(using Mathematica 4.1, JLink 2.01 and java 1.4.1)... > >frm = createWindow[]; (* basically to create a MathFrame and a drawArea >= MathCanvas *) > >Here is my drawing routine.... Map[(obj = drawMembrane[#]; >drawArea@setMathCommand[obj]; > drawArea@repaintNow[]; > Pause[.0001];) &, t ] > >t = time list ={0,.25,etc}.... and drawMembrane is a function that uses the >time value to make a graphics plot......unfortunately, this routine draws >the next time plot very slowly, plus I also notice that without the Pause[] >statement, Mathematica only draws the graph for the final time value... Jerry, You did a nice job with this one-frame-at-a-time plot. (I'm replying here to this message and your previous one where you presented the full code.) The main reason that it is slow drawing the frames is that the Pause[] function only works with integer second intervals. If you say Pause[.0001] it pauses for a whole second, which inserts a 1-second delay between each frame. If I take out the Pause, I get about 5 frames per second on my laptop (for your Sin plot). This still seems slow to me, but it turns out that Java is just slow at taking GIF data and making it into pixels to be displayed. That step consumes virtually all the time for the animation. If you make the image smaller, the animation runs much faster. Try making your window size 400 x 300 instead of 800 x 600. At that size, the animation runs at a good speed on my machine. If you want to insert a delay between frames, you need to use Java instead of calling Pause[]: LoadJavaClass[java.lang.Thread]; Map[(obj = drawMembrane[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; (* Add a 100 ms delay *) Thread`sleep[100];) &, t ] You said that without the Pause[] you only get the last frame drawn, but that shouldn't have any effect. Perhaps you took out the call to repaintNow() along with the Pause? >Following an example in the JLink documentation, I have written the >following java routine....which I saved in the same dir as MathFrame, >etc.... >public class My_DisplayGraphicsViaJava { > public void displayGraphics(String cmds[]) { // declare String Array >for Graphics Objects > for (int i = 0; i < cmds.length-1; i++) > drawArea.setMathCommand(cmds[i]); > drawArea.repaintNow(); > Thread.sleep(200);} } >and then in Mathematica I have LoadJavaClass[My_DisplayGraphicsViaJava]; >My_DisplayGraphicsViaJava`displayGraphics[obj]; (* where obj is the >array of Graphics plots created *) >But needless to say this dont work....LoadJavaClass responds by saying Class >not Found.....so what should I do to correct this? Also , on the java >routine, was i supposed to add: Extends MathFrame, etc....how will my >java routine know what drawArea.setMathCommand is, etc.....am I also >supposed to compile my java routine? You will definitely need to compile any Java classes you write! But writing this in Java won't change anything because the delay is in Java itself, not in J/Link or the MathLink communication. This Java class would need a lot of work before it would compile. You would need to either create drawArea in the Java class rather than in Mathematica code, or pass it as an argument to displayGraphics() (which needs to be static, by the way). Anyway, there is no point in thinking about any of that, since this displayGraphics() method just duplicates functionality that you have already (much more conveniently) scripted in Mathematica code. One final general note for J/Link programmers: It's OK to create Java names with underscores in them, but you have to remember how they are handled in Mathematica. When you refer to a Java name in Mathematica code as a string, you keep the underscore: LoadJavaClass[My_DisplayGraphicsViaJava]; But when a name appears as a symbol in Mathematica, J/Link maps it to a U because _ is not legal in a symbol name: MyUDisplayGraphicsViaJava`displayGraphics[....] It's often easiest to just avoid using _ in the names of Java classes and methods that you write for use with Mathematica. Todd Gayley Wolfram Research ==== >-----Original Message----- >Sent: Wednesday, September 18, 2002 8:09 AM >I am new with Mathematica, I have one question, >I know that the sollution might be very easy, but I wasn't able to >find it by now. >I would like to draw an ellipse, the formula let's say is as follows: 0.09 x^2 +0.04 x y + 0.06 y^2 = 4 >Maciej > Two methods: (1) solve for explit functions y = f[x] and plot those: In[2]:= eqn = 0.09 x^2 + 0.04 x y + 0.06 y^2 == 4 ... just for convenience; In[5]:= sols = Solve[eqn, y] In[6]:= y /. sols ...these are the two functions for y expressed by x. To find the minimum and maximum values for x, we spot the discriminant, and solve for x: In[12]:= {xmin, xmax} = x /. Solve[ Cases[y /. sols[[1]], Sqrt[disc_] :> disc, Infinity] == 0, x] ...now we may use Plot: In[18]:= Plot[Evaluate[y /. sols], {x, xmin, xmax}, AspectRatio -> Automatic] (2) guess approximate values for xmin, xmax and let Mathematica do all that work: In[1]:= << Graphics`ImplicitPlot` ...load the package In[19]:= ImplicitPlot[eqn, {x, -7, 7}] ...done. -- hw ==== b = 2; r = 4; n = 10101111 p = Reverse[Characters[n]] {1, 1, 1, 1, 0, 1, 0, 1} z = Reverse[Partition[p, r]] {{0, 1, 0, 1}, {1, 1, 1, 1}} (* this is okay *) b = 2; r = 3; z = Reverse[Partition[p, r]] {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be {{0,1,0},{1,0,1},{1,1,1}}*) What I want is a function that takes a string as input, parses each character, partitions that to whatever length I want and Prepends zeros to the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). ==== > b = 2; r = 4; > n = 10101111 > p = Reverse[Characters[n]] > {1, 1, 1, 1, 0, 1, 0, 1} > z = Reverse[Partition[p, r]] > {{0, 1, 0, 1}, {1, 1, 1, 1}} (* this is okay *) > b = 2; r = 3; > z = Reverse[Partition[p, r]] > {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be > {{0,1,0},{1,0,1},{1,1,1}}*) > > What I want is a function that takes a string as input, parses each > character, partitions that to whatever length I want and Prepends zeros to > the input as needed to create an appropriate length array. > > What is the correct syntax for Partition (or is there a better way?). z = Reverse[Partition[p, r, r, {1,1}, 0] pads 0 on the right before partitioning. This doesn't completely do what you want because when you reverse, those digits are still on the right in the first element (i.e., they are appended instead of prepended. To have them prepended, just add z[[1]] = RotateRight[z[[1]], r Length[z] - Length[p]]; and z will have what you want. Here is an example with Range (easier to see what is happening) In[1]:= p = Range[8]; b = 2; r = 3; In[2]:= z = Reverse[Partition[p, r, r, {1, 1}, 0]] Out[2]= {{7, 8, 0}, {4, 5, 6}, {1, 2, 3}} In[3]:= z[[1]] = RotateRight[z[[1]], r Length[z] - Length[p]]; In[4]:= z Out[4]= {{0, 7, 8}, {4, 5, 6}, {1, 2, 3}} Rob Knapp > > > > > ==== Has anyone had any luck getting Mathematica 4.2 to work on a Sun running Solaris 6? I get the following error message when starting Mathematica: ./Mathematica ld.so.1: ./Mathematica: fatal: librt.so.1: open failed: No such file or directory Killed But math works. Any thoughts on this would be appreciated - even if it's just Solaris 6 sucks - Reinstall with Solaris 8/9. I'd rather not go to the trouble of reinstalling the box unless absolutely necessary (It is a 270mhz Ultra 5) -- Alex Dawson 08 9380 1587 School of Electrical, Electronic and Computer Engineering Systems Administrator http://www.ee.uwa.edu.au/~alex ==== > > > Has anyone had any luck getting Mathematica 4.2 to work > on a Sun running Solaris 6? > > I get the following error message when starting Mathematica: > > ./Mathematica > ld.so.1: ./Mathematica: fatal: librt.so.1: open failed: No such file or > directory > Killed > > But math works. > > Any thoughts on this would be appreciated - even if it's just > Solaris 6 sucks - Reinstall with Solaris 8/9. I'd rather not go to the > trouble of reinstalling the box unless absolutely necessary (It is a > 270mhz Ultra 5) I'd be tempted to run 'ldd' and see what libraries it needs. On my Solaris 9 box, with Mathematica 4.2 I see: wren /usr/local/stow/Mathematica-4.2/SystemFiles/FrontEnd/Binaries/Solaris % ldd ../Mathematica libXt.so.4 => /usr/lib/libXt.so.4 libXext.so.0 => /usr/lib/libXext.so.0 libXmu.so.4 => /usr/lib/libXmu.so.4 libX11.so.4 => /usr/lib/libX11.so.4 libnsl.so.1 => /usr/lib/libnsl.so.1 libsocket.so.1 => /usr/lib/libsocket.so.1 libc.so.1 => /usr/lib/libc.so.1 libucb.so.1 => /usr/ucblib/libucb.so.1 librt.so.1 => /usr/lib/librt.so.1 libpthread.so.1 => /usr/lib/libpthread.so.1 libSM.so.6 => /usr/lib/libSM.so.6 libICE.so.6 => /usr/lib/libICE.so.6 libm.so.1 => /usr/lib/libm.so.1 libdl.so.1 => /usr/lib/libdl.so.1 libmp.so.2 => /usr/lib/libmp.so.2 libelf.so.1 => /usr/lib/libelf.so.1 libaio.so.1 => /usr/lib/libaio.so.1 libmd5.so.1 => /usr/lib/libmd5.so.1 /usr/platform/SUNW,Ultra-60/lib/libc_psr.so.1 libthread.so.1 => /usr/lib/libthread.so.1 /usr/platform/SUNW,Ultra-60/lib/libmd5_psr.so.1 You should be able to find the libraries it's using, and hopefully it might just be looking in the wrong place, in which case you may be able to create a symbolic link. However, if Solaris 2.6 is not supported (I don't know if it is) it is quite possible it wants a library you don't have, in which case you are stuck unless you re-install a later OS. -- Dr. David Kirkby, Senior Research Fellow, Department of Medical Physics, University College London, 11-20 Capper St, London, WC1E 6JA. Internal telephone: ext 46408 ==== One of these days the company I work for will buy one Mathematica 4.2 versions of the product. window manager. Our Windows systems are running on top of VMWare in Windows XP Professional. In testing using an evaluation version I found that the VMWare/XP version is performing pretty well so that wouldn't be an issue. My main concern (and probably the grounds on which we will base our decision) is the quality of the front-end. The Windows frontend works flawlessly; however, in test-driving earlier versions of Mathematica (3.0 satisfactorily. I didn't spend much time to hunt down the source of the problem, but it is probable that some X key-mapping was wrong making, for example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the Windows frontend. to full satisfaction? I'd be willing to spend a couple of hours to fix some settings, but only if I'm sure it could be done. The bottom line is that I I not if that would mean putting up with a quircky front-end. Sidney Cadot ==== > > > One of these days the company I work for will buy one Mathematica 4.2 > versions of the product. > > window manager. Our Windows systems are running on top of VMWare in Windows > XP Professional. > In testing using an evaluation version I found that the VMWare/XP version is > performing pretty well so that wouldn't be an issue. > > My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. > > to full satisfaction? I'd be willing to spend a couple of hours to fix some > settings, but only if I'm sure it could be done. The bottom line is that I I > not if that would mean putting up with a quircky front-end. For what it is worth, I have no problems with the front end under Solaris - another varient of Unix. -- Dr. David Kirkby PhD, web page: http://www.david-kirkby.co.uk Amateur radio callsign: G8WRB ==== >> >> >> One of these days the company I work for will buy one Mathematica 4.2 >> Windows versions of the product. >> >> window manager. Our Windows systems are running on top of VMWare in >> Windows XP Professional. >> In testing using an evaluation version I found that the VMWare/XP version >> is performing pretty well so that wouldn't be an issue. >> >> My main concern (and probably the grounds on which we will base our >> decision) is the quality of the front-end. The Windows frontend works >> flawlessly; however, in test-driving earlier versions of Mathematica (3.0 >> satisfactorily. I didn't spend much time to hunt down the source of the >> problem, but it is probable that some X key-mapping was wrong making, for >> example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the >> Windows frontend. >> >> working to full satisfaction? I'd be willing to spend a couple of hours >> to fix some settings, but only if I'm sure it could be done. The bottom >> VMWare/Windows, but not if that would mean putting up with a quircky >> front-end. > > For what it is worth, I have no problems with the front end under Solaris > - another varient of Unix. I sincerely wish WRI were more relaxed about allowing people to use the same license on the same hardware, but with a different OS. My understanding is that I would have to buy two licenses if I wanted to switch back and forth That's how open source is paid for. Not everybody has the same amount of spare blood in their veins, or willingness to spill it. For those who release of Mathematica, it would be nice to have a dual boot option. Perhaps it's simply a support issue. It would potentially cause the same customer to require more support if he were switching back and forth between OSs. http://public.globalsymmetry.com/proprietary/com/wri/ch05.html http://66.92.149.152/proprietary/com/wri/ch05.html I still have some tweaks to add to this, such as M-k -> C-k, but it at least demonstrates that (all) things aren't cast in stone. STH ==== Sidney, (or other Unix) for some years so perhaps my experience could help with your decision. Most of the time I run on Windows (2000, not yet XP) because: 1. The Front End is more stable. 2. The Front End is more comfortable in the sense that the keys for deleting, copying, pasting etc. are the ones my fingers expect them to be. 3. Command completion via Ctrl-k, which I use all the time, does not work 4. Generally speaking it takes more mouse clicks and keystrokes to do things I think these are general differences between the user interfaces on these operating systems rather than something specific to the Mathematica implementations. I have tried to overcome them at various time without success. Since I switched from Windows 95 to Windows NT several years ago, 2. I need to have access to certain files created on that system by other people. 3. I want to run long calculations on additional CPUs, leaving my desktop computer free for other things. You can do this between Windows machines kernel via Mathlink. This is very simple and more reliable and robust than Front End and it is easy, say, to transfer input or output betwen systems within a single Front End. I should add that in our lab we can access the the additional convenience of being able to save a notebook from the Windows Front End in the same directory as other files the kernel may be working with. You may not have this option and, of course, you need Mathematica on both systems. These are my personal opinions based on practical experience, I really do not want to enter into any controversy about operating systems. John Jowett One of these days the company I work for will buy one Mathematica 4.2 Windows > versions of the product. window manager. Our Windows systems are running on top of VMWare in Windows > XP Professional. > In testing using an evaluation version I found that the VMWare/XP version is > performing pretty well so that wouldn't be an issue. My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. > working > to full satisfaction? I'd be willing to spend a couple of hours to fix some > settings, but only if I'm sure it could be done. The bottom line is that I I but > not if that would mean putting up with a quircky front-end. > Sidney Cadot > ==== > > One of these days the company I work for will buy one Mathematica 4.2 > Windows versions of the product. The Redmond chaos code is IMHO no system at all (SCNR). I have only one problem with my Mathematica 4.0 for students, which is that the Export function does not work for gif and other graphics formats. I have posted a question about this into this group but nobody has answered, so I guess there is no fix for that, but on the other hand 4.2 is much newer and should work. > My main concern (and probably the grounds on which we will base our > decision) is the quality of the front-end. The Windows frontend works > flawlessly; however, in test-driving earlier versions of Mathematica (3.0 > satisfactorily. I didn't spend much time to hunt down the source of the > problem, but it is probable that some X key-mapping was wrong making, for > example, keyboard shortcuts for 'Copy' and 'Paste' malfunctioning. On the > Windows frontend. I have no problem concerning the frontend. One has only to adjust the font settings (if you need it, I can send you a pdf file explaining how). -- Hendrik van Hees Fakult.8at f.9fr Physik http://theory.gsi.de/~vanhees/ D-33615 Bielefeld ==== > What I want is a function that takes a string as input, parses each > character, partitions that to whatever length I want and Prepends zeros to > the input as needed to create an appropriate length array. > > What is the correct syntax for Partition (or is there a better way?). Although you can't see it in your particular example, I think your two Reverse functions would lead to reversed partitions, so I got rid of them. Then it's a matter of following directions for Partition in Help. The only issue is computing kL. The following way is a bit complicated. Perhaps someone will post a simpler way. n = 10101111; r = 3; p = Characters[n]; kL = r + 1 - Mod[Length[p], r, 1]; kR = r; z = Partition[p, r, r, {kL, kR}, 0] Tom Burton ==== Although And and Or don't have to evaluate all their arguments, I find that this is useless in many situations I run into. For instance, I might have a long list 'boolList' of Boolean expressions and I want to know if ANY of them are False, so I calculate And@@boolList In this situation, ALL the expressions in 'boolList' are calculated, even though the first may be False. Here's an example in which I overcome that: boolList = Hold[Print@#; PrimeQ@#] & /@ Range[3, 1000, 2]; ReleaseHold[And @@ boolList] 3 5 7 9 False Bobby Treat -----Original Message----- argument before any of the others, to avoid unneeded computations of the other arguments. He would put that argument first. If Mathematica turned around and sorted the arguments (which is what happens when a function is orderless), then that argument might end up being evaluated last. If the arguments take a significant amount of time to compute, then sorting first may cause the function to take much longer to evaluate. At any rate, if the above is not a concern for you, you may always change the attributes of And and Or to anything you want. Carl Woll Physics Dept U of Washington ----- Original Message ----- > However, the arithmetical functions are Orderless: Attributes/@{Plus,Times}//ColumnForm {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} > {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} ------------------- > Evgeni Trifonov > Vladivostok, Russia > ==== Maybe this will work for you: groupDigits[n_String, k_Integer] := Partition[ PadLeft[Characters[n], k Ceiling[StringLength[n]/k], 0], k] Bobby Treat -----Original Message----- {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be {{0,1,0},{1,0,1},{1,1,1}}*) What I want is a function that takes a string as input, parses each character, partitions that to whatever length I want and Prepends zeros to the input as needed to create an appropriate length array. What is the correct syntax for Partition (or is there a better way?). ==== After I load a package using < b = 2; r = 4; > n = 10101111 > p = Reverse[Characters[n]] > {1, 1, 1, 1, 0, 1, 0, 1} > z = Reverse[Partition[p, r]] > {{0, 1, 0, 1}, {1, 1, 1, 1}} (* this is okay *) > b = 2; r = 3; > z = Reverse[Partition[p, r]] > {{1, 0, 1}, {1, 1, 1}} (* this is wrong, want output to be > {{0,1,0},{1,0,1},{1,1,1}}*) > > What I want is a function that takes a string as input, parses each > character, partitions that to whatever length I want and Prepends zeros to > the input as needed to create an appropriate length array. > > What is the correct syntax for Partition (or is there a better way?). > > ==== Dear Group, It is a pleasure write to you again. I have three questions to ask. Alexandre Costa Question One: The below code is working fine but I think there are more elegant ways of doing so. Any suggestions are VERY WELCOME. << DiscreteMath`Permutations` individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] CutPosition = 3 ; CutLength = 4 ; CutSequence = Take[Drop[individual1, CutPosition], CutLength] SonOne = individual2; Do[ If[MemberQ[SonOne, CutSequence[[i]]], SonOne = Delete[SonOne, Position[SonOne, CutSequence[[i]]]]], {i, 1, CutLength}]; SonOne SonOne = RotateLeft[SonOne, 1] Do[SonOne = Insert[SonOne, Reverse[CutSequence][[i]], CutPosition + 1], {i, 1, CutLength}] SonOne Question Two: How can I change points properties (such as Size and Color) for the plot below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, {6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] Question Three: Why the Goto statement below is not working? q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] Reply-To: murray@math.umass.edu ==== I presume packagename is a context name, e.g., Graphics`Colors` . Then evaluating the expression Names[packagename*] containing the wildcard symbol * will probably do what you want. It may tell you more than you want to know unless the package was decently written. By decently I mean that names not needing to be known to the outside world have been enclosed within a Private context within the package's context. > After I load a package using > < > Is there a way to figure out what the package exports without editing > the source file? > > > > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 ==== Jose, I generally use the Needs statement to load a package. It avoids double loading and all the error messages that result. Say Needs[Graphics`Graphics`] Then to obtain information on the routines in the package just use... ?Graphics`Graphics`* names in the package. If you click on any of the names you obtain the usage message for the name. (On earlier Mathematica versions you only obtain a list of the names and you have to use ?name to obtain the usage message.) More link. If you click on that it will bring you to the relevant Help page. (Private packages may not have that feature.) David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator Reply-To: ==== Maybe there's a faster way -- I hope so! -- but here's my answer: n = 2^26 Timing[RealDigits[N[Pi - 3, n], 10, 20, 19 - n]] 67108864 {15027.922*Second, {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, 4, 0, 9, 8, 0, 3}, -67108844}} hrMinSec[15027.922] {4*hours, 10*minutes, 27.92200000000048*seconds} Bobby Treat -----Original Message----- ==== Could you tell me the CPU you used and its speed etc...i am curious, other programs out there. > Maybe there's a faster way -- I hope so! -- but here's my answer: > > n = 2^26 > Timing[RealDigits[N[Pi - 3, n], 10, 20, 19 - n]] > > 67108864 > {15027.922*Second, > {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, 4, 0, 9, 8, 0, 3}, > -67108844}} > > hrMinSec[15027.922] > {4*hours, 10*minutes, 27.92200000000048*seconds} > > Bobby Treat > > -----Original Message----- > 4 for me? > > Could someone calculate the number Pi to 67,108,864 (2^26) decimal > places > > > I made the calculation in another program and would like to verify its > > > > > ==== > Could you tell me the CPU you used and its speed etc...i am curious, > other programs out there. I used one processor of a dual 1GH Mac and got the same answer with the following speed: 4.2 for Mac OS X (June 4, 2002) oldmax = $MaxPrecision 6 1. 10 $MaxPrecision = Infinity Infinity With[{n = 2^26}, Timing[ pd = RealDigits[N[Pi, n + 1], 10, 20, 19 - n]; ]] {28794.1 Second, Null} MaxMemoryUsed[] 512055204 pd {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, 4, 0, 9, 8, 0, 3}, -67108844} Tom Burton -- ==== So would it take about the same amont of time for the complete printout of digits? Of course it would take a few additional seconds to format the output... Or does Mathematica take alot less time when it truncates the output? > > > Could you tell me the CPU you used and its speed etc...i am curious, > other programs out there. > > I used one processor of a dual 1GH Mac and got the same answer with the > following speed: > > 4.2 for Mac OS X (June 4, 2002) > oldmax = $MaxPrecision > 6 > 1. 10 > $MaxPrecision = Infinity > Infinity > With[{n = 2^26}, Timing[ > pd = RealDigits[N[Pi, n + 1], 10, 20, > 19 - n]; ]] > {28794.1 Second, Null} > MaxMemoryUsed[] > 512055204 > pd > {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, > > 4, 0, 9, 8, 0, 3}, -67108844} > > Tom Burton ==== Here's an answer to Question 1: individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] cutPosition = 3; cutLength = 4; cutSequence = Take[Drop[individual1, cutPosition], cutLength] sonOne = Complement[individual2, cutSequence] sonOne = RotateLeft[sonOne, 1] sonOne = Join[Take[sonOne, cutLength - 1], cutSequence, Drop[sonOne, cutLength - 1]] Bobby Treat -----Original Message----- << DiscreteMath`Permutations` individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] CutPosition = 3 ; CutLength = 4 ; CutSequence = Take[Drop[individual1, CutPosition], CutLength] SonOne = individual2; Do[ If[MemberQ[SonOne, CutSequence[[i]]], SonOne = Delete[SonOne, Position[SonOne, CutSequence[[i]]]]], {i, 1, CutLength}]; SonOne SonOne = RotateLeft[SonOne, 1] Do[SonOne = Insert[SonOne, Reverse[CutSequence][[i]], CutPosition + 1], {i, 1, CutLength}] SonOne Question Two: How can I change points properties (such as Size and Color) for the plot below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, {6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] Question Three: Why the Goto statement below is not working? q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] ==== I would like to build my Mathematica notebooks in manner which allows me to carry out two overlapping purposes: 1) prototype an algorithm completely within Mathematica, 2) use Mathematica as a partial evaluator to splice derived expressions into a C language version of the algorithm ( with the aid of the Format package from MathSource). The key complication in doing this is that for the Mathematica prototype I want everything to be evaluated, while for splicing I want the results from some of the functions to be retained as data in temporary variables. A first step towards these purposes is simple: write my component functions so they operate on lists (the natural form of the prototype data), then provide lists of arrays for arguments which I would like to supply as data in the resulting C language output forms. An example: -------------------------------------------------- In[1]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[2]:= f[x_,y_] := {y, 1}.t[x] In[3]:= f[{1,2,3,4},2] Out[3]= 3 In[4]:= f[Array[x,4],2] Out[4]= -x[1] + x[2] + 2 (-x[3] + x[4]) In[5]:= CAssign[fcnval, f[Array[x,4],2], AssignToArray->{x}] Out[5]//OutputForm= fcnval=-x[1]+x[2]+2.*(-x[3]+x[4]); -------------------------------------------------- For various reasons, however, I would like certain expressions of my symbolic derivation to be treated as data for the C language version. In the above example, for instance, I would like the array that function t produces to be a data array. The modification of the above example: -------------------------------------------------- In[6]:= tc[x_] := Array[tt,2] In[7]:= fc[x_,y_] := {y, 1}.tc[x] In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, fc[Array[x,4],2], AssignToArray->{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; -------------------------------------------------- But I don't want to carry around two versions of everything, nor do I really want to thread all of the supporting functions through my definitions in order to choose the correct function for the purpose I would rather define the C language alternatives only for functions like t and tc in the example, with f using the appropriate one depending on some evaluation flag that I set at the highest level. For example, it would be nice to be able to sprinkle in the C language alternatives with a construct like In[10]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[11]:= DefineTemporaryForm[t[x_]] := Array[tt,Length[x]/2] then be able to write In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, UseTemporaryForm[f[Array[x,4],2]], AssignToArray- >{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; I would appreciate any pointers on a good, clean and hopefully simple way to do this within Mathematica! Alex ==== I've been using Mathematica 4.1 on Win98 as a word processor for math-related documents, but often people that need to see the documents don't have Mathematica, and for whatever reason on my computer the HTML saves don't work at all. I'd like to export to PDF format. I can export images to PDF format no problem using, for example Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], and I can export cells correctly to GIF, JPEG, and WMF formats (probably more, those are the only ones I tested) using, for example Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy As->Cell Expression)...>> ]] When I change the filename to a .PDF and evaluate the cell, the program displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf ' message as if a file was created, but no file is created anywhere with any name that I could find with Start->Find->[All files and folders created in the previous day]. Is there a limitation to PDF exporting I don't know about? Do I need to upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I need a faster computer? A patch? Something else? ==== I recently communicated with technical support about precisely this issue. Here's their reply: ``PDF and AI export use psrender, which is a MathLink program that interfaces with the kernel. Since the kernel has no knowledge of how cells are formatted, export cannot generate PDF and AI for cells, just Graphics. Note that this is contrary to the documentation, which says: ``All graphics formats in Export can handle any type of 2D or 3D Mathematica graphics. ... They can also handle Notebook and Cell objects. --- Selwyn Hollis > I've been using Mathematica 4.1 on Win98 as a word processor for > math-related documents, but often people that need to see the documents > don't have Mathematica, and for whatever reason on my computer the HTML > saves don't work at all. I'd like to export to PDF format. I can export > images to PDF format no problem using, for example > Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], > and I can export cells correctly to GIF, JPEG, and WMF formats (probably > more, those are the only ones I tested) using, for example > Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy > As->Cell Expression)...>> ]] > When I change the filename to a .PDF and evaluate the cell, the program > displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf > ' message as if a file was created, but no file is created anywhere with any > name that I could find with Start->Find->[All files and folders created in > the previous day]. > Is there a limitation to PDF exporting I don't know about? Do I need to > upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I > need a faster computer? A patch? Something else? > > > ==== Here's a smoother animation, taking into account the period and cutting the step size in half (without using more frames): Do[Show[curve, Graphics[Disk[{ xx[t], Cosh[xx[t]]}, 0.035]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes -> None], {t, 0, 2.3, 0.05}] SelectionMove[EvaluationNotebook[], All, GeneratedCell] FrontEndTokenExecute[OpenCloseGroup] FrontEndTokenExecute[SelectionAnimate] Bobby Treat -----Original Message----- and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, > > I intend to make an animation in which > > ball A rolls down on an inclined plane from the left whilst > > ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. > > x-axis is time t, y-axis is height h. > > Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > > > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de > > ==== I would like to build my Mathematica notebooks in manner which allows me to carry out two overlapping purposes: 1) prototype an algorithm completely within Mathematica, 2) use Mathematica as a partial evaluator to splice derived expressions into a C language version of the algorithm (with the aid of the Format package from MathSource). The key complication in doing this is that for the Mathematica prototype I want everything to be evaluated, while for splicing I want the results from some of the functions to be retained as data in temporary variables. A first step towards these purposes is simple: write my component functions so they operate on lists (the natural form of the prototype data), then provide lists of arrays for arguments which I would like to supply as data in the resulting C language output forms. An example: -------------------------------------------------- In[1]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[2]:= f[x_,y_] := {y, 1}.t[x] In[3]:= f[{1,2,3,4},2] Out[3]= 3 In[4]:= f[Array[x,4],2] Out[4]= -x[1] + x[2] + 2 (-x[3] + x[4]) In[5]:= CAssign[fcnval, f[Array[x,4],2], AssignToArray->{x}] Out[5]//OutputForm= fcnval=-x[1]+x[2]+2.*(-x[3]+x[4]); -------------------------------------------------- For various reasons, however, I would like certain expressions of my symbolic derivation to be treated as data for the C language version. In the above example, for instance, I would like the array that function t produces to be a data array. The modification of the above example: -------------------------------------------------- In[6]:= tc[x_] := Array[tt,2] In[7]:= fc[x_,y_] := {y, 1}.tc[x] In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, fc[Array[x,4],2], AssignToArray->{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; -------------------------------------------------- But I don't want to carry around two versions of everything, nor do I really want to thread all of the supporting functions through my definitions in order to choose the correct function for the purpose I would rather define the C language alternatives only for functions like t and tc in the example, with f using the appropriate one depending on some evaluation flag that I set at the highest level. For example, it would be nice to be able to sprinkle in the C language alternatives with a construct like In[10]:= t[x_] := {x[[4]]-x[[3]], x[[2]]-x[[1]]} In[11]:= DefineTemporaryForm[t[x_]] := Array[tt,Length[x]/2] then be able to write In[8]:= CAssign[tt, t[Array[x,4]], AssignToArray->{x}] Out[8]//OutputForm= tt[0]=-x[3]+x[4]; tt[1]=-x[1]+x[2]; In[9]:= CAssign[fcnval, UseTemporaryForm[f[Array[x,4],2]], AssignToArray->{tt}] Out[9]//OutputForm= fcnval=2.*tt[1]+tt[2]; I would appreciate any pointers on a good, clean and hopefully simple way to do this within Mathematica! Alex ==== To find out what loaded contexts are related to the package, use: Contexts[Integrate`*] {Integrate`,Integrate`Elliptic`} To see the symbols exported by the context, execute: Names[Integrate`*] {(* too many to list here *)} Names[Integrate`*`*] {Integrate`Elliptic`Elliptic} To find out what context a symbol comes from: Context[Integrate] System` Bobby Treat -----Original Message----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator Reply-To: ==== Oops! That should be individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] cutPosition = 3; cutLength = 4; cutSequence = Take[Drop[individual1, cutPosition], cutLength] sonOne = DeleteCases[individual2, _?(MemberQ[cutSequence, #] &)] sonOne = RotateLeft[sonOne, 1] sonOne = Join[Take[ sonOne, cutLength - 1], cutSequence, Drop[sonOne, cutLength - 1]] Complement returns a sorted result, and you didn't want that. Bobby Treat -----Original Message----- sonOne = Join[Take[sonOne, cutLength - 1], cutSequence, Drop[sonOne, cutLength - 1]] Bobby Treat -----Original Message----- << DiscreteMath`Permutations` individual1 = RandomPermutation[12] individual2 = RandomPermutation[12] CutPosition = 3 ; CutLength = 4 ; CutSequence = Take[Drop[individual1, CutPosition], CutLength] SonOne = individual2; Do[ If[MemberQ[SonOne, CutSequence[[i]]], SonOne = Delete[SonOne, Position[SonOne, CutSequence[[i]]]]], {i, 1, CutLength}]; SonOne SonOne = RotateLeft[SonOne, 1] Do[SonOne = Insert[SonOne, Reverse[CutSequence][[i]], CutPosition + 1], {i, 1, CutLength}] SonOne Question Two: How can I change points properties (such as Size and Color) for the plot below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, {6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] Question Three: Why the Goto statement below is not working? q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] ==== I would appreciate help with these problems: 1. I'm plotting several thousand points, which I can do either with something like this (this is a test): w = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; x = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; y = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; z = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; dw = Graphics[{PointSize[0.01], RGBColor[ 1, 0, 0], w}]; dx = Graphics[{PointSize[0.01], RGBColor[.8, .8, .8], x}]; dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; Show[dw, dx, dy, dz, AspectRatio -> Automatic, PlotRange -> {{0, 1}, {0, 1}}, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026], This gives me dots in 4 colors for distinguishing different kinds of points in my real application. This works fine but needs the Point structure. Or, I can do (this is for one kind of point), t = Table[{Random[], Random[]}, {i, 1, 1024}]; ListPlot[t, AspectRatio -> Automatic, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026] ]; which seems simpler and may fit into the rest of the program more easily. 1. How do I get the RGBColor Rule or the equivalent into the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. How do I get ListPlot to put down 4 plots superimposed? Or can't I? 3. In either case, I need to make the whole plot area about twice as big. That is, it now occupies about a 4 square. To see details better in my real plot, and because with 16k points the small plot just looks almost like a solid blur, I want to make it more like 8 square, or as big as will fit the screen (without changing the plot range or anything else). There must be a scale factor somewhere. ==== Steve, You could try something like this: Needs[Graphics`Colors`] Clear[t]; Do[t[i] = Table[{Random[], Random[]}, {i, 1, 1024}], {i, 4}]; Show[Graphics[ {PointSize[0.005], RoyalBlue, Point /@ t[1], OrangeRed, Point /@ t[2], SpringGreen, Point /@ t[3], CadmiumLemon, Point /@ t[4]}], AspectRatio -> Automatic, Frame -> True, PlotRegion -> {{0.02, 0.96}, {0, 1}}, Background -> IvoryBlack, ImageSize -> 700]; The overall size of the plot can be controlled with the ImageSize option. ListPlot is more a hindrance than a help - throw it in the ash can. Just Map Point onto the lists of point coordinates. Give the color before each set of points. I adjusted the PlotRegion to obtain some black margin on all sides of the frame. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; Show[dw, dx, dy, dz, AspectRatio -> Automatic, PlotRange -> {{0, 1}, {0, 1}}, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026], This gives me dots in 4 colors for distinguishing different kinds of points in my real application. This works fine but needs the Point structure. Or, I can do (this is for one kind of point), t = Table[{Random[], Random[]}, {i, 1, 1024}]; ListPlot[t, AspectRatio -> Automatic, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026] ]; which seems simpler and may fit into the rest of the program more easily. 1. How do I get the RGBColor Rule or the equivalent into the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. How do I get ListPlot to put down 4 plots superimposed? Or can't I? 3. In either case, I need to make the whole plot area about twice as big. That is, it now occupies about a 4 square. To see details better in my real plot, and because with 16k points the small plot just looks almost like a solid blur, I want to make it more like 8 square, or as big as will fit the screen (without changing the plot range or anything else). There must be a scale factor somewhere. ==== Bobby, Your ODE is different from both mine and Borut's. You do however get the same as mine with your approach, if you differentiate the total energy rather than the Lagrangian. KE = Simplify[(x'[t]^2 + D[f[x[t]], t]^2)/2]; PE = g*f[x[t]]; totalE = KE + PE; treat = D[totalE, t] == 0 x''[t] - (x''[t] /. First[Solve[treat, x''[t]]]//Apart) == 0 Borut's ODE differs only in his factor of 2 in the first-order term. I suspect that might have been a typo... Borut? By the way, some nice animations of mechanical systems (some based on the same sort of approach) can be seen here: http://www.math.armstrong.edu/faculty/hollis/DEmovies/ --Selwyn > The two of you derived slightly different ODE's. I think Selwyn's is > correct, but I only had one physics course, 30 years ago. Here's a notebook expression showing how Selwyn's approach can be used > to derive the ODE for y[t] = f[x[t]], with arbitrary f. It shows that > solution in a form that is easily compared with Borut's ODE, and then it > shows my own solution (same as Borut's, by a slightly simpler method). Bobby Treat > KE = Simplify[(x'[t]^2 + D[f[x[t]], t]^2)/2]; > PE = g*f[x[t]]; > L = KE - PE; > treat = D[L, t] == 0 > ==== I've modified Selwyn's solution to make it more general. In particular, the height can be specified (up to about 35 meters). The differential equation is solved for t=0 to 5 first. The quarter-period is computed by finding a zero; then the differential equation is solved again for t=0 to the quarter-period, and the solution is extended using reflection and periodicity. This yields a higher-precision solution. Then I graph the solution, with a stepsize equal to period/40, from t=0 to 'period', labeling each frame with the values of t, x[t], and y[t]. Using a step size that divides period/4 guarantees the lowest point is reached ON a frame when appropriate. Here's the solution as a notebook expression: Notebook[{ Cell[CellGroupData[{ Cell[Borut L's solution:, Subsubtitle], Cell[TextData[StyleBox[Having noticed your statement ... BEYOND MY MEANS I thing you aren't yetnfamiliar with Lagrangian formalism. It's quite easy to derive a generalnequation of motion for a point mass, subjected to gravity and to moving on ancurve f = y(x) (i.e. f = Cosh[#]&).nn1) I'll leave re-deriving equation to you, here is what I've got (just copynpaste it).:, FontFamily->Courier New, FontSize->10, CharacterEncoding->WindowsANSI]], Text], Cell[BoxData[ RowBox[{selwyn, =, RowBox[{First, [, RowBox[{ RowBox[{ RowBox[{ RowBox[{x, ''}], [, t, ]}], /., RowBox[{Solve, [, RowBox[{diffeq, ,, RowBox[{ RowBox[{x, ''}], [, t, ]}]}], ]}]}], //, Simplify}], ]}]}]], Input], Cell[BoxData[ RowBox[{borut, =, RowBox[{First, [, RowBox[{ RowBox[{ RowBox[{x, ''}], [, t, ]}], /., RowBox[{Solve, [, RowBox[{ RowBox[{getEq, [, Cosh, ]}], ,, RowBox[{ RowBox[{x, ''}], [, t, ]}]}], ]}]}], ]}]}]], Input], Cell[BoxData[ RowBox[{ RowBox[{getEq, [, f_, ]}], :=, [IndentingNewLine], RowBox[{Simplify, [, RowBox[{ RowBox[{ RowBox[{ RowBox[{x, ''}], [, t, ]}], +, RowBox[{ SuperscriptBox[ RowBox[{ RowBox[{x, '}], [, t, ]}], 2], , FractionBox[ RowBox[{2, , RowBox[{ RowBox[{f, '}], [, RowBox[{x, [, t, ]}], ]}], , RowBox[{ RowBox[{f, ''}], [, RowBox[{x, [, t, ]}], ]}]}], RowBox[{1, +, SuperscriptBox[ RowBox[{ RowBox[{f, '}], [, RowBox[{x, [, t, ]}], ]}], 2]}]]}], +, FractionBox[ RowBox[{g, , RowBox[{ RowBox[{f, '}], [, RowBox[{x, [, t, ]}], ]}]}], RowBox[{1, +, SuperscriptBox[ RowBox[{ RowBox[{f, '}], [, RowBox[{x, [, t, ]}], ]}], 2]}]]}], ==, 0}], ]}]}]], Input], Cell[TextData[{ StyleBox[2) Next, you integrate it .:, FontFamily->Courier New, FontSize->10, CharacterEncoding->WindowsANSI], }], Text], Cell[BoxData[ RowBox[{ RowBox[{getSol, [, RowBox[{f_, ,, RowBox[{h0_, ?, Positive}], ,, RowBox[{x0_, ?, Positive}]}], ]}], :=, RowBox[{Module, [, RowBox[{ RowBox[{{, tStop, }}], ,, [IndentingNewLine], RowBox[{First, @, RowBox[{NDSolve, [, [IndentingNewLine], RowBox[{ RowBox[{{, RowBox[{ RowBox[{getEq, [, f, ]}], ,, RowBox[{ RowBox[{x, [, 0, ]}], [Equal], h0}], ,, RowBox[{ RowBox[{ RowBox[{x, '}], [, 0, ]}], [Equal], 0}]}], }}], ,, [IndentingNewLine], x, ,, [IndentingNewLine], RowBox[{{, RowBox[{t, ,, 0, ,, 10}], }}], ,, [IndentingNewLine], RowBox[{MaxStepSize, [Rule], RowBox[{1, /, 100}]}], ,, RowBox[{StoppingTest, [RuleDelayed], RowBox[{If, [, RowBox[{ RowBox[{h0, <, 0}], ,, RowBox[{x, >, 0}], ,, RowBox[{x, <, 0}]}], ]}]}]}], [IndentingNewLine], ]}]}]}], [IndentingNewLine], ]}]}]], Input], Cell[< 3) Here follows animation code, specially for linear versus cosh case, apply my initial conditions (below) >, Text], Cell[BoxData[ RowBox[{ RowBox[{makeDuo, [, RowBox[{f_, ,, g_, ,, h0_}], ]}], :=, RowBox[{Module, [, RowBox[{ RowBox[{{, RowBox[{ RowBox[{solf, =, RowBox[{getSol, [, RowBox[{f, ,, h0}], ]}]}], ,, RowBox[{solg, =, RowBox[{getSol, [, RowBox[{g, ,, h0}], ]}]}], ,, tf, ,, tg, ,, maxT, ,, minT}], }}], ,, [IndentingNewLine], RowBox[{ RowBox[{tf, =, RowBox[{solf, [, RowBox[{[, RowBox[{ 1, ,, 2, ,, 1, ,, 1, ,, 2}], ]}], ]}]}], ;, [IndentingNewLine], RowBox[{tg, =, RowBox[{solg, [, RowBox[{[, RowBox[{ 1, ,, 2, ,, 1, ,, 1, ,, 2}], ]}], ]}]}], ;, [IndentingNewLine], RowBox[{maxT, =, RowBox[{Max, [, RowBox[{{, RowBox[{tf, ,, tg}], }}], ]}]}], ;, [IndentingNewLine], RowBox[{minT, =, RowBox[{Min, [, RowBox[{{, RowBox[{tf, ,, tg}], }}], ]}]}], ;, [IndentingNewLine], RowBox[{Do, [, RowBox[{ RowBox[{Plot, [, RowBox[{ RowBox[{{, RowBox[{ RowBox[{f, @, x}], ,, RowBox[{g, @, x}]}], }}], ,, RowBox[{{, RowBox[{x, ,, 0, ,, RowBox[{ArcCosh, @, h0}]}], }}], ,, RowBox[{AspectRatio, [Rule], Automatic}], ,, RowBox[{Frame, [Rule], True}], ,, RowBox[{Axes, [Rule], False}], ,, RowBox[{Epilog, [Rule], RowBox[{{, RowBox[{ RowBox[{ AbsolutePointSize, [, 10, ]}], ,, RowBox[{Hue, [, 0, ]}], ,, RowBox[{Point, [, RowBox[{ RowBox[{{, RowBox[{ RowBox[{x, [, t, ]}], ,, RowBox[{f, @, RowBox[{x, [, t, ]}]}]}], }}], /., solf}], ]}], ,, RowBox[{Hue, [, .6, ]}], ,, RowBox[{Point, [, RowBox[{ RowBox[{{, RowBox[{ RowBox[{x, [, t, ]}], ,, RowBox[{g, @, RowBox[{x, [, t, ]}]}]}], }}], /., solg}], ]}]}], }}]}]}], ]}], ,, RowBox[{{, RowBox[{t, ,, 0, ,, minT, ,, minT}], }}]}], ]}]}]}], ]}]}]], Input], Cell[TextData[{ StyleBox[4) My initial conditions. In my opinion, you weren't true on this. Saying nSTARTING FROM THE SAME HEIGHT is not enough - you should specify x asnwell, thus specifing starting POINT and not just height y., FontFamily->Courier New, FontSize->10, CharacterEncoding->WindowsANSI], }], Text], Cell[BoxData[{ RowBox[{makeDuo, [, RowBox[{ RowBox[{ RowBox[{ RowBox[{Cosh, [, 1., ]}], , #}], &}], ,, RowBox[{ RowBox[{Cosh, [, #, ]}], &}], ,, 23}], ]}], [IndentingNewLine], RowBox[{SelectionMove, [, RowBox[{ RowBox[{EvaluationNotebook, [, ]}], ,, All, ,, GeneratedCell}], ]}], n, RowBox[{ FrontEndTokenExecute, [, , ]}], n, RowBox[{ FrontEndTokenExecute, [, , ]}]}], Input] }, Open ]] }, ScreenRectangle->{{0, 1024}, {0, 711}}, WindowSize->{815, 569}, WindowMargins->{{0, Automatic}, {Automatic, -1}}, ShowSelection->True ] Bobby Treat -----Original Message----- and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, > > I intend to make an animation in which > > ball A rolls down on an inclined plane from the left whilst > > ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. > > x-axis is time t, y-axis is height h. > > Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > > > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de > > ==== Try this: << Graphics`Colors` n = 4096; data = {w, x, y, z} = Array[Random[] &, {4, n, 2}]; g@{a_, b_} := ListPlot[a, PlotStyle -> {PointSize[0.005], b}, DisplayFunction -> Identity, Show[g /@ Transpose[{data, {Red, Blue, Yellow, White}}], PlotRange -> {{0, 1}, {0, 1}}, Axes -> Automatic, Frame -> True, DisplayFunction -> $DisplayFunction, Background -> GrayLevel[.026], ImageSize -> 500]; Bobby Treat -----Original Message----- dx = Graphics[{PointSize[0.01], RGBColor[.8, .8, .8], x}]; dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; Show[dw, dx, dy, dz, AspectRatio -> Automatic, PlotRange -> {{0, 1}, {0, 1}}, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026], This gives me dots in 4 colors for distinguishing different kinds of points in my real application. This works fine but needs the Point structure. Or, I can do (this is for one kind of point), t = Table[{Random[], Random[]}, {i, 1, 1024}]; ListPlot[t, AspectRatio -> Automatic, Axes -> Automatic, Frame -> True, Background -> GrayLevel[.026] ]; which seems simpler and may fit into the rest of the program more easily. 1. How do I get the RGBColor Rule or the equivalent into the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. How do I get ListPlot to put down 4 plots superimposed? Or can't I? 3. In either case, I need to make the whole plot area about twice as big. That is, it now occupies about a 4 square. To see details better in my real plot, and because with 16k points the small plot just looks almost like a solid blur, I want to make it more like 8 square, or as big as will fit the screen (without changing the plot range or anything else). There must be a scale factor somewhere. ==== The same command worked for me, insofar as creating the plot is concerned. I did get an error message opening the file, saying that Adobe Acrobat was Unable to find or create the font 'Mathematica1Mono-Bold'. Some characters may not display or print correctly. The plot looks fine, though. Bobby Treat -----Original Message----- Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy As->Cell Expression)...>> ]] When I change the filename to a .PDF and evaluate the cell, the program displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf ' message as if a file was created, but no file is created anywhere with any name that I could find with Start->Find->[All files and folders created in the previous day]. Is there a limitation to PDF exporting I don't know about? Do I need to upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I need a faster computer? A patch? Something else? ==== I'm trying to export a table from Mathematica 4.0 to Notepad, for examples, or something similar, but it's impossible for me! It always exports the cell with all its rubbish, or an image (if I use Word). How can I export just plain _numbers_? Thanx Fip ==== You can use Export[file.dat, expr] where expr is a two-dimensional array. Or for more flexibility study the following. Assuming data has n rows and 2 columns. file = OpenWrite[file.dat]; Map[ ( (* the N may be redundant haven't tested the code w/o it *) str = ToString[PaddedForm[N[#[[1]]],{10,6}]]<> <> ToString[PaddedForm[N[#[[2]]],{10,6}]]; (* make numbers e notation: the *^ notation has given me fits, so I just put this in as a precaution *) str = StringReplace[str, *^ -> e]; WriteString[file, str, n] )&, data]; Close[file] Hope this helps, Lawrence > I'm trying to export a table from Mathematica 4.0 to Notepad, for examples, > or something similar, but it's impossible for me! It always exports the cell > with all its rubbish, or an image (if I use Word). > How can I export just plain _numbers_? > > Thanx > Fip > > -- Lawrence A. Walker Jr. http://www.kingshonor.com ==== > > I'm trying to export a table from Mathematica 4.0 to Notepad, for examples, > or something similar, but it's impossible for me! It always exports the cell > with all its rubbish, or an image (if I use Word). > How can I export just plain _numbers_? Try with this: WriteSimpleTableForm[file_String, data_List, opts___] := Module[{str}, str = OpenWrite[file]; WriteString[str, ToString[TableForm[data, opts]]]; Close[str] ] This is my small solution for this problem. marek ==== I put the following in .../.../KeyEventTranslations.tr: Item[KeyEvent[<,Modifiers->{Control}], FrontEndExecute[{ FrontEnd`NotebookWrite[FrontEnd`SelectedNotebook[], [LeftDoubleBracket][RightDoubleBracket],After]}]], to make it easy to insert the double-brackets. This works fine, but I want the cursor to be placed between the brackets not after them. How can this be done? Gru137 Peter -- =--=--=--=--=--=--=--=--=--=--=--=--=--= http://home.t-online.de/home/phbrf ~ ~ ~ ==== >I've been using Mathematica 4.1 on Win98 as a word processor for >math-related documents, but often people that need to see the documents >don't have Mathematica, and for whatever reason on my computer the HTML >saves don't work at all. I'd like to export to PDF format. I can export >images to PDF format no problem using, for example >Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], >and I can export cells correctly to GIF, JPEG, and WMF formats (probably >more, those are the only ones I tested) using, for example >Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy >As->Cell Expression)...>> ]] >When I change the filename to a .PDF and evaluate the cell, the program >displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf >' message as if a file was created, but no file is created anywhere with any >name that I could find with Start->Find->[All files and folders created in >the previous day]. >Is there a limitation to PDF exporting I don't know about? Do I need to >upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I >need a faster computer? A patch? Something else? This is a limitation of PDF export. The mechanism for exporting GIF, JPEG, and other raster formats is completely different than the system used for PDF export. Because of this PDF export is limited to graphics expressions. Cells and Notebooks cannot be converted via Export. However, there is a way to generate PDFs using the frontend. See http://support.wolfram.com/mathematica/graphics/export/convertpdfghostscript .html http://support.wolfram.com/mathematica/graphics/export/convertpdfdistiller.h tml -Dale ==== Dear Mathematica friends, how can Mathematica 4.1 be used to combine sound and graphics? In particular, I would like to prepare a demo video about differential equations. I can Plot the solution and I can Play the solution. How to combine the 2 results into a single file that can be played back using xine or DivX, like ordinary video can? Best wishes from Prague -- Pavel Pokorny Math Dept, Prague Institute of Chemical Technology http://staffold.vscht.cz/mat/Pavel.Pokorny ==== Hoi, it depends a bit what you want to do. E.g.: If you want to write applications for clients then go with that systems your clients use (probably Windows). If you just use it for yourself, for development: use what you like more. anymore, like there were in 3.0 times. The copy and paste problems are gone if you switch off the KDE Klipper. On the other hand, there are a few OS- (or better Window-manager-specific) 1.: you cannot rotate text (i.e., FrameLabel settings will look weird (vertically arranged horizontal letters), you have to use RotateLabel -> False generally, or play with the Fonts settings such that horizontal tick marks still fit) 2.: If you work with bigger graphics in notebooks I suggest Windows (or MacOS X) since least on my XFree 4.2 installation with a not too modern graphics card). Also I find resizing of larger notebooks somewhat slow. 3.: If you like to work with keyboard shortcuts: Windows is better, clearly. 4.: There are a couple of Font issues which are better on Windows since not all fonts engels, nederlands, duits of spaans) Rolf Mertig Mertig Consulting Berlin ==== I'd like to add a JLink animation of the rolling ball based on Selwyn's solution: UseFrontEndForRendering = False; createWindow[] := Module[{frame}, frame = JavaNew[com.wolfram.jlink.MathFrame, Doppler Animation]; 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[]; frame@setSize[800, 600]; frame@setLocation[200, 200]; JavaShow[frame]]; frame ] drawRoll[t_] := Show[curve, Graphics[{RGBColor[1, 0, 0], Disk[{xx[t], Cosh[xx[t]]}, 0.05]}], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes -> None, DisplayFunction -> Identity]; times = Range[0, 5, .05]; LoadJavaClass[java.lang.Thread]; AnimationPlot[t_List] := JavaBlock[Block[{frm}, frm = createWindow[]; Map[(obj = drawRoll[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; Thread@sleep[5];) &, t ] ]] AnimationPlot[times] jerry blimbaum panama city, fl -----Original Message----- and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, > > I intend to make an animation in which > > ball A rolls down on an inclined plane from the left whilst > > ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. > > x-axis is time t, y-axis is height h. > > Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > > > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de > > ==== I noticed that n Mathematica 3.0 , IntegerDigits function is giving wrong results. This problem is not found in Mathematica 4.1. Whether any body else has also noted any such problem. For example IntegerDigits[10^18+7] will give the digits 0 and 7 , omitting 1. Shyam Sunder Gupta ==== You're right; I wasn't exporting a Cell. I misunderstood his post and successfully executed this: Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]] but that was working for him, already. Sorry for the confusion. Bobby -----Original Message----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== > w = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > x = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > y = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > z = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > 2. In the latter case I also want to plot 4 types of points. > How do I get ListPlot to put down 4 plots superimposed? > Or can't I? You can, but you have to do it via Graphics`MulitpleListPlot`. Load the requisite packages Needs[Graphics`Colors`] Needs[Graphics`MultipleListPlot`] Define cols = {Black, Red, Green, Blue}; pnts = {PlotSymbol[Triangle], PlotSymbol[Box], PlotSymbol[Diamond], PlotSymbol[Star]}; Then grf = MultipleListPlot[w, x, y, z, PlotStyle->cols, SymbolShape->pnts, SymbolsStyle->cols ]; Documentation shows how to incorporate legends and to define other symbols. Dave. ========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au =========================================== ==== >Dear Group, It is a pleasure write to you again. I have three questions to ask. > Alexandre Costa > >Question Two: > >How can I change points properties (such as Size and Color) for the plot >below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` > >listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, >{6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; > >LabeledListPlot[listcities, Axes -> None, Frame -> True, > DisplayFunction -> $DisplayFunction] It's not a built-in feature of LabeledListPlot, so you'll have to do it manually. gr=LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] You can add graphics directives to the points and text with a replacement rule. Show[gr/.x_Point|x_Text->{RGBColor[1,0,0],x}] >Question Three: Why the Goto statement below is not working? > >q = 2; >Label[start]; >q = 3; >Label[begin]; >Print[q]; >q += 1; If[q < 6, Goto[begin], Goto[start]] First, let me say that noone should ever use Goto. You should always use a loop or some other process instead. With that said . . . When you type semicolon separated input into the frontend, each command is treated as a separate input (as if they were in separate input cells). So the Labels and the Gotos are evaluated separately and there's no way to jump from one to the other. Instead, the commands need to be within the same expression. This can be done by wrapping the command in a CompoundExpression ( q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] ) Or some other expression, like a Module. -------------------------------------------------------------- Omega Consulting The final answer to your Mathematica needs Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html ==== >I would appreciate help with these problems: 1. I'm plotting several thousand points, which I can do >either with something like this (this is a test): > >w = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >x = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >y = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >z = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >dw = Graphics[{PointSize[0.01], RGBColor[ 1, 0, 0], w}]; >dx = Graphics[{PointSize[0.01], RGBColor[.8, .8, .8], x}]; >dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; >dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; >Show[dw, dx, dy, dz, AspectRatio -> Automatic, > PlotRange -> {{0, 1}, {0, 1}}, > Axes -> Automatic, > Frame -> True, > Background -> GrayLevel[.026], > >This gives me dots in 4 colors for distinguishing different >kinds of points in my real application. This works fine but >needs the Point structure. Or, I can do (this is for one >kind of point), > >t = Table[{Random[], Random[]}, {i, 1, 1024}]; >ListPlot[t, AspectRatio -> Automatic, > Axes -> Automatic, > Frame -> True, > Background -> GrayLevel[.026] > ]; > >which seems simpler and may fit into the rest of the program >more easily. 1. How do I get the RGBColor Rule or the equivalent into >the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. >How do I get ListPlot to put down 4 plots superimposed? >Or can't I? 3. In either case, I need to make the whole plot area about >twice as big. That is, it now occupies about a 4 square. To >see details better in my real plot, and because with 16k points >the small plot just looks almost like a solid blur, I want to >make it more like 8 square, or as big as will fit the screen >(without changing the plot range or anything else). There >must be a scale factor somewhere. > You can plot more than one list with MultipleListPlot. <Automatic,Axes->Automatic,Frame->True, SymbolShape->{ColorPoint[RGBColor[1,0,0]], ColorPoint[RGBColor[.8, .8, .8]],ColorPoint[RGBColor[ 0, .5, .9]], ColorPoint[RGBColor[.8, .8, 0]]}, SymbolStyle->PointSize[0.01],Background->GrayLevel[.026] ] -------------------------------------------------------------- Omega Consulting The final answer to your Mathematica needs Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html ==== >I have to use a graphics of mathematica with powerpoint for a little >Y-axes and line of function) are bold or more visible: how can I do >that? Use the PlotStyle and AxesStyle options as in Plot[x,{x,0,5},PlotStyle->Thickness[0.015],AxesStyle->Thickness[0.015]] ==== Dear Mathematica friends, how can Mathematica 4.1 be used to combine sound and graphics? In particular, I would like to prepare a demo video about differential equations. I can Plot the solution and I can Play the solution. How to combine the 2 results into a single file that can be played back using xine or DivX, like ordinary video can? Best wishes from Prague -- Pavel Pokorny Math Dept, Prague Institute of Chemical Technology http://staffold.vscht.cz/mat/Pavel.Pokorny ==== I'd like to add a JLink animation of the rolling ball based on Selwyn's solution: UseFrontEndForRendering = False; createWindow[] := Module[{frame}, frame = JavaNew[com.wolfram.jlink.MathFrame, Doppler Animation]; 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[]; frame@setSize[800, 600]; frame@setLocation[200, 200]; JavaShow[frame]]; frame ] drawRoll[t_] := Show[curve, Graphics[{RGBColor[1, 0, 0], Disk[{xx[t], Cosh[xx[t]]}, 0.05]}], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes -> None, DisplayFunction -> Identity]; times = Range[0, 5, .05]; LoadJavaClass[java.lang.Thread]; AnimationPlot[t_List] := JavaBlock[Block[{frm}, frm = createWindow[]; Map[(obj = drawRoll[#]; drawArea@setMathCommand[obj]; drawArea@repaintNow[]; Thread@sleep[5];) &, t ] ]] AnimationPlot[times] jerry blimbaum panama city, fl -----Original Message----- and the equation of motion is diffeq = Simplify[ D[D[L, x'[t]], t] ] == Simplify[ D[L, x[t]] ] Now solve and animate ... xx[t_] = x[t]/. First[ NDSolve[{diffeq, x[0] == -1, x'[0] == 0}, x[t], {t, 0, 5}]] curve = Plot[Cosh[x], {x, -1, 1}] Do[ Show[curve, Graphics[Disk[{xx[t], Cosh[xx[t]]}, 0.025]], PlotRange -> {{-1.2, 1.2}, {0.9, 1.65}}, AspectRatio -> Automatic, Axes->None], {t, 0, 5, 0.1}] ---- Selwyn Hollis > Dear Colleagues, > > I intend to make an animation in which > > ball A rolls down on an inclined plane from the left whilst > > ball B - starting from the same height - rolls down Cosh[t]'s path from the > right. > > x-axis is time t, y-axis is height h. > > Ball A is fine; ball B - which should arrive at h=0 before A - is beyond my > means. > > > Matthias Bode > Sal. Oppenheim jr. & Cie. KGaA > Koenigsberger Strasse 29 > D-60487 Frankfurt am Main > GERMANY > Mobile: +49(0)172 6 74 95 77 > Internet: http://www.oppenheim.de > > ==== >I've been using Mathematica 4.1 on Win98 as a word processor for >math-related documents, but often people that need to see the documents >don't have Mathematica, and for whatever reason on my computer the HTML >saves don't work at all. I'd like to export to PDF format. I can export >images to PDF format no problem using, for example >Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], >and I can export cells correctly to GIF, JPEG, and WMF formats (probably >more, those are the only ones I tested) using, for example >Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy >As->Cell Expression)...>> ]] >When I change the filename to a .PDF and evaluate the cell, the program >displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf >' message as if a file was created, but no file is created anywhere with any >name that I could find with Start->Find->[All files and folders created in >the previous day]. >Is there a limitation to PDF exporting I don't know about? Do I need to >upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I >need a faster computer? A patch? Something else? This is a limitation of PDF export. The mechanism for exporting GIF, JPEG, and other raster formats is completely different than the system used for PDF export. Because of this PDF export is limited to graphics expressions. Cells and Notebooks cannot be converted via Export. However, there is a way to generate PDFs using the frontend. See http://support.wolfram.com/mathematica/graphics/export/convertpdfghostscript .html http://support.wolfram.com/mathematica/graphics/export/convertpdfdistiller.h tml -Dale ==== I noticed that n Mathematica 3.0 , IntegerDigits function is giving wrong results. This problem is not found in Mathematica 4.1. Whether any body else has also noted any such problem. For example IntegerDigits[10^18+7] will give the digits 0 and 7 , omitting 1. Shyam Sunder Gupta ==== You're right; I wasn't exporting a Cell. I misunderstood his post and successfully executed this: Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]] but that was working for him, already. Sorry for the confusion. Bobby -----Original Message----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== > w = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > x = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > y = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > z = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; > 2. In the latter case I also want to plot 4 types of points. > How do I get ListPlot to put down 4 plots superimposed? > Or can't I? You can, but you have to do it via Graphics`MulitpleListPlot`. Load the requisite packages Needs[Graphics`Colors`] Needs[Graphics`MultipleListPlot`] Define cols = {Black, Red, Green, Blue}; pnts = {PlotSymbol[Triangle], PlotSymbol[Box], PlotSymbol[Diamond], PlotSymbol[Star]}; Then grf = MultipleListPlot[w, x, y, z, PlotStyle->cols, SymbolShape->pnts, SymbolsStyle->cols ]; Documentation shows how to incorporate legends and to define other symbols. Dave. ========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au =========================================== ==== >Dear Group, It is a pleasure write to you again. I have three questions to ask. > Alexandre Costa > >Question Two: > >How can I change points properties (such as Size and Color) for the plot >below? The PlotStyle Option does not work for this LabeledListPlot << Graphics`Graphics` > >listcities = {{1, 5}, {4, 6}, {7, 5}, {5, 4}, {9, 4}, {2, 3}, {4, 2}, >{6, 2}, {1, 1}, {5, 1}, {3, 0}, {9, 0}}; > >LabeledListPlot[listcities, Axes -> None, Frame -> True, > DisplayFunction -> $DisplayFunction] It's not a built-in feature of LabeledListPlot, so you'll have to do it manually. gr=LabeledListPlot[listcities, Axes -> None, Frame -> True, DisplayFunction -> $DisplayFunction] You can add graphics directives to the points and text with a replacement rule. Show[gr/.x_Point|x_Text->{RGBColor[1,0,0],x}] >Question Three: Why the Goto statement below is not working? > >q = 2; >Label[start]; >q = 3; >Label[begin]; >Print[q]; >q += 1; If[q < 6, Goto[begin], Goto[start]] First, let me say that noone should ever use Goto. You should always use a loop or some other process instead. With that said . . . When you type semicolon separated input into the frontend, each command is treated as a separate input (as if they were in separate input cells). So the Labels and the Gotos are evaluated separately and there's no way to jump from one to the other. Instead, the commands need to be within the same expression. This can be done by wrapping the command in a CompoundExpression ( q = 2; Label[start]; q = 3; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin], Goto[start]] ) Or some other expression, like a Module. -------------------------------------------------------------- Omega Consulting The final answer to your Mathematica needs Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html ==== Mario: Use, for example, PlotStyle->Thickness[0.01] for plot and AxesStyle->Thickness[0.01]. Other way is using AbsoluteThickness instead of Thickness. See The Mathematica Book: Section 2.9.3. Germ.87n Buitrago A. ----- Original Message ----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== Mario: Use, for example, PlotStyle->Thickness[0.01] for plot and AxesStyle->Thickness[0.01]. Other way is using AbsoluteThickness instead of Thickness. See The Mathematica Book: Section 2.9.3. Germ.87n Buitrago A. ----- Original Message ----- Sender: steve@smc.vnet.net Approved: Steven M. Christensen , Moderator ==== I have to use a graphics of mathematica with powerpoint for a little Y-axes and line of function) are bold or more visible: how can I do that? ==== >I have to use a graphics of mathematica with powerpoint for a little >Y-axes and line of function) are bold or more visible: how can I do >that? Use the PlotStyle and AxesStyle options as in Plot[x,{x,0,5},PlotStyle->Thickness[0.015],AxesStyle->Thickness[0.015]] ==== >I would appreciate help with these problems: 1. I'm plotting several thousand points, which I can do >either with something like this (this is a test): > >w = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >x = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >y = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >z = Table[Point[{Random[], Random[]}], {i, 1, 4096}]; >dw = Graphics[{PointSize[0.01], RGBColor[ 1, 0, 0], w}]; >dx = Graphics[{PointSize[0.01], RGBColor[.8, .8, .8], x}]; >dy = Graphics[{PointSize[0.01], RGBColor[ 0, .5, .9], y}]; >dz = Graphics[{PointSize[0.01], RGBColor[.8, .8, 0], z}]; >Show[dw, dx, dy, dz, AspectRatio -> Automatic, > PlotRange -> {{0, 1}, {0, 1}}, > Axes -> Automatic, > Frame -> True, > Background -> GrayLevel[.026], > >This gives me dots in 4 colors for distinguishing different >kinds of points in my real application. This works fine but >needs the Point structure. Or, I can do (this is for one >kind of point), > >t = Table[{Random[], Random[]}, {i, 1, 1024}]; >ListPlot[t, AspectRatio -> Automatic, > Axes -> Automatic, > Frame -> True, > Background -> GrayLevel[.026] > ]; > >which seems simpler and may fit into the rest of the program >more easily. 1. How do I get the RGBColor Rule or the equivalent into >the latter? The RGBColor[] call is not a rule. 2. In the latter case I also want to plot 4 types of points. >How do I get ListPlot to put down 4 plots superimposed? >Or can't I? 3. In either case, I need to make the whole plot area about >twice as big. That is, it now occupies about a 4 square. To >see details better in my real plot, and because with 16k points >the small plot just looks almost like a solid blur, I want to >make it more like 8 square, or as big as will fit the screen >(without changing the plot range or anything else). There >must be a scale factor somewhere. > You can plot more than one list with MultipleListPlot. <Automatic,Axes->Automatic,Frame->True, SymbolShape->{ColorPoint[RGBColor[1,0,0]], ColorPoint[RGBColor[.8, .8, .8]],ColorPoint[RGBColor[ 0, .5, .9]], ColorPoint[RGBColor[.8, .8, 0]]}, SymbolStyle->PointSize[0.01],Background->GrayLevel[.026] ] -------------------------------------------------------------- Omega Consulting The final answer to your Mathematica needs Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html ==== For the life of me I am not sure why the following is not working in my v. 4.2: ru[a]=a->x; f[x_]:=(a+b) /. ru[a]; Why do I get f[c] = b+x and not f[c] = b+c? What gives? Lawrence -- Lawrence A. Walker Jr. http://www.kingshonor.com Reply-To: kuska@informatik.uni-leipzig.de ==== because te right hand side of SetDelayed[] is not evaluate. Try ru[a] = a -> x; f[x_] := (a + b) /. ru[a]; f1[x_] := Evaluate[(a + b) /. ru[a]]; and f1[] does what you expect In[]:={f[c], f1[c]} Out[]={b + x, b + c} Jens > > > For the life of me I am not sure why the following is not working in my > v. 4.2: > > ru[a]=a->x; > f[x_]:=(a+b) /. ru[a]; > > Why do I get > f[c] = b+x > > and not > f[c] = b+c? > > What gives? > > Lawrence > > -- > Lawrence A. Walker Jr. > http://www.kingshonor.com ==== Sir, we are having FreeBSD Server, In this we connected a heavy duty Dot matrix printer locally. While on taking outputs, username and file name are printing as BANNER TYPE. Instead of this, we would like to take the print out as username and file name should be printed as header through out the file. if u are having any scripts like that please send us Raj Mohan System Administrator Reply-To: jmt@dxdydz.net ==== I would like to add : Some characters, at least with a french keyboard, are not directly available typed through their Mathematica entities : [EHat] , [OHat], etc. While this is not an issue when programming, it can become quite painful when writing documentation. > Hoi, > it depends a bit what you want to do. > E.g.: If you want to write applications for clients then go with that > systems your clients use (probably Windows). > If you just use it for yourself, for development: use what you like more. > anymore, like > there were in 3.0 times. > The copy and paste problems are gone if you switch off the KDE Klipper. > > On the other hand, there are a few OS- (or better Window-manager-specific) > 1.: you cannot rotate text (i.e., FrameLabel settings will look weird > (vertically arranged > horizontal letters), you have to use > RotateLabel -> False generally, or play with the Fonts settings > such that horizontal > tick marks still fit) > > 2.: If you work with bigger graphics in notebooks I suggest Windows (or > MacOS X) since > least on my XFree 4.2 > installation with a not too modern graphics card). > Also I find resizing of larger notebooks somewhat slow. > > 3.: If you like to work with keyboard shortcuts: Windows is better, clearly. > > 4.: There are a couple of Font issues which are better on Windows since > not all fonts > > engels, nederlands, duits of spaans) > > Rolf Mertig > > Mertig Consulting > Berlin > > > ==== Hoi, it depends a bit what you want to do. E.g.: If you want to write applications for clients then go with that systems your clients use (probably Windows). If you just use it for yourself, for development: use what you like more. anymore, like there were in 3.0 times. The copy and paste problems are gone if you switch off the KDE Klipper. On the other hand, there are a few OS- (or better Window-manager-specific) 1.: you cannot rotate text (i.e., FrameLabel settings will look weird (vertically arranged horizontal letters), you have to use RotateLabel -> False generally, or play with the Fonts settings such that horizontal tick marks still fit) 2.: If you work with bigger graphics in notebooks I suggest Windows (or MacOS X) since least on my XFree 4.2 installation with a not too modern graphics card). Also I find resizing of larger notebooks somewhat slow. 3.: If you like to work with keyboard shortcuts: Windows is better, clearly. 4.: There are a couple of Font issues which are better on Windows since not all fonts engels, nederlands, duits of spaans) Rolf Mertig Mertig Consulting Berlin ==== I am considering the following integral W[m_,n_]:=Integrate[BesselJ[m, x]*BesselJ[n, x], {x, 0, Infinity}] where m,n are reals >=0. With Mathematica 4.1 I obtain: If[Re[m+n]>-1, -Cos[(m-n)Pi/2]/(2 Pi)* (2 EulerGamma + Log[4] + PolyGamma[0, 1/2(1 + m - n)] + PolyGamma[0, 1/2(1 - m + n)] + 2PolyGamma[0, 1/2(1 + m + n)]) and so using this answer as a definition I obtain W[0,0]=-(2 EulerGamma + Log[4] + 4 PolyGamma[0, 1/2])/(2 Pi)=0.84564 I suspect that these integrals are divergent (*). So I try the numerical integration: NW[m_,n_]:=NIntegrate[BesselJ[m, x]*BesselJ[n, x], {x, 0, Infinity}] so that NW[0,0]=11.167 Othe couples are W[1,0]=Indeterminate NW[1,0]=0.597973 W[0,1.5]=0.537095 NW[0,1.5]=-5.79306 W[1,1]=0.20902 NW[1,1]=17.5425 W[2,0]=0.427599 NW[2,0]=-6.83464 W[2,1]=Indeterminate NW[2,1]=4.69013 (*) The integral is a particular case of the Weber-Schafheitlin integrals (Abramowitz, 11.4.33). Any explanation about the analytical expression will be gratefully accepteed. Roberto. Roberto Brambilla CESI Via Rubattino 54 20134 Milano tel +39.02.2125.5875 fax +39.02.2125.5492 rlbrambilla@cesi.it ==== WRI Tech Support sent me an answer to the font problem. Copying the Type 1 (not True Type) fonts made the error go away: A workaround for the font-related issue that you encountered, is to place copies of the Mathematica Type 1 fonts from C:Program FilesWolfram ResearchMathematica4.2SystemFilesFontsType1 into C:Program FilesAdobeAcrobat 5.0ResourceFont Sincerely, George Kambouroglou Technical Support Wolfram Research, Inc. support@wolfram.com -----Original Message----- I've been using Mathematica 4.1 on Win98 as a word processor for math-related documents, but often people that need to see the documents don't have Mathematica, and for whatever reason on my computer the HTML saves don't work at all. I'd like to export to PDF format. I can export images to PDF format no problem using, for example Export[c:docsplot3.pdf, Plot[Sin[x],{x,-2Pi,2Pi}]], and I can export cells correctly to GIF, JPEG, and WMF formats (probably more, those are the only ones I tested) using, for example Export[c:docscell4.gif, Cell[ <<...(copied cell data from Edit->Copy As->Cell Expression)...>> ]] When I change the filename to a .PDF and evaluate the cell, the program displays 'Running...' for a second and gives the 'Out[n] = c:docscell4.pdf ' message as if a file was created, but no file is created anywhere with any name that I could find with Start->Find->[All files and folders created in the previous day]. Is there a limitation to PDF exporting I don't know about? Do I need to upgrade to 4.2? Am I doing something wrong with the Export[] command? Do I need a faster computer? A patch? Something else? ==== SSG> I noticed that n Mathematica 3.0 , IntegerDigits function is SSG> giving wrong results. This problem is not found in Mathematica SSG> 4.1. Whether anybody else has also noted any such problem. SSG> For example IntegerDigits[10^18+7] will give the digits 0 SSG> and 7, omitting 1. Having made totally 4,000,000 attemtps, I was not able to reproduce your example. What version of Mathematica do you use? ...................................................... 4.2 for Microsoft Windows (February 28, 2002) 4.1 for Microsoft Windows (November 2, 2000) 4.0 for Microsoft Windows (April 21, 1999) Microsoft Windows 3.0 (April 25, 1997) Windows 387 2.2 (April 9, 1993) IntegerDigits[10^18 + 7] IntegerDigits[10^18 + 7] IntegerDigits[10^18 + 7] IntegerDigits[10^18 + 7] IntegerDigits[10^18 + 7] {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7} {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7} {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7} {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7} {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7} ...................................................... Best wishes, Vladimir Bondarenko Mathematical Director Symbolic Testing Group Web : http://www.CAS-testing.org/ http://maple.bug-list.org/VER2/ (under tuning) http://maple.bug-list.org/VER3/ (under tuning) http://maple.bug-list.org/VER1/ (under tuning) Voice : (380)-652-447325 Mon-Fri 9 a.m.-6 p.m. Mail : 76 Zalesskaya Str, Simferopol, Crimea, Ukraine ==== Just tested it with no errors, version 3.0 John A. Velling -----Original Message----- ==== I would appreciate any info on these issues. 1. I have a symbol slback. I was getting tag times lback protected (or something) errors. (A typically uninformative error message.) I suspected there was a separation between the s and l, and they looked too far apart, but when I spaced past them with the arrow keys, there did not appear to be anything like a space in between. I retyped the symbol and all was ok. This has happened before. What's going on ??? 2. I'm using Raster to plot data points in a 256x256 array. Two problems: First, regardless of the ImageSize setting (I need the display as big as possible), the individual data cells when examined closely at 300% vary in size by almost 2:1. This makes detailed inspection of the data values difficult. Surely there is some setting of something which would make each data cell an exact number of screen pixels? Second, I'm using Show[ Graphics[Raster[ rescol, ColorFunction -> Hue]], AspectRatio -> Automatic, ImageSize -> 700]; but the Hues don't allow enough easily distinguishable shades to visually recognize even 6 data values easily. (I'm slightly colorblind.) It would be nice to have black and white available for two of the data values, but Hue does not allow this. I don't understand what the documentation says about RasterArray. 3. I wanted to get this raster image into a format where I could dissect it with Photoshop or equivalent. After much fooling around, I found that I can export the selection as an html file, read it into Navigator, do File> Edit Page, which brings up Netscape Composer, right click the image which, allows saving it as a GIF, which I can finally work on with a photo editor. Maybe there is an easier way, or maybe this description will help someone with the same need. Reply-To: kuska@informatik.uni-leipzig.de ==== > I would appreciate any info on these issues. > > 1. I have a symbol slback. I was getting > tag times lback protected (or something) errors. > (A typically uninformative error message.) > I suspected there was a separation between the s > and l, and they looked too far apart, but when I > spaced past them with the arrow keys, there did > not appear to be anything like a space in between. > I retyped the symbol and all was ok. This has > happened before. What's going on ??? As long as you don't send us the *exact* input we can't help you. You should also send the mathematica version you are using. But typical this error comes from a equation a*b==c where the user has mixed up Equal[] and Set[] > > 2. I'm using Raster to plot data points > in a 256x256 array. Two problems: First, > regardless of the ImageSize setting (I need the > display as big as possible), the individual data cells > when examined closely at 300% vary in size by > almost 2:1. This makes detailed inspection of the > data values difficult. Surely there is some setting > of something which would make each data cell an > exact number of screen pixels? Second, I'm > using > Show[ Graphics[Raster[ rescol, > ColorFunction -> Hue]], > AspectRatio -> Automatic, > ImageSize -> 700]; > but the Hues don't allow enough easily distinguishable > shades to visually recognize even 6 data values easily. > (I'm slightly colorblind.) The most humans can distinguish 160 gray levels >It would be nice to have black > and white available for two of the data values, but Hue > does not allow this. And something like: mycolor[i_] := Switch[Round[i], 0, RGBColor[0, 0, 0], 1, RGBColor[1, 0, 0], 2, RGBColor[1, 1, 0], 3, RGBColor[0, 1, 0], 4, RGBColor[0, 1, 1], 5, RGBColor[0, 0, 1], _, RGBColor[1, 1, 1]] Show[Graphics[ Raster[Table[Random[Integer, {0, 6}], {16}, {16}], ColorFunction -> mycolor, ColorFunctionScaling -> False]]] does not help ? > I don't understand what the > documentation says about RasterArray. If you can't be more specific *what* you not understand we can not help you. > > 3. I wanted to get this raster image into a format > where I could dissect it with Photoshop or equivalent. And ? waht does Export[] do ? it write the expression in a desired format, TIFF, PNG, PPM are all lossless compressed bitmap formats, that Mathematica can export and that can be imported into PhotoShop > After much fooling around, I found that I can export the > selection as an html file, read it into Navigator, do File> > Edit Page, which brings up Netscape Composer, right > click the image which, allows saving it as a GIF, which > I can finally work on with a photo editor. Maybe > there is an easier way, or maybe this description will > help someone with the same need. May be that thhis description help someone who can't read the fancy documation on Import[] and Export[]. Jens ==== [snip] > 2. I'm using Raster to plot data points > in a 256x256 array. Two problems: First, > regardless of the ImageSize setting (I need the > display as big as possible), the individual data cells > when examined closely at 300% vary in size by > almost 2:1. This makes detailed inspection of the > data values difficult. Surely there is some setting > of something which would make each data cell an > exact number of screen pixels? GRAY: (No answer received.) I can get around this by making the images bigger but this is not a complete solution. > Second, I'm using > Show[ Graphics[Raster[ rescol, > ColorFunction -> Hue]], > AspectRatio -> Automatic, > ImageSize -> 700]; > but the Hues don't allow enough easily distinguishable > shades to visually recognize even 6 data values easily. > (I'm slightly colorblind.) The most humans can distinguish 160 gray levels >It would be nice to have black > and white available for two of the data values, but Hue > does not allow this. And something like: mycolor[i_] := > Switch[Round[i], > 0, RGBColor[0, 0, 0], > 1, RGBColor[1, 0, 0], > 2, RGBColor[1, 1, 0], > 3, RGBColor[0, 1, 0], > 4, RGBColor[0, 1, 1], > 5, RGBColor[0, 0, 1], > _, RGBColor[1, 1, 1]] Show[Graphics[ > Raster[Table[Random[Integer, {0, 6}], {16}, {16}], > ColorFunction -> mycolor, ColorFunctionScaling -> False]]] GRAY: Sounds good. I'll try it. Interesting that the help does not contain this in a form I could easily find. > 3. I wanted to get this raster image into a format > where I could dissect it with Photoshop or equivalent. And ? what does Export[] do ? it write the expression > in a desired format, TIFF, PNG, PPM are all lossless > compressed bitmap formats, that Mathematica can export > and that can be imported into PhotoShop GRAY: I foolishly thought something like Export would be under the File menu. > After much fooling around, I found that I can export the > selection as an html file, read it into Navigator, do File> > Edit Page, which brings up Netscape Composer, right > click the image which, allows saving it as a GIF, which > I can finally work on with a photo editor. Maybe > there is an easier way, or maybe this description will > help someone with the same need. GRAY: I just found that simply Copying the image and Pasting it into Paint Shop Pro (or no doubt lots of other bitmap editors) works. For outputting a Raster noninteractively, there is Export, but I haven't tried it yet. Jens, thank you for your reply. ==== explain to me why I get this behavior and what I can do to fix it. When I run Mathematica in X with the graphical user interface by typing mathematica, I can run the following commands and get the expected output, namely a plot with the plot label in a big font. However, when I run the math command and get the text interface and run the same code I do not get the label in a big font. cc = Plot[Sin[x], {x, 0, Pi}, {PlotLabel -> StyleForm[Label, FontSize -> 60]}] Export[test.eps, cc, eps] I believe that this is due to the different method in which the math and mathematica commands setup fonts. Is there anyway to get the behavior that I want? As a side note when I use the old syntax of cc=Plot[Sin[x],{x,0,Pi},{PlotLabel->FontForm[Label,{Courier,60}]}] I get it to work. However, I would like not to use this syntax as it has several limitations. Any suggestions would be greatly appreciated. ==== I have a dual processor Dell computer...unfortunately, I can only access one of the processors...I purchased Wolfram's parallel processing toolkit which , because of the very poor documentation, never did me any good...i'm told that another option for accessing the dual processors is to write C code etc...I can't C program, so i'm wondering this...duzz anyone have C code, both source and binary, that they could give me for accomplishing this....in addition, i would like to access this C code with JavaNativeCode, etc...can anyone help me with this? thanks... jerry blimbaum NSWC panama city, fl Reply-To: kuska@informatik.uni-leipzig.de ==== you can have a parallel implicit Runge-Kutta method programmed in C *and* with the Parallel Computing Toolkit both on the base of the MathLink protocol. Since I have a SGI I can't help you with the binary for a Dell what ever computer but if you like the source ... You can also have a native MPI source of the code but you will need a running MPI for your computer. Jens > > I have a dual processor Dell computer...unfortunately, I can only access one > of the processors...I purchased Wolfram's parallel processing toolkit which > , because of the very poor documentation, never did me any good...i'm told > that another option for accessing the dual processors is to write C code > etc...I can't C program, so i'm wondering this...duzz anyone have C code, > both source and binary, that they could give me for accomplishing this....in > addition, i would like to access this C code with JavaNativeCode, etc...can > anyone help me with this? thanks... > > jerry blimbaum NSWC panama city, fl ==== I have a set of inequalities that I solve with InequalitySolve. But then it gives a complete set of solutions, but not in the way I would like it to be! :-) For example, the simple following calculation will give: In[1]:= ineq = {y4 >= -1, y5 >= -1, y6 + y4 >= y5 - 1, y5 >= y6, y6 >= -1}; InequalitySolve[ineq,{y4,y6,y5}] Out[1]:= y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 the result is good, but I would like it to be in the simpler but equivalent form y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 How can I tell InequalitySolve to do that? It is simple for this example, but for a large set of simple inequalities InequalitySolve gives lines and lines of results instead of a simple result. Vincent Bouchard ==== f[c] == (c+b)/.ru[c] == (c+b)/.c->x == x+b == b+x Bobby Treat -----Original Message----- f[c] = b+c? What gives? Lawrence -- Lawrence A. Walker Jr. http://www.kingshonor.com ==== Sorry; disregard my earlier answer. ru[c] isn't defined, so that obviously wasn't the correct sequence of events. Here's the right one: f[c] == HoldPattern[(a+b)/.ru[a]]/.x->c == (a+b)/.ru[a] == (a+b)/.a->x == x + b == b + x The substitution of c for x occurs before the rule ru[a] is evaluated, so there's no x in the expression to replace. Instead, there's an 'a' to replace with x. If the other sequence had been correct, you have no rule for evaluating ru[c], so it would have remained just that -- ru[c]. When the kernel tried to apply it as a rule to (a+b), there would have been an error. That didn't happen, so that wasn't the sequence of events. Bobby Treat -----Original Message----- f[c] = b+c? What gives? Lawrence -- Lawrence A. Walker Jr. http://www.kingshonor.com ==== You really should read about the difference between := (SetDelayed) and = (Set). When you enter your definition f[x_]:=(a+b) /. ru[a] the right hand side is not evaluated. So next when you evaluate f[c] you get (a+b)/.ru[a] and only now ru[a] is evaluated, thus giving you (a+b)/.a->x which is b+x There are several ways to get what you want. One is to use = instead of :=, another to force evaluation of the right hand side with f[x_]:=Evaluate[(a+b) /. ru[a]] yet another to insert the actual rule in the definition of f: f[x_]:=(a+b) /. a->x Andrzej Kozlowski Toyama International University JAPAN On Wednesday, September 25, 2002, at 02:50 PM, Lawrence A. Walker Jr. For the life of me I am not sure why the following is not working in my > v. 4.2: ru[a]=a->x; > f[x_]:=(a+b) /. ru[a]; Why do I get > f[c] = b+x and not > f[c] = b+c? What gives? Lawrence -- > Lawrence A. Walker Jr. > http://www.kingshonor.com > ==== Well, I have written the following notebook with Mathematica In[78]:= a=Sqrt[4*Pi/Sqrt[3]] In[79]:= fcom[k_,mu_]:=(( 1+Exp[-I*mu*2*Pi/a]+Exp[-I*mu*4*Pi/a])*(1-Exp[-I*k*(a-mu)])/(I*k)+ Exp[-I*mu*2* Pi/a]*((1-Exp[-I*(k+2*Pi/a)*(a-mu)])/(I*(k+2*Pi/a))+( 1-Exp[-I*(k-2*Pi/a)*(a-mu)])/(I*(k-2*Pi/a)))+ Exp[-I*mu*4* Pi/a]*((1-Exp[-I*(k+4*Pi/a)*(a-mu)])/(I*(k+4*Pi/a))+( 1-Exp[-I*(k+2*Pi/a)*(a-mu)])/(I*(k+2*Pi/a)))+( 1-Exp[-I*(k-2*Pi/a)*(a-mu)])/(I*(k-2*Pi/a))+( 1-Exp[-I*(k-4*Pi/a)*(a-mu)])/(I*(k-4*Pi/a)))/(3*a) In[80]:= f0[k_,mu_]:=((1+Exp[-I*mu*2*Pi/a]+Exp[-I*mu*4*Pi/a])*(a-mu)+ Exp[-I*mu*2* Pi/a]*((1-Exp[-I*2*Pi/a*(a-mu)])/(I*(2*Pi/a))+( 1-Exp[-I*(-2*Pi/a)*(a-mu)])/(I*(-2*Pi/a)))+ Exp[-I*mu*4* Pi/a]*((1-Exp[-I*(4*Pi/a)*(a-mu)])/(I*(4*Pi/a))+( 1-Exp[-I*(2*Pi/a)*(a-mu)])/(I*(2*Pi/a)))+( 1-Exp[-I*(-2*Pi/a)*(a-mu)])/(I*(-2*Pi/a))+( 1-Exp[-I*(-4*Pi/a)*(a-mu)])/(I*(-4*Pi/a)))/(3*a) In[81]:= fp1[k_,mu_]:=(( 1+Exp[-I*mu*2*Pi/a]+Exp[-I*mu*4*Pi/a])*(1-Exp[-I*2*Pi/a*(a-mu)])/( I*2*Pi/a)+ Exp[-I*mu*2*Pi/a]*((1-Exp[-I*(4*Pi/a)*(a-mu)])/(I*(4*Pi/a))+(a-mu))+ Exp[-I*mu*4* Pi/a]*((1-Exp[-I*(6*Pi/a)*(a-mu)])/(I*(6*Pi/a))+( 1-Exp[-I*(4*Pi/a)*(a-mu)])/(I*(4*Pi/a)))+( a-mu)+(1-Exp[-I*(-2*Pi/a)*(a-mu)])/(I*(-2*Pi/a)))/(3*a) In[82]:= fm1[k_,mu_]:=(( 1+Exp[-I*mu*2*Pi/a]+Exp[-I*mu*4*Pi/a])*( 1-Exp[I*2*Pi/a*(a-mu)])/(-I*2*Pi/a)+ Exp[-I*mu*2*Pi/a]*((a-mu)+(1-Exp[-I*(-4*Pi/a)*(a-mu)])/(I*(-4*Pi/a)))+ Exp[-I*mu*4*Pi/a]*((1-Exp[-I*(2*Pi/a)*(a-mu)])/(I*(2*Pi/a))+(a-mu))+( 1-Exp[-I*(-4*Pi/a)*(a-mu)])/(I*(-4*Pi/a))+( 1-Exp[-I*(-6*Pi/a)*(a-mu)])/(I*(-6*Pi/a)))/(3*a) In[83]:= fp2[k_,mu_]:=(( 1+Exp[-I*mu*2*Pi/a]+Exp[-I*mu*4*Pi/a])*(1-Exp[-I*4*Pi/a*(a-mu)])/( I*4*Pi/a)+ Exp[-I*mu*2* Pi/a]*((1-Exp[-I*(6*Pi/a)*(a-mu)])/(I*(6*Pi/a))+(1-Exp[-I*( 2*Pi/a)*(a-mu)])/(I*(2*Pi/a)))+ Exp[-I*mu*4* Pi/a]*((1-Exp[-I*(8*Pi/a)*(a-mu)])/(I*(8*Pi/a))+( 1-Exp[-I*(6*Pi/a)*(a-mu)])/(I*(6*Pi/a)))+( 1-Exp[-I*(2*Pi/a)*(a-mu)])/(I*(2*Pi/a))+(a-mu))/(3*a) In[84]:= fm2[k_,mu_]:=(( 1+Exp[-I*mu*2*Pi/a]+Exp[-I*mu*4*Pi/a])*( 1-Exp[I*4*Pi/a*(a-mu)])/(-I*4*Pi/a)+ Exp[-I*mu*2* Pi/a]*((1-Exp[-I*(-2*Pi/a)*(a-mu)])/(I*(-2*Pi/a))+( 1-Exp[-I*(-6*Pi/a)*(a-mu)])/(I*(-6*Pi/a)))+ Exp[-I*mu*4* Pi/a]*((a-mu)+(1-Exp[-I*(-2*Pi/a)*(a-mu)])/(I*(-2*Pi/a)))+( 1-Exp[-I*(-6*Pi/a)*(a-mu)])/(I*(-6*Pi/a))+( 1-Exp[-I*(-8*Pi/a)*(a-mu)])/(I*(-8*Pi/a)))/(3*a) In[85]:= Lp[0|N[0],mu_]:=f0[0,mu] In[86]:= Lp[2*Pi/a|N[2*Pi/a],mu_]:=fp1[2*Pi/a,mu] In[87]:= Lp[-2*Pi/a|-N[2*Pi/a],mu_]:=fm1[2*Pi/a,mu] In[88]:= Lp[4*Pi/a|N[4*Pi/a],mu_]:=fp2[4*Pi/a,mu] In[89]:= Lp[-4*Pi/a|-N[4*Pi/a],mu_]:=fm2[-4*Pi/a,mu] In[90]:= Lp[k_,mu_]:=fcom[k,mu] In[91]:= Ll[k_,mu_]:=0/;mu>=a In[92]:= Ll[k_,mu_]:=0/;mu<=-a In[93]:= Ll[k_,mu_]:=Lp[k,mu]/;0<=mu
MonteCarlo,MaxPoints->100000000,Compiled->False] but this is not enough to ensure convergence of the integration. Notice that I have inserted some points in the integration path in order to avoid problems with numerical divergences which Mathematica detects in fcom[k,mu] (but these divergences do not really exist, analitically) Does somebody has a smart suggestion to perform this computation? Fabio ==== In a presentation I wish to use Plot to generate a sequence of frames and then animate them. The problem is that the audience sees the animation twice. Once when the frames are being generated and then again after I have closed the group and double clicked on the top graphic. However, the first showing during generation is enough (but uncontrolled). Is it possible to tidy up the generation of the graphic so that it becomes the animation? I have tried the following Do[Plot[Sin[t]*Sin[x], {x, 0, Pi}, PlotRange -> {{0, Pi}, {-1, 1}}, ImageSize -> 400]; SelectionMove[EvaluationNotebook[], All, GeneratedCell]; FrontEndExecute[{FrontEnd`SelectionAnimate[0.1]}]; FrontEndExecute[{FrontEndToken[Clear]}], {t, 0, 15, 0.1}] This works but the cell dividing line flashes on and off spoiling the animation and if there is anything in the cell below this jumps up and down. Is there a proper way of doing this? Hugh Goyder ==== I need to program the following recursion scheme for time series forecasting (The Innovation Algorithm). I will write it in pseudo-Mathematica notation. K is the given m x m autocovariance (numerical) matrix of the process v[0] = K[[1,1]]; H[n,n-k] = (v[k])^(-1) (K[[n+1,k+1]] - Sum[(H[k,k-j] H[n,n-j] v[j]), {j,0,k-}]) for k=0,1,...,n-1 v[n] = K[[n+1,n+1]] -Sum[(H[n,n-j])^2 v[j],{j,0,n-1}] The scheme should be solved in the order v[0], H[1,1], v[1], H[2,2], H[2,1], v[2], H[3,3], H[3,2], H[3,1], ... I have already tried to program it in a straght-forward way, but as have no experience with recursive functions with two variables, it doesn't seem to work properly and is also very slow. Any help would be Robert Reply-To: murray@math.umass.edu ==== I don't understand the problem. Say I enter the 2D form for the reciprocal of the square root of a^2 + b^2, but I enter it in Standard Form (i.e., using the Control key with / to form the fraction, and the Control key with 2 to get the square root symbol). If then I click anywhere within the subexpression inside the square root, then with 2 to three clicks the entire expression under the square root will be highlighted. I can then do a copy-and-paste to put that into any cell, in the usual way -- with keyboard key combinations, right-click context menu, or Mathematica Edit menu. Isn't that GUI enough? Would you REALLY want to be able to DRAG the highlighted expression to a new place? Think of how much of a mess this could cause through inadvertent movement of the mouse after highlighting some subexpression. In fact, I hate Microsoft Word's doing just that! > >>I'm a poor physicist trying to figure out how to sort out the >>physical from the non-physical solutions to a problem. To do >>that, I need to be able to look at an expression and pick out a >>subexpression, the part under the radical. > > > GRAY: > This points up the need, which I've been aware of for years, to be > able to select any part of an expression and drag it to a new line for > further processing. Mathematica and the other CAS I'm familiar with are still > pretty much stuck with a command line interface. They need a true > GUI with extensive interaction. > When I can see on the screen exactly what I want to do, why > should I have to type a bunch of stuff in to access what I want? > Maybe we'll see this in version 5? 6? Never? > > > > > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 ==== > I'm a poor physicist trying to figure out how to sort out the > physical from the non-physical solutions to a problem. To do > that, I need to be able to look at an expression and pick out a > subexpression, the part under the radical. GRAY: This points up the need, which I've been aware of for years, to be able to select any part of an expression and drag it to a new line for further processing. Mathematica and the other CAS I'm familiar with are still pretty much stuck with a command line interface. They need a true GUI with extensive interaction. When I can see on the screen exactly what I want to do, why should I have to type a bunch of stuff in to access what I want? Maybe we'll see this in version 5? 6? Never? Reply-To: murray@math.umass.edu ==== I get the same result in 4.2 (under Windows). Not sure why. But you could try this modification: PlaySeq[L_, dur_] := Do[PlayTone[L[[i]], dur]; Pause[dur], {i, Length[L]}] Then PlaySeq[{224, 256, 384}, 3] seems to work as expected, prolonging the notes before the last one to their full expected duration. > PlayTone[F_, dur_] := Play[Sin[2*Pi*F*t], {t, 0, dur}] > allows me to play a sine wave of frequency F and duration dur > > PlaySeq[L_, dur_] := Do[PlayTone[L[[i]], dur], {i, Length[L]}] > > should allow me to play a sequence of tones > with a given list of frequencies L > and all the same duration dur. > > It does not work at least in 4.1 > > all tones but the last one are much shorter than dur. > > any help? > > > > > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street Amherst, MA 01375 ==== this is almost the solution. but it creates some artificial rests. when the sounds are created, there is some silence between the different notes. when after creation one clicks the play sound icon of the group with all the sounds, these rests disappear. is there a way of Play creating ghte waves, but NOT playing them, and then, doubleclicking the sound icon, hearing the sound without rests immediately? > I get the same result in 4.2 (under Windows). Not sure why. But you > could try this modification: > > PlaySeq[L_, dur_] := Do[PlayTone[L[[i]], dur]; > Pause[dur], {i, Length[L]}] > > Then > > PlaySeq[{224, 256, 384}, 3] > > seems to work as expected, prolonging the notes before the last one to > their full expected duration. > > >>PlayTone[F_, dur_] := Play[Sin[2*Pi*F*t], {t, 0, dur}] >>allows me to play a sine wave of frequency F and duration dur >>PlaySeq[L_, dur_] := Do[PlayTone[L[[i]], dur], {i, Length[L]}] >>should allow me to play a sequence of tones >>with a given list of frequencies L >>and all the same duration dur. >>It does not work at least in 4.1 >>all tones but the last one are much shorter than dur. >>any help? > > -- -- Erich Neuwirth, Computer Supported Didactics Working Group Visit our SunSITE at http://sunsite.univie.ac.at ==== PlayTone[F_, dur_] := Play[Sin[2*Pi*F*t], {t, 0, dur}] allows me to play a sine wave of frequency F and duration dur PlaySeq[L_, dur_] := Do[PlayTone[L[[i]], dur], {i, Length[L]}] should allow me to play a sequence of tones with a given list of frequencies L and all the same duration dur. It does not work at least in 4.1 all tones but the last one are much shorter than dur. any help? -- -- Erich Neuwirth, Computer Supported Didactics Working Group Visit our SunSITE at http://sunsite.univie.ac.at ==== using Set (=) instead of SetDelayed (:=) in f[x_]:=(a+b) /. ru[a]; will give you what you desire. Matthias Bode. -----UrsprÌ.b9ngliche Nachricht----- Gesendet: Mittwoch, 25. September 2002 07:51 An: mathgroup@smc.vnet.net Betreff: Strange ReplaceAll behavior For the life of me I am not sure why the following is not working in my v. 4.2: ru[a]=a->x; f[x_]:=(a+b) /. ru[a]; Why do I get f[c] = b+x and not f[c] = b+c? What gives? Lawrence -- Lawrence A. Walker Jr. http://www.kingshonor.com ==== If you want to do it with the mouse, it's not that difficult. I click within the part I want and double-click until the part is selected. (Each double-click expands the selection by one level of nesting.) Then push Ctrl-C, click where you want to put the result, and push Ctrl-V. Does that help any? Bobby -----Original Message----- able to select any part of an expression and drag it to a new line for further processing. Mathematica and the other CAS I'm familiar with are still pretty much stuck with a command line interface. They need a true GUI with extensive interaction. When I can see on the screen exactly what I want to do, why should I have to type a bunch of stuff in to access what I want? Maybe we'll see this in version 5? 6? Never? ==== I met a critical problem for running Mathematica 4.1 on MacOS X 10.2. (OSX native version) I hope such a problem is suitable to be posted to this ML. What happens is the following. When Mathematica 4.1 installed in HDD is started, a window quickly appears saying that A serious error has occured while Mathematica was starting up. Mathematica will probably not function properly until this problem is resolved. ... The Mathematica fonts are not properly installed in your system. Without these fonts, typeset mathematical expressions cannot be displayed properly. This message is correct. If I chose Continue Anyway, mathematical expressins are totally broken. What is strange is that when I start Mathematica 4.1 by double clicking Mathematica in CDROM, it works without any problem. Further more, Once Mathematica 4.1 is correctly started in this way, I can restart Mathematica directly from double clicking Mathematica in HDD, which is the installed one. Once CDROM is ejected, the error appears again. It is clearly font related problem but I do not know how to solve. If someone know how to manage, please let me know. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- I met a critical problem for running Mathematica 4.1 on MacOS X 10.2. (OSX native version) I hope such a problem is suitable to be posted to this ML. What happens is the following. When Mathematica 4.1installed in HDD is started, a window quickly appears saying that A serious error has occured while Mathematica was starting up. Mathematica will probably not function properly until this problem is resolved. ... The Mathematica fonts are not properly installed in your system. Without these fonts, typeset mathematical expressions cannot be displayed properly. This message is correct. If I chose Continue Anyway, mathematical expressins are totally broken. What is strange is that when I start Mathematica 4.1 by double clicking Mathematica in CDROM, it works without any problem. Further more, Once Mathematica 4.1 is correctly started in this way, I can restart Mathematica directly from double clicking Mathematica in HDD, which is the installed one. Once CDROM is ejected, the error appears again. It is clearly font related problem but I do not know how to solve. If someone know how to manage, please let me know. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Apple-Mail-2-977368608-- ==== Toshinao, Try reinstalling Mathematica from the CD. --- Selwyn Hollis > > I met a critical problem for running Mathematica 4.1 on MacOS X 10.2. > (OSX native version) I hope such a problem is suitable to be posted to > this ML. > > What happens is the following. When Mathematica 4.1 installed in HDD > is started, a window quickly appears saying that > > A serious error has occured while Mathematica was starting up. > Mathematica will probably not function properly until this problem is > resolved. > ... > The Mathematica fonts are not properly installed in your system. > Without these fonts, typeset mathematical expressions cannot be > displayed properly. > > This message is correct. If I chose Continue Anyway, mathematical > expressins are totally broken. > > What is strange is that when I start Mathematica 4.1 by double clicking > Mathematica in CDROM, it works without any problem. Further more, > Once Mathematica 4.1 is correctly started in this way, I can restart > Mathematica > directly from double clicking Mathematica in HDD, which is the > installed one. > Once CDROM is ejected, the error appears again. > > It is clearly font related problem but I do not know how to solve. If > someone > know how to manage, please let me know. > > -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- > > > > > I met a critical problem for running Mathematica 4.1 on MacOS X 10.2. > > (OSX native version) I hope such a problem is suitable to be posted to > > this ML. > > > What happens is the following. When Mathematica 4.1installed in HDD > > is started, a window quickly appears saying that > > > A serious error has occured while Mathematica was starting up. > > Mathematica will probably not function properly until this problem is > > resolved. > > ... > > The Mathematica fonts are not properly installed in your system. > > Without these fonts, typeset mathematical expressions cannot be > > displayed properly. > > > This message is correct. If I chose Continue Anyway, mathematical > > expressins are totally broken. > > > What is strange is that when I start Mathematica 4.1 by double clicking > > Mathematica in CDROM, it works without any problem. Further more, > > Once Mathematica 4.1 is correctly started in this way, I can restart > Mathematica > > directly from double clicking Mathematica in HDD, which is the > installed one. > > Once CDROM is ejected, the error appears again. > > > It is clearly font related problem but I do not know how to solve. If > someone > > know how to manage, please let me know. > > > -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- > > --Apple-Mail-2-977368608-- > ==== The reason why InequalitySolve returns it's answer in what sometimes turns out to be unnecessarily complicated form is that the underlying algorithm, Cylindrical Agebraic Decomposition (CAD) returns its answers in this form. Unfortunately it seems to me unlikely that a simplification of the kind you need can be can be accomplished in any general way. To see why observe the following. First of all: In[1]:= FullSimplify[x > 0 || x == 0] Out[1]= x >= 0 This is fine. However: In[2]:= FullSimplify[x > 0 && x < 2 || x == 0 && x < 2] Out[2]= x == 0 || 0 < x < 2 Of course what you would like is simply 0 <= x < 2. One reason why you can't get it is that while Mathematica can perform a LogicalExpand, as in: In[3]:= LogicalExpand[(x > 0 || x == 0) && x < 2] Out[3]= x == 0 && x < 2 || x > 0 && x < 2 There i no LogicalFactor or anything similar that would reverse what LogicalExpand does. if there was then you could perform the sort of simplifications you need for: In[4]:= FullSimplify[(x > 0 || x == 0) && x < 2] Out[4]= 0 <= x < 2 However, it does not seem to me very likely that such logical factoring can be performed by a general enough algorithm (though I am no expert in this field). In any case, certainly Mathematica can't do this. I also noticed that Mathematica seems unable to show that the answer it returns to your problem is actually equivalent to your simpler one. In fact this looks like a possible bug in Mathematica. Let's first try the function ImpliesQ from the Experimental context: << Experimental` Now Mathematica correctly gives: In[6]:= ImpliesQ[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[6]= True However: In[7]:= ImpliesQ[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[7]= False That simply means that ImpliesQ cannot show the implication, not that it does not hold. ImpliesQ relies on CAD, as does FullSimplify. Switching to FullSimplify we see that: In[8]:= FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[8]= True while In[9]:= FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[9]= y4 >= -1 && y6 <= y5 <= 1 + y4 + y6 On the other hand, taking just the individual summands of Or as hypotheses; In[10]:= FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[10]= True In[11]:= FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 == -1 && y6 >= -1 && y5 == y6 ] Out[11]= True In fact FullSimplify is unable to use Or in assumptions, which can be demonstrated on an abstract example: In[12]:= FullSimplify[C,(A||B)&&(C)] Out[12]= True In[13]:= FullSimplify[C,LogicalExpand[(A||B)&&(C)]] Out[13]= C This could be fixed by modifying FullSimplify: In[14]:= Unprotect[FullSimplify]; In[14]:= FullSimplify[expr_,Or[x_,y__]]:=Or[FullSimplify[expr,x],FullSimplify[exp r,y]]; In[15]:= Protect[FullSimplify]; Now at least we get as before: In[16]:= FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[16]= True but also: In[17]:= FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[17]= True This seems to me a possible worthwhile improvement in FullSimplify, though of course not really helpful for your problem. Andrzej Kozlowski Toyama International University JAPAN > I have a set of inequalities that I solve with InequalitySolve. But > then > it gives a complete set of solutions, but not in the way I would like > it > to be! :-) For example, the simple following calculation will give: In[1]:= ineq = {y4 >= -1, y5 >= -1, y6 + y4 >= y5 - 1, y5 >= y6, y6 >= > -1}; > InequalitySolve[ineq,{y4,y6,y5}] Out[1]:= y4 == -1 && y6 >= -1 && y5 == y6 || > y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 the result is good, but I would like it to be in the simpler but > equivalent form y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 How can I tell InequalitySolve to do that? It is simple for this > example, > but for a large set of simple inequalities InequalitySolve gives lines > and > lines of results instead of a simple result. > Vincent Bouchard ==== I have been trying to integrate the following : Integrate[Cosh[2 Abs[x-y]] 2 y, {y,0,1/2}, Assumptions->{Im[x]==0,x>0}] However, Mathematica chokes and simply returns the integral as it is. However, if I split up the integral into two portions, it quickly gives me an answer for the parts. Is there something implicit that I am missing in the Assumptions ? MS. -- 12:02am up 5:06, 1 user, load average: 0.54, 0.22, 0.08 ==== The modification to FullSimplify that I sent earlier works correctly only for assumptions of the form Or[a,b] (and even then not is not always what one would like). For what it's worth here is a better (but slow) version: In[1]:= Unprotect[FullSimplify]; In[2]:= FullSimplify[expr_, x_ || y__] := FullSimplify[ FullSimplify[expr, x] || FullSimplify[expr, Or[y]]]; In[3]:= Protect[FullSimplify]; For example: In[4]:= FullSimplify[Sqrt[(x - 1)^2] + Sqrt[(x - 2)^2] + Sqrt[(x - 3)^2], x > 1 || x > 2 || x > 3] Out[4]= -1 + x + Abs[-3 + x] + Abs[-2 + x] || -3 + 2*x + Abs[-3 + x] || 3*(-2 + x) Andrzej Kozlowski Toyama International University JAPAN > The reason why InequalitySolve returns it's answer in what sometimes > turns out to be unnecessarily complicated form is that the underlying > algorithm, Cylindrical Agebraic Decomposition (CAD) returns its > answers in this form. Unfortunately it seems to me unlikely that a > simplification of the kind you need can be can be accomplished in any > general way. To see why observe the following. First of all: In[1]:= > FullSimplify[x > 0 || x == 0] Out[1]= > x >= 0 This is fine. However: In[2]:= > FullSimplify[x > 0 && x < 2 || x == 0 && x < 2] Out[2]= > x == 0 || 0 < x < 2 Of course what you would like is simply 0 <= x < 2. One reason why you > can't get it is that while Mathematica can perform a LogicalExpand, > as in: > In[3]:= > LogicalExpand[(x > 0 || x == 0) && x < 2] Out[3]= > x == 0 && x < 2 || x > 0 && x < 2 There i no LogicalFactor or anything similar that would reverse what > LogicalExpand does. if there was then you could perform the sort of > simplifications you need for: In[4]:= > FullSimplify[(x > 0 || x == 0) && x < 2] Out[4]= > 0 <= x < 2 However, it does not seem to me very likely that such logical > factoring can be performed by a general enough algorithm (though I am > no expert in this field). In any case, certainly Mathematica can't do > this. I also noticed that Mathematica seems unable to show that the answer > it returns to your problem is actually equivalent to your simpler one. > In fact this looks like a possible bug in Mathematica. Let's first try > the function ImpliesQ from the Experimental context: << Experimental` Now Mathematica correctly gives: In[6]:= > ImpliesQ[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, > y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 > <= 1 + y4 + y6] Out[6]= > True However: In[7]:= > ImpliesQ[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && > y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + > y4 + y6] Out[7]= > False That simply means that ImpliesQ cannot show the implication, not that > it does not hold. ImpliesQ relies on CAD, as does FullSimplify. > Switching to FullSimplify we see that: In[8]:= > FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && > y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + > y4 + y6] Out[8]= > True while In[9]:= > FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, > y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 > <= 1 + y4 + y6] Out[9]= > y4 >= -1 && y6 <= y5 <= 1 + y4 + y6 On the other hand, taking just the individual summands of Or as > hypotheses; > In[10]:= > FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, > y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[10]= > True In[11]:= > FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, > y4 == -1 && y6 >= -1 && y5 == y6 ] Out[11]= > True In fact FullSimplify is unable to use Or in assumptions, which can be > demonstrated on an abstract example: > In[12]:= > FullSimplify[C,(A||B)&&(C)] Out[12]= > True In[13]:= > FullSimplify[C,LogicalExpand[(A||B)&&(C)]] Out[13]= > C This could be fixed by modifying FullSimplify: In[14]:= > Unprotect[FullSimplify]; In[14]:= > FullSimplify[expr_,Or[x_,y__]]:=Or[FullSimplify[expr,x],FullSimplify[ex > pr,y]]; In[15]:= > Protect[FullSimplify]; Now at least we get as before: In[16]:= > FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && > y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + > y4 + y6] Out[16]= > True but also: In[17]:= > FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, > y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 > <= 1 + y4 + y6] Out[17]= > True This seems to me a possible worthwhile improvement in FullSimplify, > though of course not really helpful for your problem. > Andrzej Kozlowski > Toyama International University > JAPAN > I have a set of inequalities that I solve with InequalitySolve. But >> then >> it gives a complete set of solutions, but not in the way I would like >> it >> to be! :-) For example, the simple following calculation will give: >> In[1]:= ineq = {y4 >= -1, y5 >= -1, y6 + y4 >= y5 - 1, y5 >= y6, y6 >>= -1}; >> InequalitySolve[ineq,{y4,y6,y5}] >> Out[1]:= y4 == -1 && y6 >= -1 && y5 == y6 || >> y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 >> the result is good, but I would like it to be in the simpler but >> equivalent form >> y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 >> How can I tell InequalitySolve to do that? It is simple for this >> example, >> but for a large set of simple inequalities InequalitySolve gives >> lines and >> lines of results instead of a simple result. >> Vincent Bouchard ==== >-----Original Message----- >Sent: Wednesday, September 25, 2002 7:51 AM > >For the life of me I am not sure why the following is not >working in my >v. 4.2: > >ru[a]=a->x; >f[x_]:=(a+b) /. ru[a]; > >Why do I get >f[c] = b+x > >and not >f[c] = b+c? > >What gives? > >Lawrence -- >Lawrence A. Walker Jr. >http://www.kingshonor.com > Lawrence, in your definition of f, x doesn't show up explicitely. So, in the evaluation sequence, when the definition for f[c] is applied, no x appears at rhs i.e. (a + b) /. ru[a] and such c cannot be inserted. The result is the same as directly executing In[11]:= (a + b) /. ru[a] Out[11]= b + x If you don't like this, you have to make explicit the Value of ru[a] in the definiton of f. One way to do so is to use Set instead of SetDelayed: In[9]:= f[x_] = (a + b) /. ru[a] Out[9]= b + x In[10]:= f[c] Out[10]= b + c The drawback of this that not only the value of ru[a] is inserted but also the whole expression including ReplaceAll is evaluated. If this is not wanted, you have to insert the value of ru[a] into the unevaluated rhs at the definition. The general means for this are function application, With or Replace: In[7]:= (g[x_] := (a + b) /. #) &[ru[a]] In[8]:= g[c] Out[8]= b + c In[16]:= Clear[g] In[20]:= Unevaluated[g[x_] := (a + b) /. rule] /. rule -> ru[a] In[21]:= g[c] Out[21]= b + c Here we have to prevent evaluation of the defintion before our rule is inserted, this is achieved by Unevaluated. With is a bit more complicated, since the scoping rules for SetDelayed would not allow the substition of an expression at rhs containing a pattern variable (the pattern variable is renamed in this case). A simple answer to this is to also substitute the argument variable (the pattern): In[31]:= Clear[g] In[32]:= With[{rule = ru[a], arg = x_}, g[arg] := (a + b) /. rule] In[33]:= g[c] Out[33]= b + c -- Hartmut Wolf ==== Hartmut, I add an explicit illustration to your ingenious solution using With. Hartmut's solution: Clear[g]; ru[a] = a -> x; With[{rule = ru[a], arg = x_}, g[arg] := a + b /. rule]; g[ c] b + c Why is arg = x_ needed? Without it we get Clear[g]; With[{rule=ru[a]}, g[x_]:=a+b/.rule]; g [c] b+x The reason for this shows in ?g Global`g g[x$_] := a + b /. a -> x The x in x_ has been changed to x$ and there is no x$ on the right side. This is a general feature of scoping. Taking it further we get Clear[g]; With[{rule=ru[a]},g[x_]:=a+x/.rule]; g [c] c+x ?g Global`g g[x$_] := a + x$ /. a -> x -- Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay@haystack.demon.co.uk Voice: +44 (0)116 271 4198 -----Original Message----- > >Sent: Wednesday, September 25, 2002 7:51 AM >For the life of me I am not sure why the following is not > >working in my > >v. 4.2: >ru[a]=a->x; > >f[x_]:=(a+b) /. ru[a]; >Why do I get > >f[c] = b+x >and not > >f[c] = b+c? >What gives? >Lawrence -- > >Lawrence A. Walker Jr. > >http://www.kingshonor.com > Lawrence, in your definition of f, x doesn't show up explicitely. So, in the > evaluation sequence, when the definition for f[c] is applied, no x appears > at rhs i.e. > (a + b) /. ru[a] and such c cannot be inserted. The result is the same as > directly executing In[11]:= (a + b) /. ru[a] > Out[11]= b + x If you don't like this, you have to make explicit the Value of ru[a] in the > definiton of f. One way to do so is to use Set instead of SetDelayed: In[9]:= f[x_] = (a + b) /. ru[a] > Out[9]= b + x In[10]:= f[c] > Out[10]= b + c The drawback of this that not only the value of ru[a] is inserted but also > the whole expression including ReplaceAll is evaluated. If this is not > wanted, you have to insert the value of ru[a] into the unevaluated rhs at > the definition. The general means for this are function application, With or > Replace: In[7]:= (g[x_] := (a + b) /. #) &[ru[a]] > In[8]:= g[c] > Out[8]= b + c In[16]:= Clear[g] > In[20]:= > Unevaluated[g[x_] := (a + b) /. rule] /. rule -> ru[a] > In[21]:= g[c] > Out[21]= b + c Here we have to prevent evaluation of the defintion before our rule is > inserted, this is achieved by Unevaluated. With is a bit more complicated, since the scoping rules for SetDelayed would > not allow the substition of an expression at rhs containing a pattern > variable (the pattern variable is renamed in this case). A simple answer to > this is to also substitute the argument variable (the pattern): > In[31]:= Clear[g] > In[32]:= > With[{rule = ru[a], arg = x_}, g[arg] := (a + b) /. rule] > In[33]:= g[c] > Out[33]= b + c -- > Hartmut Wolf ==== Try In[1]:= M={{1,2,3},{4,5,6},{7,8,9}}; In[2]:= Export[test.csv,M,CSV]; Also, avoid using names with capital initial, since these are usually reserved for Mathematica functions. Tomas Garza Mexico City ----- Original Message ----- > M={{1,2,3},{4,5,6},{7,8,9}}; > TableForm[M] 1 2 3 > 4 5 6 > 7 8 9 The commands like Put or Write create files with a standard Mathematica > matrix notation with braces, I get the the same result with Save As/Copy Robert ==== I would appreciate if someone could tell me how to put my output for example a matrix in TableForm as a space-delimited ASCII file in Mathematica 3.0. for example: M={{1,2,3},{4,5,6},{7,8,9}}; TableForm[M] 1 2 3 4 5 6 7 8 9 The commands like Put or Write create files with a standard Mathematica matrix notation with braces, I get the the same result with Save As/Copy Robert ==== Much longer. At least 10 times as long. Not sure because I quit. As I read Bobby Treat's response, one of my processors had been laboring for more than three days to generate all the digits. (I had not considered to display or print all of them. Why on Earth would I want to do that?) So I started over, asking RealDigits to skip most of the digits. Tom Burton > > > So would it take about the same amont of time for the complete printout > of digits? Of course it would take a few additional seconds to format > the output... > > Or does Mathematica take alot less time when it truncates the output? > > >> >> >>> Could you tell me the CPU you used and its speed etc...i am curious, >>> other programs out there. >> >> I used one processor of a dual 1GH Mac and got the same answer with the >> following speed: >> >> 4.2 for Mac OS X (June 4, 2002) >> oldmax = $MaxPrecision >> 6 >> 1. 10 >> $MaxPrecision = Infinity >> Infinity >> With[{n = 2^26}, Timing[ >> pd = RealDigits[N[Pi, n + 1], 10, 20, >> 19 - n]; ]] >> {28794.1 Second, Null} >> MaxMemoryUsed[] >> 512055204 >> pd >> {{3, 3, 8, 6, 3, 2, 2, 0, 8, 9, 6, 2, 2, 3, >> >> 4, 0, 9, 8, 0, 3}, -67108844} >> >> Tom Burton > ==== Often posters to MathGroup copy and paste in the complete cell expression, including the In and Out numbers, when posting to MathGroup. I wonder if this is the best method because one can't then just copy out all the statements and paste them into a Mathematica notebook. All the statement numbers have to be edited out and if there are many statement definitions this is an extended task for any responder. This, of course, decreases the chances for a response. A better method is for the poster to just copy and paste the CONTENTS of each cell. This is more work for the poster, but it may pay off in better responses. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ ==== David, I agree with you that it makes responding and using easier if the In and Out numbers are not included. An easier way to do this, rather than copying the contents of the cells, is Usually a little manual reformating is needed to distinguish text, input and output --- I try to use one tab indent for input and two tabs indent for output, plus some blank line adjustment. I wonder if anyone has a way of automatically achieving this reformating. -- Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay@haystack.demon.co.uk Voice: +44 (0)116 271 4198 > Often posters to MathGroup copy and paste in the complete cell expression, > including the In and Out numbers, when posting to MathGroup. I wonder if this is the best method because one can't then just copy out all > the statements and paste them into a Mathematica notebook. All the statement > numbers have to be edited out and if there are many statement definitions > this is an extended task for any responder. This, of course, decreases the > chances for a response. A better method is for the poster to just copy and > paste the CONTENTS of each cell. This is more work for the poster, but it > may pay off in better responses. David Park > djmp@earthlink.net > http://home.earthlink.net/~djmp/ ==== copying and pasting is straightforward. I always run my notebooks this way, because showing the In[x], Out[x] does not seem to provide me with much beyond clutter. Kevin > Often posters to MathGroup copy and paste in the complete cell expression, > including the In and Out numbers, when posting to MathGroup. I wonder if this is the best method because one can't then just copy out all > the statements and paste them into a Mathematica notebook. All the statement > numbers have to be edited out and if there are many statement definitions > this is an extended task for any responder. This, of course, decreases the > chances for a response. A better method is for the poster to just copy and > paste the CONTENTS of each cell. This is more work for the poster, but it > may pay off in better responses. David Park > djmp@earthlink.net > http://home.earthlink.net/~djmp/ ==== >In a presentation I wish to use Plot to generate a sequence of frames and >then animate them. The problem is that the audience sees the animation >twice. Once when the frames are being generated and then again after I have >closed the group and double clicked on the top graphic. However, the first >showing during generation is enough (but uncontrolled). > >Hugh Goyder This creates a graphics cell from a graphics expression. GraphicCell[graphics_] := Cell[GraphicsData[PostScript, DisplayString[graphics]],Graphics] cellgroup. Block[{$DisplayFunction=Identity, graphs}, graphs = Table[GraphicCell[ Plot[Sin[t]*Sin[x], {x, 0, Pi}, PlotRange -> {{0, Pi}, {-1, 1}}, ImageSize -> 400]], {t,0,15,.1}]; NotebookWrite[EvaluationNotebook[],Cell[CellGroupData[graphs,Closed]]]; SelectionMove[EvaluationNotebook[], All, GeneratedCell]; FrontEndExecute[{FrontEndToken[EvaluationNotebook[], SelectionAnimate]}] ] -------------------------------------------------------------- Omega Consulting The final answer to your Mathematica needs Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html ==== Actually, the reason why ImpliesQ (and FullSimplify) fail to prove the implication is not that the hypothesis is a disjunction. To use the cylindrical algebraic decomposition algorithm they need to know that the assumptions imply that all variables are real. The assumptions mechanism infers variable domains in a purely syntactical way, i.e. v is assumed to be real if there is an Element[v, Reals] statement or v appears in an inequality. It does not attempt to analyze assumptions further, to figure out that, say y6 >= -1 implies that y6 is real, and then if we have y5 == y6 then y5 must be real too. Doing such an analysis in general would require solving the assumptions over complex numbers, and then finding out which variables need to be real. This would be in general too time consuming to do, but analyzing linear dependencies like the ones in your example is a possible future improvement. ImpliesQ cannot prove the implication here, because it knows only that y6 is real. In[1]:= <= -1 && y5 == y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[2]= False If we add an explicit assumption that y4 and y5 are real, ImpliesQ (and FullSimplify) can prove this implication, and the full version of your example. In[3]:= ImpliesQ[Element[y4|y5, Reals] && y4 == -1 && y6 >= -1 && y5 == y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[3]= True In[4]:= ImpliesQ[Element[y4|y5, Reals] && (y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6), y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] Out[4]= True In[5]:= FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, Element[y4|y5, Reals] && (y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6)] Out[5]= True Adam Strzebonski Wolfram Research > > On second thoughts I realized that there seems to be an inherent > ambiguity about what one coudl mean by using alternatives (statements > joned by Or) assumptions. In fact it now seems to me that the > reasonable intertpretation for ImpliesQ and FullSimplify ought to > perhaps be different. It seems to me that ImpliesQ[Or[a,b],c] ought to > return True if aand only if ImpliesQ[a,c] and ImpliesQ[b,c] both return > True. If so this could be acomplished by adding the rule > ImpliesQ[Or[a,b],c] = And[ImpliesQ[a,c],ImpliesQ[b,c]]. That could then > be used in proving that the two answers to the system of inequalities > that of Vincent's original posting are equivalent. On the other hand > probably FullSimplify[a, Or[p,q]] ought to return > Or[FullSimplify[a,p],FullSimplify[a,q]] (or do nothing as it doe snow). > The first approach would seem to be consistent with the way > FullSimplify works with domain specifications but would however have > the strange effect of returning True if just one of the alternatives > were true and the other false. So perhaps after all it is best to > leave FullSimplify as it is. However, it seems to me that ImpliesQ > shoud be able to handle such cases (?) > > Andrzej Kozlowski > Toyama International University > JAPAN > > > The modification to FullSimplify that I sent earlier works correctly > only for assumptions of the form Or[a,b] (and even then not is not > always what one would like). For what it's worth here is a better (but > slow) version: In[1]:= > Unprotect[FullSimplify]; In[2]:= > FullSimplify[expr_, x_ || y__] := FullSimplify[ > FullSimplify[expr, x] || FullSimplify[expr, Or[y]]]; In[3]:= > Protect[FullSimplify]; For example: In[4]:= > FullSimplify[Sqrt[(x - 1)^2] + Sqrt[(x - 2)^2] + > Sqrt[(x - 3)^2], x > 1 || x > 2 || x > 3] Out[4]= > -1 + x + Abs[-3 + x] + Abs[-2 + x] || > -3 + 2*x + Abs[-3 + x] || 3*(-2 + x) Andrzej Kozlowski > Toyama International University > JAPAN >> The reason why InequalitySolve returns it's answer in what sometimes >> turns out to be unnecessarily complicated form is that the underlying >> algorithm, Cylindrical Agebraic Decomposition (CAD) returns its >> answers in this form. Unfortunately it seems to me unlikely that a >> simplification of the kind you need can be can be accomplished in any >> general way. To see why observe the following. First of all: >> In[1]:= >> FullSimplify[x > 0 || x == 0] >> Out[1]= >> x >= 0 >> This is fine. However: >> In[2]:= >> FullSimplify[x > 0 && x < 2 || x == 0 && x < 2] >> Out[2]= >> x == 0 || 0 < x < 2 >> Of course what you would like is simply 0 <= x < 2. One reason why >> you can't get it is that while Mathematica can perform a >> LogicalExpand, as in: >> In[3]:= >> LogicalExpand[(x > 0 || x == 0) && x < 2] >> Out[3]= >> x == 0 && x < 2 || x > 0 && x < 2 >> There i no LogicalFactor or anything similar that would reverse >> what LogicalExpand does. if there was then you could perform the sort >> of simplifications you need for: >> In[4]:= >> FullSimplify[(x > 0 || x == 0) && x < 2] >> Out[4]= >> 0 <= x < 2 >> However, it does not seem to me very likely that such logical >> factoring can be performed by a general enough algorithm (though I >> am no expert in this field). In any case, certainly Mathematica can't >> do this. >> I also noticed that Mathematica seems unable to show that the answer >> it returns to your problem is actually equivalent to your simpler >> one. In fact this looks like a possible bug in Mathematica. Let's >> first try the function ImpliesQ from the Experimental context: >> << Experimental` >> Now Mathematica correctly gives: >> In[6]:= >> ImpliesQ[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 >> <= 1 + y4 + y6] >> Out[6]= >> True >> However: >> In[7]:= >> ImpliesQ[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && >> y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + >> y4 + y6] >> Out[7]= >> False >> That simply means that ImpliesQ cannot show the implication, not that >> it does not hold. ImpliesQ relies on CAD, as does FullSimplify. >> Switching to FullSimplify we see that: >> In[8]:= >> FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 >> && >> y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + >> y4 + y6] >> Out[8]= >> True >> while >> In[9]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 >> <= 1 + y4 + y6] >> Out[9]= >> y4 >= -1 && y6 <= y5 <= 1 + y4 + y6 >> On the other hand, taking just the individual summands of Or as >> hypotheses; >> In[10]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] >> Out[10]= >> True >> In[11]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 ] >> Out[11]= >> True >> In fact FullSimplify is unable to use Or in assumptions, which can be >> demonstrated on an abstract example: >> In[12]:= >> FullSimplify[C,(A||B)&&(C)] >> Out[12]= >> True >> In[13]:= >> FullSimplify[C,LogicalExpand[(A||B)&&(C)]] >> Out[13]= >> C >> This could be fixed by modifying FullSimplify: >> In[14]:= >> Unprotect[FullSimplify]; >> In[14]:= >> FullSimplify[expr_,Or[x_,y__]]:=Or[FullSimplify[expr,x],FullSimplify[e >> xpr,y]]; >> In[15]:= >> Protect[FullSimplify]; >> >> Now at least we get as before: >> In[16]:= >> FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 >> && >> y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + >> y4 + y6] >> Out[16]= >> True >> but also: >> In[17]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 >> <= 1 + y4 + y6] >> Out[17]= >> True >> This seems to me a possible worthwhile improvement in FullSimplify, >> though of course not really helpful for your problem. >> Andrzej Kozlowski >> Toyama International University >> JAPAN >>> I have a set of inequalities that I solve with InequalitySolve. But >>> then >>> it gives a complete set of solutions, but not in the way I would >>> like it >>> to be! :-) For example, the simple following calculation will give: >>>> In[1]:= ineq = {y4 >= -1, y5 >= -1, y6 + y4 >= y5 - 1, y5 >= y6, y6 >>>= -1}; >>> InequalitySolve[ineq,{y4,y6,y5}] >>>> Out[1]:= y4 == -1 && y6 >= -1 && y5 == y6 || >>> y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 >>>> the result is good, but I would like it to be in the simpler but >>> equivalent form >>>> y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 >>>> How can I tell InequalitySolve to do that? It is simple for this >>> example, >>> but for a large set of simple inequalities InequalitySolve gives >>> lines and >>> lines of results instead of a simple result. >>>>> Vincent Bouchard >>>> ==== On second thoughts I realized that there seems to be an inherent ambiguity about what one could mean by using alternatives (statements joned by Or) assumptions. In fact it now seems to me that the reasonable intertpretation for ImpliesQ and FullSimplify ought to perhaps be different. It seems to me that ImpliesQ[Or[a,b],c] ought to return True if aand only if ImpliesQ[a,c] and ImpliesQ[b,c] both return True. If so this could be acomplished by adding the rule ImpliesQ[Or[a,b],c] = And[ImpliesQ[a,c],ImpliesQ[b,c]]. That could then be used in proving that the two answers to the system of inequalities that of Vincent's original posting are equivalent. On the other hand probably FullSimplify[a, Or[p,q]] ought to return Or[FullSimplify[a,p],FullSimplify[a,q]] (or do nothing as it doe snow). The first approach would seem to be consistent with the way FullSimplify works with domain specifications but would however have the strange effect of returning True if just one of the alternatives were true and the other false. So perhaps after all it is best to leave FullSimplify as it is. However, it seems to me that ImpliesQ shoud be able to handle such cases (?) Andrzej Kozlowski Toyama International University JAPAN > The modification to FullSimplify that I sent earlier works correctly > only for assumptions of the form Or[a,b] (and even then not is not > always what one would like). For what it's worth here is a better (but > slow) version: In[1]:= > Unprotect[FullSimplify]; In[2]:= > FullSimplify[expr_, x_ || y__] := FullSimplify[ > FullSimplify[expr, x] || FullSimplify[expr, Or[y]]]; > > In[3]:= > Protect[FullSimplify]; For example: In[4]:= > FullSimplify[Sqrt[(x - 1)^2] + Sqrt[(x - 2)^2] + > Sqrt[(x - 3)^2], x > 1 || x > 2 || x > 3] Out[4]= > -1 + x + Abs[-3 + x] + Abs[-2 + x] || > -3 + 2*x + Abs[-3 + x] || 3*(-2 + x) Andrzej Kozlowski > Toyama International University > JAPAN >> The reason why InequalitySolve returns it's answer in what sometimes >> turns out to be unnecessarily complicated form is that the underlying >> algorithm, Cylindrical Agebraic Decomposition (CAD) returns its >> answers in this form. Unfortunately it seems to me unlikely that a >> simplification of the kind you need can be can be accomplished in any >> general way. To see why observe the following. First of all: >> In[1]:= >> FullSimplify[x > 0 || x == 0] >> Out[1]= >> x >= 0 >> This is fine. However: >> In[2]:= >> FullSimplify[x > 0 && x < 2 || x == 0 && x < 2] >> Out[2]= >> x == 0 || 0 < x < 2 >> Of course what you would like is simply 0 <= x < 2. One reason why >> you can't get it is that while Mathematica can perform a >> LogicalExpand, as in: >> In[3]:= >> LogicalExpand[(x > 0 || x == 0) && x < 2] >> Out[3]= >> x == 0 && x < 2 || x > 0 && x < 2 >> There i no LogicalFactor or anything similar that would reverse >> what LogicalExpand does. if there was then you could perform the sort >> of simplifications you need for: >> In[4]:= >> FullSimplify[(x > 0 || x == 0) && x < 2] >> Out[4]= >> 0 <= x < 2 >> However, it does not seem to me very likely that such logical >> factoring can be performed by a general enough algorithm (though I >> am no expert in this field). In any case, certainly Mathematica can't >> do this. >> I also noticed that Mathematica seems unable to show that the answer >> it returns to your problem is actually equivalent to your simpler >> one. In fact this looks like a possible bug in Mathematica. Let's >> first try the function ImpliesQ from the Experimental context: >> << Experimental` >> Now Mathematica correctly gives: >> In[6]:= >> ImpliesQ[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 >> <= 1 + y4 + y6] >> Out[6]= >> True >> However: >> In[7]:= >> ImpliesQ[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && >> y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + >> y4 + y6] >> Out[7]= >> False >> That simply means that ImpliesQ cannot show the implication, not that >> it does not hold. ImpliesQ relies on CAD, as does FullSimplify. >> Switching to FullSimplify we see that: >> In[8]:= >> FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 >> && >> y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + >> y4 + y6] >> Out[8]= >> True >> while >> In[9]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 >> <= 1 + y4 + y6] >> Out[9]= >> y4 >= -1 && y6 <= y5 <= 1 + y4 + y6 >> On the other hand, taking just the individual summands of Or as >> hypotheses; >> In[10]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6] >> Out[10]= >> True >> In[11]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 ] >> Out[11]= >> True >> In fact FullSimplify is unable to use Or in assumptions, which can be >> demonstrated on an abstract example: >> In[12]:= >> FullSimplify[C,(A||B)&&(C)] >> Out[12]= >> True >> In[13]:= >> FullSimplify[C,LogicalExpand[(A||B)&&(C)]] >> Out[13]= >> C >> This could be fixed by modifying FullSimplify: >> In[14]:= >> Unprotect[FullSimplify]; >> In[14]:= >> FullSimplify[expr_,Or[x_,y__]]:=Or[FullSimplify[expr,x],FullSimplify[e >> xpr,y]]; >> In[15]:= >> Protect[FullSimplify]; >> Now at least we get as before: >> In[16]:= >> FullSimplify[y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 >> && >> y6 <= y5 <= 1 + y4 + y6, y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + >> y4 + y6] >> Out[16]= >> True >> but also: >> In[17]:= >> FullSimplify[y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6, >> y4 == -1 && y6 >= -1 && y5 == y6 || y4 > -1 && y6 >= -1 && y6 <= y5 >> <= 1 + y4 + y6] >> Out[17]= >> True >> This seems to me a possible worthwhile improvement in FullSimplify, >> though of course not really helpful for your problem. >> Andrzej Kozlowski >> Toyama International University >> JAPAN >>> I have a set of inequalities that I solve with InequalitySolve. But >>> then >>> it gives a complete set of solutions, but not in the way I would >>> like it >>> to be! :-) For example, the simple following calculation will give: >>>> In[1]:= ineq = {y4 >= -1, y5 >= -1, y6 + y4 >= y5 - 1, y5 >= y6, y6 >>>= -1}; >>> InequalitySolve[ineq,{y4,y6,y5}] >>>> Out[1]:= y4 == -1 && y6 >= -1 && y5 == y6 || >>> y4 > -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 >>>> the result is good, but I would like it to be in the simpler but >>> equivalent form >>>> y4 >= -1 && y6 >= -1 && y6 <= y5 <= 1 + y4 + y6 >>>> How can I tell InequalitySolve to do that? It is simple for this >>> example, >>> but for a large set of simple inequalities InequalitySolve gives >>> lines and >>> lines of results instead of a simple result. >>>>> Vincent Bouchard >>>> ==== Hallo!, My name is Nagesh and pursuing research studies in Refrigeration. At present I am writing a Dynamic Refrigeration System Simulation Package. I am using Mathematica as a programming language for the same since last one year. I don't have any programming experience before this. I have following querries:- 1. Is any body here have expertise or information about the capability of Mathematica as a system simulation tool? 2. Is is possible to program a user friendly interface for my system simulation package with Mathematica or I have to use some other software? 3. My refrigeration system simulation package is likely to have approximately 60 First order Differential equations. Is is possible to solve these in Mathematica ? If yes then can anybody here guide me about this further. I am explaining below in short about the objectives I want to fulfill from coding out of my main input file 1. Example from Main Input File ( this will contain about 200-250 variables which will be entered by the user of this package) Below is examples of two variables entered into this file, which will be used in other analysis files for further evaluation. 2. Example from other analysis file ( there will be about 20-25 other such component analysis files ) where the above mentioned variables from main input file will be used for further evaluations:- Below is one example from this file explaining how the variables from main input file will be used in other files. I hope that this short information will be useful for guiding me to solve the following problems that I am facing. I am facing follwing problems or objectives:- 1. My 1st Objective:- The user of this package must be able to change only the value of the variable in the main input file but he must not be able to change the name of the variable itself. For example he must be able to change the value of the variable but he must not be able to change the name of this variable itself. Here our problem is how to achieve or program it so that our objective will be fullfilled. 2. My 2nd Objective:- How I can program the main input file so that it will be user friendly in terms of its visuals and satisfying the constraint mentioned above in objective1. 3. My 3rd Objective:- How can I program the optional values for each variable in the main input file ? so that there will be always a value assigned to each variable listed in main input file whenever the user opens up this file. If user want to change the values of some variables then he can change them and run the simulation otherwise the simulation run will be done with optional values assigned to each variable in the input file. 4. My 4th Objective:- How can I program the check for correctness of the input values supplied by the package user ? I will be very greatful to you for helping and suggesting some technique or method to solve some of my above mentioned programming problems. Can anybody here guide me about the above mentioned programming problems ? Nagesh Rajepandhare ==== I want to add a further suggestion: Probably each differential equation logically belongs to one of the defined classes in the sense, that it helps to define the behaviour of the component. In this case, each differential equation should be stored in one of theses classes as textstring in a form appropriate for the execution in Mathematica. Hermann Schmitt ----- Original Message ----- Is any body here have expertise or information about the capability of > Mathematica as a system simulation tool? > Mr. Kuska answers: > Since the most system simulation tools are simply solving a system of > ordinary differntial equations it is simple to do this with NDSolve[]. My comment: That is: He sees the simulation system merely as a set of differential > equations. The question of Mr. Nagesh: My 4th Objective:- How can I program the check for correctness of the > input values supplied by the package user ? > The answer of Mr. Kuska is: > And @@ (NumericQ /@ {aListOfAllYourNumericParameters}) My comment: This is a nice command and shows the knowledge of Mr.Kuska. But does Mr. > Nagesh understand it and is it sufficient to check, if all inputs are > numerical? Additionally I think, it is not userfriendly to see the input merely as a > set of 200-250 numbers. My suggestion is, that JLink is used, a suggestion Mr. Kusk takes into > consideration, too. But further I suggest, that classes are defined in Java, which represent the > parts of the system. Constructors of the classes should build objects with default values. > Graphical user interfaces should give the opportunity to change the data fields in the objects and > check the input for correctness. The system should give the opportunity, to store the objects on harddisk > (serialization). accessed directly. > My name is Nagesh and pursuing research studies in Refrigeration. At > present I am writing a Dynamic Refrigeration System Simulation Package. > I > am using Mathematica as a programming language for the same since last > one > year. I don't have any programming experience before this. I have > following > querries:- > 1. Is any body here have expertise or information about the capability > of > Mathematica as a system simulation tool? Since the most system simulation tools are simply solving a system of > ordinary differntial equations it is simple to do this with NDSolve[]. 2. Is is possible to program a user friendly interface for my system > simulation package with Mathematica or I have to use some other > software? Write a MathLink or J/Link frontend that launch the kernel. But you > should keep > in mind that the user interface is typical 80-90 % of your code. > If you just whant to solve some ode's it is probably easyer to > include one of the excelent ode-solvers from netlib in your C-code > than to call Mathematica to do that. As long as you dont wish to change > the ode's very often (than Mathematica is more flexible) you should > not use Mathematica. 3. My refrigeration system simulation package is likely to have > approximately 60 First order Differential equations. Is is possible to > solve these in Mathematica ? Sure. > If yes then can anybody here guide me about > this further. Write down the equations and call NDSolve[]. > I am explaining below in short about the objectives I want to fulfill > from > coding out of my main input file > > 1. Example from Main Input File ( this will contain about 200-250 > variables > which will be entered by the user of this package) This sounds like a *very* userfiendly interface ;-) > Below is examples of two variables entered into this file, which will be > used in other analysis files for further evaluation. 2. Example from other analysis file ( there will be about 20-25 other > such > component analysis files ) where the above mentioned variables from main > input file will be used for further evaluations:- Below is one example from this file explaining how the variables from > main > input file will be used in other files. I hope that this short information will be useful for guiding me to > solve > the following problems that I am facing. I am facing follwing problems > or > objectives:- 1. My 1st Objective:- The user of this package must be able to change > only > the value of the variable in the main input file but he must not be able > to > change the name of the variable itself. For example he must be able to > change the value of the variable but he must not be able to change > the > name of this variable itself. > Here our problem is how to achieve or program it so that our objective > will > be fullfilled. Options with defaulf values ? or something like {aParam,bParam}={ODEParameter1,ODEParameter2} /. > userRules /. > {ODEParameter1->1,ODEParameter2->2} > 2. My 2nd Objective:- How I can program the main input file so that it > will > be user friendly in terms of its visuals and satisfying the constraint > mentioned above in objective1. What is *userfiendly* in a file with 250 variables ??? > 3. My 3rd Objective:- How can I program the optional values for each > variable in the main input file ? so that there will be always a value > assigned to each variable listed in main input file whenever the user > opens > up this file. If user want to change the values of some variables then > he > can change them and run the simulation otherwise the simulation run will > be > done with optional values assigned to each variable in the input file. See above. > 4. My 4th Objective:- How can I program the check for correctness of the > input values supplied by the package user ? And @@ (NumericQ /@ {aListOfAllYourNumericParameters}) > Jens > ==== I have developed one package where it is included a functions for solving System of ODE. You can downloaded from: http://web.usal.es/~guillerm/biokmod. The functions are: SystemDSolve and SystemNDSolve Guillermo Sanchez > I want to add a further suggestion: > Probably each differential equation logically belongs to one of the defined > classes in the sense, that it helps to define the behaviour of the > component. > In this case, each differential equation should be stored in one of theses > classes as textstring in a form appropriate for the execution in > Mathematica. > Hermann Schmitt > ----- Original Message ----- > > I agree with Mr. Kuska, that the system Mr Nagesh describes is not > userfriendly. But I think, the suggestions of Mr. Kuska do not make it > more > userfriendly, rather the opposite is true. Mr. Nagesh asks Is any body here have expertise or information about the capability of > Mathematica as a system simulation tool? > Mr. Kuska answers: > Since the most system simulation tools are simply solving a system of > ordinary differntial equations it is simple to do this with NDSolve[]. My comment: That is: He sees the simulation system merely as a set of differential > equations. The question of Mr. Nagesh: My 4th Objective:- How can I program the check for correctness of the > input values supplied by the package user ? > The answer of Mr. Kuska is: > And @@ (NumericQ /@ {aListOfAllYourNumericParameters}) My comment: This is a nice command and shows the knowledge of Mr.Kuska. But does Mr. > Nagesh understand it and is it sufficient to check, if all inputs are > numerical? Additionally I think, it is not userfriendly to see the input merely as a > set of 200-250 numbers. > > My suggestion is, that JLink is used, a suggestion Mr. Kusk takes into > consideration, too. But further I suggest, that classes are defined in Java, which represent > the > parts of the system. Constructors of the classes should build objects with default values. > Graphical user interfaces should give the opportunity to change the data fields in the objects and > check the input for correctness. The system should give the opportunity, to store the objects on harddisk > (serialization). accessed directly. > My name is Nagesh and pursuing research studies in Refrigeration. At > present I am writing a Dynamic Refrigeration System Simulation > Package. > I > am using Mathematica as a programming language for the same since last > one > year. I don't have any programming experience before this. I have > following > querries:- > 1. Is any body here have expertise or information about the capability > of > Mathematica as a system simulation tool? Since the most system simulation tools are simply solving a system of > ordinary differntial equations it is simple to do this with NDSolve[]. 2. Is is possible to program a user friendly interface for my system > simulation package with Mathematica or I have to use some other > software? Write a MathLink or J/Link frontend that launch the kernel. But you > should keep > in mind that the user interface is typical 80-90 % of your code. > If you just whant to solve some ode's it is probably easyer to > include one of the excelent ode-solvers from netlib in your C-code > than to call Mathematica to do that. As long as you dont wish to change > the ode's very often (than Mathematica is more flexible) you should > not use Mathematica. 3. My refrigeration system simulation package is likely to have > approximately 60 First order Differential equations. Is is possible to > solve these in Mathematica ? Sure. > If yes then can anybody here guide me about > this further. Write down the equations and call NDSolve[]. > I am explaining below in short about the objectives I want to fulfill > from > coding out of my main input file 1. Example from Main Input File ( this will contain about 200-250 > variables > which will be entered by the user of this package) This sounds like a *very* userfiendly interface ;-) > Below is examples of two variables entered into this file, which will > be > used in other analysis files for further evaluation. 2. Example from other analysis file ( there will be about 20-25 other > such > component analysis files ) where the above mentioned variables from > main > input file will be used for further evaluations:- Below is one example from this file explaining how the variables from > main > input file will be used in other files. I hope that this short information will be useful for guiding me to > solve > the following problems that I am facing. I am facing follwing problems > or > objectives:- 1. My 1st Objective:- The user of this package must be able to change > only > the value of the variable in the main input file but he must not be > able > to > change the name of the variable itself. For example he must be able to > change the value of the variable but he must not be able to > change > the > name of this variable itself. > Here our problem is how to achieve or program it so that our objective > will > be fullfilled. Options with defaulf values ? or something like {aParam,bParam}={ODEParameter1,ODEParameter2} /. > userRules /. > {ODEParameter1->1,ODEParameter2->2} > 2. My 2nd Objective:- How I can program the main input file so that it > will > be user friendly in terms of its visuals and satisfying the constraint > mentioned above in objective1. What is *userfiendly* in a file with 250 variables ??? > 3. My 3rd Objective:- How can I program the optional values for each > variable in the main input file ? so that there will be always a value > assigned to each variable listed in main input file whenever the user > opens > up this file. If user want to change the values of some variables then > he > can change them and run the simulation otherwise the simulation run > will > be > done with optional values assigned to each variable in the input file. See above. > 4. My 4th Objective:- How can I program the check for correctness of > the > input values supplied by the package user ? And @@ (NumericQ /@ {aListOfAllYourNumericParameters}) > Jens > ==== I agree with Mr. Kuska, that the system Mr Nagesh describes is not userfriendly. But I think, the suggestions of Mr. Kuska do not make it more userfriendly, rather the opposite is true. Mr. Nagesh asks Is any body here have expertise or information about the capability of Mathematica as a system simulation tool? Mr. Kuska answers: Since the most system simulation tools are simply solving a system of ordinary differntial equations it is simple to do this with NDSolve[]. My comment: That is: He sees the simulation system merely as a set of differential equations. The question of Mr. Nagesh: My 4th Objective:- How can I program the check for correctness of the input values supplied by the package user ? The answer of Mr. Kuska is: And @@ (NumericQ /@ {aListOfAllYourNumericParameters}) My comment: This is a nice command and shows the knowledge of Mr.Kuska. But does Mr. Nagesh understand it and is it sufficient to check, if all inputs are numerical? Additionally I think, it is not userfriendly to see the input merely as a set of 200-250 numbers. My suggestion is, that JLink is used, a suggestion Mr. Kusk takes into consideration, too. But further I suggest, that classes are defined in Java, which represent the parts of the system. Constructors of the classes should build objects with default values. Graphical user interfaces should give the opportunity to change the data fields in the objects and check the input for correctness. The system should give the opportunity, to store the objects on harddisk (serialization). accessed directly. My name is Nagesh and pursuing research studies in Refrigeration. At > present I am writing a Dynamic Refrigeration System Simulation Package. I > am using Mathematica as a programming language for the same since last one > year. I don't have any programming experience before this. I have following > querries:- > 1. Is any body here have expertise or information about the capability of > Mathematica as a system simulation tool? Since the most system simulation tools are simply solving a system of > ordinary differntial equations it is simple to do this with NDSolve[]. 2. Is is possible to program a user friendly interface for my system > simulation package with Mathematica or I have to use some other software? Write a MathLink or J/Link frontend that launch the kernel. But you > should keep > in mind that the user interface is typical 80-90 % of your code. > If you just whant to solve some ode's it is probably easyer to > include one of the excelent ode-solvers from netlib in your C-code > than to call Mathematica to do that. As long as you dont wish to change > the ode's very often (than Mathematica is more flexible) you should > not use Mathematica. 3. My refrigeration system simulation package is likely to have > approximately 60 First order Differential equations. Is is possible to > solve these in Mathematica ? Sure. > If yes then can anybody here guide me about > this further. Write down the equations and call NDSolve[]. > I am explaining below in short about the objectives I want to fulfill from > coding out of my main input file 1. Example from Main Input File ( this will contain about 200-250 variables > which will be entered by the user of this package) This sounds like a *very* userfiendly interface ;-) > Below is examples of two variables entered into this file, which will be > used in other analysis files for further evaluation. 2. Example from other analysis file ( there will be about 20-25 other such > component analysis files ) where the above mentioned variables from main > input file will be used for further evaluations:- Below is one example from this file explaining how the variables from main > input file will be used in other files. I hope that this short information will be useful for guiding me to solve > the following problems that I am facing. I am facing follwing problems or > objectives:- 1. My 1st Objective:- The user of this package must be able to change only > the value of the variable in the main input file but he must not be able to > change the name of the variable itself. For example he must be able to > change the value of the variable but he must not be able to change the > name of this variable itself. > Here our problem is how to achieve or program it so that our objective will > be fullfilled. Options with defaulf values ? or something like {aParam,bParam}={ODEParameter1,ODEParameter2} /. > userRules /. > {ODEParameter1->1,ODEParameter2->2} > 2. My 2nd Objective:- How I can program the main input file so that it will > be user friendly in terms of its visuals and satisfying the constraint > mentioned above in objective1. What is *userfiendly* in a file with 250 variables ??? > 3. My 3rd Objective:- How can I program the optional values for each > variable in the main input file ? so that there will be always a value > assigned to each variable listed in main input file whenever the user opens > up this file. If user want to change the values of some variables then he > can change them and run the simulation otherwise the simulation run will be > done with optional values assigned to each variable in the input file. See above. > 4. My 4th Objective:- How can I program the check for correctness of the > input values supplied by the package user ? And @@ (NumericQ /@ {aListOfAllYourNumericParameters}) > Jens > ==== See my comments in the following text! Hermann Schmitt ----- Original Message ----- sofu = Interpolation[ ==== > Lucas, > > I'm certainly not competent to give you any answer, and me too, I'd be eager > to hear such -- hoped Wolfram's to react; anyway, here is my opinion. > > PrecedenceForm is only for parenthesizing at output. > > Although we have MakeExpressions to add semantic actions to the Mathematica > compiler (if we may call such the transformation from input string, i.e. > language, to the internal representation as indicated by FullForm i.e. > code), we cannot influence the Mathematica syntax proper, i.e. parsing. > The operator precedence rules however are part of that (esp. needed for box > formation). So I can't see a way to reach your goal. > > Now, I don't know what your ordinary Plus shall designate. If it's only > abstract, i.e. you don't use it for numeric calculation, you possibly might > interchange the roles of Plus and CirclePlus > > In[6]:= a [CirclePlus] b + c [CirclePlus] d > Out[6]= a[CirclePlus]b + c[CirclePlus]d > > As for BigCirclePlus (if you still need it after the reassigned meanings) > I'd try to define a palette, but perhaps this is not possible to the extend > you desire. I never tried. > > Another approach would be to use Union and Intersection for low precedence > plus and low precedence times (or [Subset]; [Superset] or [And]; [Or] > or [Therefore];[Because] or ...). > > The ultima ratio is to write a new front end. > > But, if I were you, I'd ignore these kind of problems at first and set up > the package fully functioning (with 1D input), apply it to your problems and > investigations, and finally, when time comes to publishing, at output > formatting you have quite a lot of choices. > > I'm sorry, just wanted to keep the discussion alive, since anyway, this is > of much interest. is actually quite simple -- just a list of expressions. If I had an appropriate OutputForm written then the effect would be: {expr1, expr2, ..., exprN} --> expr1 [CirclePlus] expr2 [CirclePlus] ... So certainly I cn get a functional package, but the final product should be notationally similar to the pure mathematical reference. I'm sure this is a goal shared by many. If anyone is curious about what exactly I'm up to, I'm attempting to implement a Clocked Objective Function package based (primarily) on these publications: A Lagrangian Formulation of Neural Networks I: Theory and Analog Dynamics A Lagrangian Formulation of Neural Networks II: Clocked Objective Functions and Applications Both are found in Neural, Parallel and Scientific Computations 6 (1998) 297-372, authors are Eric Mjolsness and Willard L. Miranker -Lucas Scharenbroich -JPL / MLS Group ==== > I am writing a Java application that displays Mathematica output using > MathCanvas. I am having difficulty in that the internal frames > (JInternalFrame)in my application are covered by the MathCanvas when > the internal frames are moved into the MathCanvas area. I tried > setting the frame's layer to 0, but that didn't work. Can anyone help > me out? I suppose the problem is, that MathCanvas is an AWT Component, which causes problem with the other Swing JComponents; 2 possible solutions: - get J/Link 2.0, which comes with a Swing version of MathCanvas (MathGraphicsJPanel if memory serves); - if you can't do that, write a Swing replacement for MathCanvas using Swing; this is pretty simple: you can use the evaluateToImage methods, which return a byte array containg a GIF Image; if you want to make it very simple, you just make your control a JPanel that contains a JLabel, and when you want to set a M_-GraphicsExpression (from a Plot,...) you just set the GIF Image as the JLabels Icon; something like this (jlPlot being the JLabel): StdLink.requestTransaction();^M byte [] bGifData = kl.evaluateToImage(sExpression, width,height); if (bGifData == null || bGifData.length <= 1){ System.out.println(bGifData empty); } Image iPlot = Toolkit.getDefaultToolkit().createImage(bGifData); iiPlot.setImage(iPlot); jlPlot.setIcon(iiPlot); jlPlot.repaint(); murphee ==== > I am writing a Java application that displays Mathematica output using > MathCanvas. I am having difficulty in that the internal frames > (JInternalFrame)in my application are covered by the MathCanvas when > the internal frames are moved into the MathCanvas area. I tried > setting the frame's layer to 0, but that didn't work. Can anyone help > me out? I suppose the problem is, that MathCanvas is an AWT Component, which causes problem with the other Swing JComponents; 2 possible solutions: - get J/Link 2.0, which comes with a Swing version of MathCanvas (MathGraphicsJPanel if memory serves); - if you can't do that, write a Swing replacement for MathCanvas using Swing; this is pretty simple: you can use the evaluateToImage methods, which return a byte array containg a GIF Image; if you want to make it very simple, you just make your control a JPanel that contains a JLabel, and when you want to set a M_-GraphicsExpression (from a Plot,...) you just set the GIF Image as the JLabels Icon; something like this (jlPlot being the JLabel): StdLink.requestTransaction();^M byte [] bGifData = kl.evaluateToImage(sExpression, width,height); if (bGifData == null || bGifData.length <= 1){ System.out.println(bGifData empty); } Image iPlot = Toolkit.getDefaultToolkit().createImage(bGifData); iiPlot.setImage(iPlot); jlPlot.setIcon(iiPlot); jlPlot.repaint(); murphee ==== I am writing a Java application that displays Mathematica output using MathCanvas. I am having difficulty in that the internal frames (JInternalFrame)in my application are covered by the MathCanvas when the internal frames are moved into the MathCanvas area. I tried setting the frame's layer to 0, but that didn't work. Can anyone help me out? ==== I wonder if someone knows a fast way to import data from a tab-separated file when numbers use coma (instead of point) as a decimal separator. I know how to do this using: Import[MyFile.txt,Table,ConversionOptions ->{NumberPoint->,}] However I got to noticed that Import is far much time and memory consiming than ReadList[]. Anyone as an idea? TIA ==== > I am having a strange problem with a function giving a complex number as > a result. I did the following: > - define a function: > denom[x_, p_, d_] := Sqrt[1 + (x*Tan[p]/d)^2] > > Integrate and simplify it with the assumption that d is larger than 0: > FullSimplify[Integrate[denom[x, p, d], {x, 0, d}], d > 0] > > The result of the above line is > d/2*(1+i*Sqrt[2]*d*Cos[p]^2)*Sqrt[Sec[p]^2] where i is Sqrt[-1] > > I assing it to a function called peter in the following way: > peter[p_, d_] := FullSimplify[Integrate[denom[x, p, d], {x, 0, d}], d>0] > > and check the value of the function at [0,1] > peter[0,1] > > and the result is 1. > How is it possible that the result doesn't have an imaginary part??? > I would expect the result to be 0.5+Sqrt[2]/2*i > You are evaluating the integral each time that you call peter. When you call it with p=0 denom is evaluated to 1 before the integration. Define peter with Evaluate or else don't use a delayed set. denom[x_,p_,d_]:=Sqrt[1+(x*Tan[p]/d)^2]; peter[p_,d_]:=Evaluate[FullSimplify[Integrate[denom[x,p,d],{x,0,d}],d>0]]; peter2[p_,d_]:=FullSimplify[Integrate[denom[x,p,d],{x,0,d}],d>0]; peter[0,1] (1/2)*(1 + I*Sqrt[2]) peter2[0,1] 1 peter2[10^-6,1]//N 0.5 + 0.707107*I peter2[-10^-6,1]//N 0.5 + 0.707107*I Bob Hanlon Chantilly, VA USA ==== (1) To discourage alteration of the program file, save it as a binary file. Look up DumpSave in Help. (2) To discourage alteration of symbols within a Mathematica session, use the Locked attributed. (3) To finally answer your question, use the ReadProtected attribute on symbols you would like viewers not to see. Hope this helps, Tom ==== > I am having a strange problem with a function giving a complex number as > a result... You should perhaps examine the integral of denom. Do you really expect a complex result? The integral involves multibranched functions (a fact masked a bit by the form Tan[p] in the integrand; try replacing Tan[p] by p to see what is going on). Is your result on the branch you want? I suspect not; you are probably after a real result. The following modification produces a real result: Integrate[denom[x, p, d], {x, 0, d}, PrincipalValue -> True, GenerateConditions -> False] But you'll need to take the limit p->0. Hope this helps, Tom Burton ==== The integral doesn't converge when b is real, because of the second order singularity at Abs[b] in that case. Arg[b^2]!=0 is used to express this because the issue is whether that singularity is on the positive x-axis. Behavior at 0 and Infinity are fine if Re[a]>0, but otherwise those are problems too, so Mathematica has the right answer in those terms. I can't vouch for the formula it comes up with when the conditions are met, but it's not closed-form in the usual sense anyway; but it's closed-form in terms of functions MATHEMATICA is comfortable with! Bobby Treat -----Original Message----- (Pi - 2*SinIntegral[a*Sqrt[-(1/b^2)]])), Integrate[1/(E^(a/x)*(-b^2 + x^2)), {x, 0, Infinity}]] If b is Real then Arg[b^2]==0 and Mathematica doesn't solve it. Let's define a function that allows us to test specific values of a and b. f[a_, b_][x_] = Exp[-a/x]/(x^2 - b^2); Integrate[f[2, 3][x], {x, 0, Infinity}] Integrate::idiv : Integral of 1/(E^(2/x)*(-9 + x^2)) does not converge on {0, Infinity}. But if we use an imaginary value for b... Integrate[f[2, 3I][x], {x, 0, Infinity}] %//N (1/6)*(2*CosIntegral[2/3]*Sin[2/3] + Cos[2/3]*(Pi - 2*SinIntegral[2/3])) 0.254022 David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ Master«s Degree of Applied Physics - Unesp/Rio Claro - State of S.8bo Paulo - Brazil Laboratory of Electrical Measurements phone : ( 0XX19 ) 526 - 2237 ********************************************************************* ==== > > > I solved the epidemic SIR ODE System > ( > ) numerically using NDSolve: > > approxsolutions=NDSolve[{ > > s«[t]==-a s[t] i[t], > i«[t]==a s[t] i[t] - b i[t], > r«[t]==b i[t], > > s[0]==700, i[0]==1, r[0]==0}, {i[t], s[t], r[t]}, {t,0,20}]; > > and this for fixed values of a and b. > > Now I want to fit the solution for variable a and b to a list of given > points (fitting using the least squares method and the mathematica fonction > findminimum). My questions are > 1- Is it possible to solve the ODE (with mathematica) for not fixed values > of a and b (so to get a parametric solution that depends on a and b)? > 2- Is it possible in mathematica to use the fonction findminimum with the > (not explicit) solutions of the ODE, if not are there some other > alternatives? > > In advance, thank you very much > > Majid There was a discussion on this topic three years ago. The URL below will take you to a reply in that thread that includes remarks and code from Carl Woll and myself. I'll also show some code for your specific example, in order to indicate potential problems. http://library.wolfram.com/mathgroup/archive/1999/Oct/msg00104.html Below is some mildly clumsy code tailored to your example. It will do the DE solving given parameter values, form an objective function (sum-of-squares type) given actual data and solutions for specific parameters, and to do the minimization. I did everything at machine precision but this is not necessarily a good idea. Also I do no error checking e.g. for cases where the numeric DE solver fails to solve over the full range. A related issue is that, depending on roughly where the correct parameter values live, and how close you are in your initial guess, this might not be at all a well-behaved problem. machsoln[a_?NumericQ,b_?NumericQ] := First[NDSolve[{ D[ss[t],t]==-a*ss[t]*ii[t], D[ii[t],t]==a*ss[t]*ii[t]-b*ii[t], D[rr[t],t]==b*ii[t], ss[0]==700, ii[0]==1, rr[0]==0}, {ii[t], ss[t], rr[t]}, {t,0,20}]]; machsol = machsoln[1/100,1]; We'll generate some data for parameter values a=1/100, b=1. machdata = Table[{t,ii[t],ss[t],rr[t]} /. machsol, {t,0,20,5}] For the objective function, given numeric values for {a,b}, we'll solve the system, evaluate at the same 't' values as are used for our data, subtract resulting vectors from corresponding data vectors, take norm squares, and sum. objfunc[data_,{a_?NumericQ,b_?NumericQ}] := Module[ {iii, sss, rrr, newdata, vals}, {iii,sss,rrr} = {ii[t],ss[t],rr[t]} /. machsoln[a,b]; newdata = Map[{iii,sss,rrr} /. t-># &, Map[First,data]]; vals = Map[#.#&, Map[Rest,data]-newdata]; Apply[Plus, vals] ] For example, we will get 0 if we use {a,b} = {.01,1}, and something nonzero if we increase both modestly, say by 10%. In[85]:= objfunc[machdata, {.01,1.}] Out[85]= 0. In[86]:= objfunc[machdata, {.011,1.1}] Out[86]= 72.5289 With the above objective function we can call FindMinimum. For this we will use two starting values for each parameter so that FIndMinimum can use a secant method. An alternative to this, wherein one passes along a gradient black box evaluator, is presented by Carl Woll in his note at the URL above. findParams[data_, inits:{a1_,b1_}] := Module[ {vals,a,b}, FindMinimum[objfunc[data,{a,b}], {a,a1,a1+.1*a1}, {b,b1,b1+.1*b1}] ] For example, if I give {a,b} = {.011,1.1} as initial values, I get a result reasonably fast and quite accurate, albeit with many warnings indicated. They basically indicate In[87]:= findParams[data, {.011,1.1}] InterpolatingFunction::dmval: Input value {20} lies outside the range of data in the interpolating function. Extrapolation will be used. InterpolatingFunction::dmval: Input value {20} lies outside the range of data in the interpolating function. Extrapolation will be used. InterpolatingFunction::dmval: Input value {20} lies outside the range of data in the interpolating function. Extrapolation will be used. General::stop: Further output of InterpolatingFunction::dmval will be suppressed during this calculation. -11 Out[87]= {8.46495 10 , {a$4965 -> 0.01, b$4965 -> 1.}} It still does reasonably well when I perturb by 50% from the correct parameter values. This time the warning message indicates that we might be closer to trouble. In[89]:= findParams[data, {.015,1.5}] FindMinimum::fmcv: Failed to converge to the requested accuracy or precision within 30 iterations. -10 Out[89]= {6.48159 10 , {a$8747 -> 0.01, b$8747 -> 1.}} You might want to play with various options in FindMinimum such as MaxIterations. You might also need to use NDSolve options e.g. WorkingPrecision in order to improve the quality of the result. Daniel Lichtblau Wolfram Research ==== I solved the epidemic SIR ODE System ( ) numerically using NDSolve: approxsolutions=NDSolve[{ s«[t]==-a s[t] i[t], i«[t]==a s[t] i[t] - b i[t], r«[t]==b i[t], s[0]==700, i[0]==1, r[0]==0}, {i[t], s[t], r[t]}, {t,0,20}]; and this for fixed values of a and b. Now I want to fit the solution for variable a and b to a list of given points (fitting using the least squares method and the mathematica fonction findminimum). My questions are 1- Is it possible to solve the ODE (with mathematica) for not fixed values of a and b (so to get a parametric solution that depends on a and b)? 2- Is it possible in mathematica to use the fonction findminimum with the (not explicit) solutions of the ODE, if not are there some other alternatives? In advance, thank you very much Majid Reply-To: kjm@KevinMcCann.com ==== Majid, I separately sent you a nb that addresses the numerical curve fit of an NDSolve result. I have had this and have used the technique for a long time; the example, however, did not originate with me. Apologies to the original author - lost in the mists of mind and time. Kevin > > I solved the epidemic SIR ODE System > ( > ) numerically using NDSolve: > > approxsolutions=NDSolve[{ > > s«[t]==-a s[t] i[t], > i«[t]==a s[t] i[t] - b i[t], > r«[t]==b i[t], > > s[0]==700, i[0]==1, r[0]==0}, {i[t], s[t], r[t]}, {t,0,20}]; > > and this for fixed values of a and b. > > Now I want to fit the solution for variable a and b to a list of given > points (fitting using the least squares method and the mathematica > fonction findminimum). My questions are > 1- Is it possible to solve the ODE (with mathematica) for not fixed values > of a and b (so to get a parametric solution that depends on a and b)? > 2- Is it possible in mathematica to use the fonction findminimum with the > (not explicit) solutions of the ODE, if not are there some other > alternatives? > > In advance, thank you very much > > Majid ==== Let say you have your data in an array like so: data = {{5, {685, 12, 4}}, {10, {550, 105, 50}}, {15, {207, 250, 244}}, {20, {69, 169, 463}}} where 5, 10, 15, 20 are the observation times. (These numbers are perturbed slightly from an actual solution.) The following defines the least squares error as a function of a and b: LSE[a_, b_] := Module[ {diff, sir = {s[t],i[t],r[t]} /. NDSolve[{s'[t]== -a*s[t]*i[t], i'[t]== a*s[t]*i[t] - b*i[t], r'[t]== b*i[t], s[0]== 700, i[0]== 1, r[0]== 0}, {s[t],i[t],r[t]}, {t, 0, 20}]//First }, diff:=(sir/.t->data[[i,1]]) - data[[i,2]]; Sum[diff.diff, {i, Length[data]}] ] Now... In: FindMinimum[ LSE[a, b], {a, 0, .1}, {b, 0, 1}]//Timing Out: {5.7 sec, {14.1967, {a -> 0.000999599, b -> 0.200351}}} --- Selwyn Hollis > > I solved the epidemic SIR ODE System > ( > ) numerically using NDSolve: > > approxsolutions=NDSolve[{ > > s«[t]==-a s[t] i[t], > i«[t]==a s[t] i[t] - b i[t], > r«[t]==b i[t], > > s[0]==700, i[0]==1, r[0]==0}, {i[t], s[t], r[t]}, {t,0,20}]; > > and this for fixed values of a and b. > > Now I want to fit the solution for variable a and b to a list of given > points (fitting using the least squares method and the mathematica fonction > findminimum). My questions are > 1- Is it possible to solve the ODE (with mathematica) for not fixed values > of a and b (so to get a parametric solution that depends on a and b)? > 2- Is it possible in mathematica to use the fonction findminimum with the > (not explicit) solutions of the ODE, if not are there some other > alternatives? > > In advance, thank you very much > > Majid > > ==== In order to do some transformations on a tree I need to be able to replace an expression with head hdA if and if only its parent has head hdB and its grandparent had head hdC. Furthermore, the item itself and its parent may have any number sibling elements. What I do now is the following. Give the expression: ttexpr = grandparent[ parent1[grandchild2[], grandchild1[], grandchild4[], grandchild1[]], grandchild1[], parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]]; I apply a rule: ttexpr /. { grandparent[left1___, parent1[left2___, grandchild1[], right2___], right1___] -> grandparent[left1, parent1[left2, MATCHED[], right2], right1]} which gives the desired expression: grandparent[parent1[grandchild2[], MATCHED[], grandchild4[], grandchild1[]], grandchild1[], parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]] But I have the feeling that it should be possible to do this more elegantly. Does anybody have an idea in this respect? Sidney Cadot ==== Perhaps you could use ReadList with the option Word, which will read your data in as strings. Then you may substitute commas with periods and convert to numbers with ToExpression? Tomas Garza Mexico City ----- Original Message ----- > 2,234 2,567 2,89 > 3,234 3,567 3,89 > I know how to do this using Import: Import[MyFile.txt, Table, > ConversionOptions -> {NumberPoint -> ,}] ; However, Import is not the function I'd like to use, because it is realy > slow over large files. I wonder if someone knows a way to use something faster than Import (I > namely think of ReadList) with coma-numbers? > ==== Yes, Import is slow, I suppose because of it's generality. Your particular case seems to be close to one that ReadList can handle efficiently. Therefore I would recommend the following sequence of steps: (1) Use ReadList to read into Words instead of Numbers. (2) Use StringReplace to replace , with . within words. (3) Convert the words to expressions with ToExpression. This should be easy provided that you do not encounter scientific notation (1,3e6). Tom Burton ==== > If I want to protect the Mathematica Program, what can I do? > Is there any method to avoid other people's reading my program but > it is still able to run fluently? Encode does what you're after .... Dave. ========================================== Dr. David Annetts EM Modelling Analyst Australia David.Annetts@csiro.au =========================================== ==== I try to solve a three equation linear ODE system with constant When I try the same thing on Mathematica 4.0 (Solaris) I get a very strange result containing things like E^x#1 OR #1^2. Am I doing something wrong, or is there a bug/problem with Mathematica. Neil -- Solving a Three Equation ODE system (Linear with Constant Coefficients) with Mathematica 3.0 ---- INPUT: DSolve[{y1'[x] + c11*y1[x] + c12*y2[x] +c13*y3[x] +c1==0, y2'[x]+c21*y1[x]+c22*y2[x]+c23*y3[x]+c2==0, y3'[x]+c31*y1[x]+c32*y2[x]+c33*y3[x]+c3==0, y1[0]==y1i, y2[0]==y2i, y3[0]==y3i}, {y1[x], y2[x], y3[x]}, x] OUTPUT: Eigensystem::eivec: Unable to find eigenvector for eigenvalue !(Root[((((c13 c22 c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + ([LeftSkeleton] 20 [RightSkeleton])) &), 1)]). Eigensystem::eivec: Unable to find eigenvector for eigenvalue !(Root[((((c13 c22 c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + ([LeftSkeleton] 20 [RightSkeleton])) &), 2)]). Eigensystem::eivec: Unable to find eigenvector for eigenvalue !(Root[((((c13 c22 c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + ([LeftSkeleton] 20 [RightSkeleton])) &), 3)]). General::stop: Further output of !(Eigensystem :: eivec) will be suppressed during this calculation. -- ______________________________________________________ Neil E. Klepeis, UC Berkeley, School of Public Health, and Lawrence Berkeley National Laboratory, ==== Neil, They are not a general analitical solution for a system of ODE with 3 or more variables where all coffs. are parameters. I have a package for solving SODE. Perhaps you can find it useful. Guillermo Sanchez > I try to solve a three equation linear ODE system with constant > > When I try the same thing on Mathematica 4.0 (Solaris) I get a very > strange result containing things like E^x#1 OR #1^2. > > Am I doing something wrong, or is there a bug/problem with Mathematica. > > Neil > > > > -- Solving a Three Equation ODE system (Linear with Constant > Coefficients) with Mathematica 3.0 ---- > > INPUT: > > DSolve[{y1'[x] + c11*y1[x] + c12*y2[x] +c13*y3[x] +c1==0, > y2'[x]+c21*y1[x]+c22*y2[x]+c23*y3[x]+c2==0, > y3'[x]+c31*y1[x]+c32*y2[x]+c33*y3[x]+c3==0, > y1[0]==y1i, y2[0]==y2i, y3[0]==y3i}, > {y1[x], y2[x], y3[x]}, x] > > OUTPUT: > > Eigensystem::eivec: > Unable to find eigenvector for eigenvalue !(Root[((((c13 > c22 > c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + > ([LeftSkeleton] 20 [RightSkeleton])) &), 1)]). > Eigensystem::eivec: > Unable to find eigenvector for eigenvalue !(Root[((((c13 > c22 > c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + > ([LeftSkeleton] 20 [RightSkeleton])) &), 2)]). > Eigensystem::eivec: > Unable to find eigenvector for eigenvalue !(Root[((((c13 > c22 > c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + > ([LeftSkeleton] 20 [RightSkeleton])) &), 3)]). > General::stop: > Further output of !(Eigensystem :: eivec) will be suppressed > during this calculation. Reply-To: nklepeis@uclink4.berkeley.edu ==== Guillermo, indoor air exposure to particulate matter. Does your package use Runge-Kutta or some other numerical algorithm? I'm thinking of something like that, but with a fixed (non-adaptive) step size. Neil > Neil, > > They are not a general analitical solution for a system of ODE with 3 > or more variables where all coffs. are parameters. I have a package > for solving SODE. Perhaps you can find it useful. > > > Guillermo Sanchez > > >>I try to solve a three equation linear ODE system with constant >>When I try the same thing on Mathematica 4.0 (Solaris) I get a very >>strange result containing things like E^x#1 OR #1^2. >>Am I doing something wrong, or is there a bug/problem with Mathematica. >>Neil >>-- Solving a Three Equation ODE system (Linear with Constant >>Coefficients) with Mathematica 3.0 ---- >>INPUT: >>DSolve[{y1'[x] + c11*y1[x] + c12*y2[x] +c13*y3[x] +c1==0, >> y2'[x]+c21*y1[x]+c22*y2[x]+c23*y3[x]+c2==0, >> y3'[x]+c31*y1[x]+c32*y2[x]+c33*y3[x]+c3==0, >> y1[0]==y1i, y2[0]==y2i, y3[0]==y3i}, >> {y1[x], y2[x], y3[x]}, x] >>OUTPUT: >>Eigensystem::eivec: >> Unable to find eigenvector for eigenvalue !(Root[((((c13 >>c22 >>c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + >>([LeftSkeleton] 20 [RightSkeleton])) &), 1)]). >>Eigensystem::eivec: >> Unable to find eigenvector for eigenvalue !(Root[((((c13 >>c22 >>c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + >>([LeftSkeleton] 20 [RightSkeleton])) &), 2)]). >>Eigensystem::eivec: >> Unable to find eigenvector for eigenvalue !(Root[((((c13 >>c22 >>c31) - (c12 c23 c31) - (c13 c21 c32) + (c11 c23 c32) + >>([LeftSkeleton] 20 [RightSkeleton])) &), 3)]). >>General::stop: >> Further output of !(Eigensystem :: eivec) will be suppressed >>during this calculation. > > -- ______________________________________________________ Neil E. Klepeis, UC Berkeley, School of Public Health, and Lawrence Berkeley National Laboratory, Berkeley, CA USA. Voice: 831-768-9510 ==== To the Group, In[104]:= LaplaceTransform[D[f[t],t],t,s] Out[104]= -f[0] + s LaplaceTransform[f[t],t,s] In[105]:= LaplaceTransform[Integrate[f[t],t],t,s] Out[105]= LaplaceTransform[Integrate[f[t] ,t], t, s] Item 104 is correct, but item 105 is not. The correct 105 should be: -f[0]/s + LaplaceTransform[f[t],t,s]/s . If Mathematica can get 104 right, then it should also produce a correct 105. This looks like a bug. Any thoughts on this? (Note: Number 105 does not look like that on the notebook page. It shows the indefinite integral with an integral symbol followed by f[t] dt instead of the function Integrate[ ]. I've spelled it out because the Vista Research, Inc. ==== I would like to match a named pattern in an expression and then square the result. But my attempt fails. Clear[f, g, x, y, a] expr = 3*f[x]*g[y] + 2 + x^2; expr /. a:(f[_]*g[_]) :> a^2 2 + x^2 + 3*f[x]*g[y] If I drop the name on the pattern, it matches - but it doesn't do what I want. expr /. f[_]*g[_] :> a^2 2 + 3*a^2 + x^2 How can I name such a pattern and use it on the rhs of a rule? David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ ==== > I would like to match a named pattern in an expression and then square the > result. But my attempt fails. > > [...] David Park > djmp@earthlink.net > > I simplified your example to see whats the problem. I only take the multiplication of three symbols a, b, c. In[1]:= Clear[a, b, c, p, x, y] If you use the unnamed pattern 'a c' in Replace you get In[2]:= a b c /. a c :> x Out[2]= b x the replacement will be done because all possibilites of the multiplication are tested and the right one will be found. But if you take a named pattern 'p : a c' your are searching for a multiplication of exactly two variables called 'a' and 'c' and you are not successful with the replacement: In[3]:= a b c /. p : a c :> x Out[3]= a b c In this case you have to take into account that the multiplication can consist of more than two terms, e. g. In[4]:= a b c /. p : a c z___ :> x z Out[4]= b x¬ Hope that will help you, -- Rainer Gruber ==== I want to get the coefficient of the Legendre-Gauss Quadrature, I find this method is fast, but when the integration result is big, then the result is not accurate enough, I think it is because I only use 5 coefficient to compute it. Do you think it will be accurater when I use more coefficients to compute? Is possible to get 16 coefficients to compute? The 6 coefficients I use are from: http://mathworld.wolfram.com/Legendre-GaussQuadrature.html I need more coefficients to get accurater result. How about the method of the Integration function built-in Mathematica? Chen ==== The package NumericalMath`GaussianQuadrature` has what you want. --- Selwyn Hollis > I want to get the coefficient of the Legendre-Gauss Quadrature, > I find this method is fast, but when the integration result is big, then the result is > not accurate enough, I think it is because I only use 5 coefficient to compute it. > Do you think it will be accurater when I use more coefficients to compute? > Is possible to get 16 coefficients to compute? > The 6 coefficients I use are from: > http://mathworld.wolfram.com/Legendre-GaussQuadrature.html > > I need more coefficients to get accurater result. > How about the method of the Integration function built-in Mathematica? > > Chen > ==== The presence of 3* in your formula prevents the match pattern you want form taking place since: In[11]:= FullForm[3*f[x]*g[y]] Out[11]//FullForm= Times[3,f[x],g[y]] use instead: In[12]:= expr=3*f[x]*g[y]+2+x^2; In[13]:= expr /. a:((p_.)*f[_]*g[_]) :> p*a^2 Out[13]= 2 + x^2 + 27*f[x]^2*g[y]^2 Andrzej Kozlowski Toyama International University JAPAN > I would like to match a named pattern in an expression and then square > the > result. But my attempt fails. Clear[f, g, x, y, a] > expr = 3*f[x]*g[y] + 2 + x^2; expr /. a:(f[_]*g[_]) :> a^2 > 2 + x^2 + 3*f[x]*g[y] If I drop the name on the pattern, it matches - but it doesn't do what > I > want. expr /. f[_]*g[_] :> a^2 > 2 + 3*a^2 + x^2 How can I name such a pattern and use it on the rhs of a rule? David Park > djmp@earthlink.net > http://home.earthlink.net/~djmp/ ==== I need FrameLabels of the kind of H^s_z / H^p_Z and tried something like FrameLabel->{FontForm{HSuperscript[s]Subscript[z] ...}} but s is too far away from z. How can I manage it that s is directly above z ? Are there some backspace-characters to be used? Harry ==== Try Power[Subscript[H, z], s] I need FrameLabels of the kind of H^s_z / H^p_Z and tried something > like FrameLabel->{FontForm{HSuperscript[s]Subscript[z] ...}} but s is too far away from z. How can I manage it that s is > directly above z ? Are there some backspace-characters to be used? Harry ==== Try Power[Subscript[H, z], s] I need FrameLabels of the kind of H^s_z / H^p_Z and tried something > like FrameLabel->{FontForm{HSuperscript[s]Subscript[z] ...}} but s is too far away from z. How can I manage it that s is > directly above z ? Are there some backspace-characters to be used? Harry ==== >-----Original Message----- >Sent: Thursday, August 29, 2002 7:38 AM >I would like to match a named pattern in an expression and >then square the >result. But my attempt fails. > >Clear[f, g, x, y, a] >expr = 3*f[x]*g[y] + 2 + x^2; > >expr /. a:(f[_]*g[_]) :> a^2 >2 + x^2 + 3*f[x]*g[y] > >If I drop the name on the pattern, it matches - but it doesn't >do what I >want. > >expr /. f[_]*g[_] :> a^2 >2 + 3*a^2 + x^2 > >How can I name such a pattern and use it on the rhs of a rule? > >David Park >djmp@earthlink.net >http://home.earthlink.net/~djmp/ Dear David, just don't insist on a single name! In[17]:= expr /. (a : f[_])*(b : g[_]) :> (a*b)^2 Out[17]= 2 + x^2 + 3*f[x]^2*g[y]^2 In[29]:= 3*ff[z]*f[x]*g[y] + 2 + x^2 /. (a : f[_])*(b : g[_]) :> (a*b)^2 Out[29]= 2 + x^2 + 3*f[x]^2*ff[z]*g[y]^2 We might tend to understand this behaviour of the pattern matcher. As Times has the Flat, Orderless attributes, the components of the pattern have to be taken apart to match separated subexpressions at the lhs, what should the pattern variable then designate in the course of this procedure? Look at the FullForm In[31]:= (a : f[_])*(b : g[_]) // FullForm Out[31]//FullForm= Times[Pattern[a, f[Blank[]]], Pattern[b, g[Blank[]]]] compared to In[12]:= a : f[_]*g[_] // FullForm Out[12]//FullForm= Pattern[a, Times[f[Blank[]], g[Blank[]]]] Depending on your real problem... In[43]:= expr /. a_?NumericQ *b_ :> a*Times[b]^2 Out[43]= 2 + x^2 + 3*f[x]^2*g[y]^2 ...might be a more elegant (but risky) solution (?), or perhaps else (more robust if you know the names f,g)... In[79]:= expr /. a:(f | g)[___] :> a^2 Out[79]= 2 + x^2 + 3*f[x]^2*g[y]^2 In[139]:= expr /. a : h_[___] /; MemberQ[{f, g}, h] :> a^2 Out[139]= 2 + x^2 + 3*f[x]^2*g[y]^2 Perhaps a fine way would be In[74]:= 2 + x^2 + 3 f[x]*g[y] /. HoldPattern[Times[a:(_[___]..)]] :> Times[a]^2 Out[74]= 2 + x^2 + 3*f[x]^2*g[y]^2 but of course this only works if you have at least two factors f[] and g[] (and no mixed powers of x and y!) In that case come back to something like In[103]:= 2 + x^2*y^2 + 3*x*y^3*f[x]*g[y] + f[x] /. a : (_[___]) :> a^2 /; FreeQ[a, Power | Times] Out[103]= 2 + x^2*y^2 + f[x]^2 + 3*x*y^3*f[x]^2*g[y]^2 -- Hartmut ==== version 4.1.5.0 I try to do the simple task of transposing a matrix. X = {{a,b},{c,d},{e,f}} > whereas Transpose[{{a,b},{c,d},{e,f}}] works well. What is wrong with writing Transpose[X] ? Terje Johnsen ==== Andrzej, That doesn't work because I don't want to square the 3. Of course, I could divide by p but not in my actual example. In my actual example I am not squaring but doing a MetricSimplify tensor operation and the whole purpose is to operate on only two of four factors. I can do it by giving a specific pattern but not by using a general pattern. Here is a better example. expr = f[a]g[b]h[c]; This works... expr /. g[b]h[c] :> op[g[a]h[c]] f[a] op[g[a] h[c]] This even works with a more general pattern but is a silly way to do it... expr /. g[_]h[_] :> op[g[a]h[c]] f[a] op[g[a] h[c]] This is what I want to do, but again it doesn't work: expr /. p_. (sub : g[_]h[_]) :> p op[sub] f[a] g[b] h[c] I have to be able to obtain a name for the match to the g[_]h[_] pattern. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ In[13]:= expr /. a:((p_.)*f[_]*g[_]) :> p*a^2 Out[13]= 2 + x^2 + 27*f[x]^2*g[y]^2 Andrzej Kozlowski Toyama International University JAPAN > I would like to match a named pattern in an expression and then square > the > result. But my attempt fails. Clear[f, g, x, y, a] > expr = 3*f[x]*g[y] + 2 + x^2; expr /. a:(f[_]*g[_]) :> a^2 > 2 + x^2 + 3*f[x]*g[y] If I drop the name on the pattern, it matches - but it doesn't do what > I > want. expr /. f[_]*g[_] :> a^2 > 2 + 3*a^2 + x^2 How can I name such a pattern and use it on the rhs of a rule? David Park > djmp@earthlink.net > http://home.earthlink.net/~djmp/ ==== David, > I would like to match a named pattern in an expression and then square the > result. But my attempt fails. > > Clear[f, g, x, y, a] > expr = 3*f[x]*g[y] + 2 + x^2; > > expr /. a:(f[_]*g[_]) :> a^2 > 2 + x^2 + 3*f[x]*g[y] ... Well, I see that expr /. a:Times[f[_],g[_],h___]:> a^2 works, and I think I understand why your form above does not work (examine FullForm of expr--your form does not account for 3), but I don't understand why eliminating a: from your form allows the pattern to match. Tom Burton ==== I would expect that Plot[Sin[x]/Sin[x], {x, -2.5, -1.5}] would produce a horizontal line at y=1. However, on my Windows XP computer it produces a graph where the y value is less than 1 at several points. Most notibly between x=-1.6 and x=-1.8 Is this just an isolated case? Or does it happen to others? If so - why? Ken. ==== This results from: a) the fact that Mathematica implements division as multiplication and reciprocation b) the use of machine precision for plotting the graph c) the default scaling of the y axis revealing the resultant inaccuracies Although Sin[x]/Sin[x] gives 1 when evaluated symbolically (x undefined), substituting a floating-point value for x results in composite division being performed numerically, with consequent inaccuracy. This can be verified by the following: In[1]:= FullForm[HoldForm[Sin[x]/Sin[x]] Out[1]//FullForm= HoldForm[Times[Sin[x], Power[Sin[x], -1]]] By default, Mathematica scales the y axis such that the small discrepancies are visible. The PlotRange option may be given to explicitly specify the range for the y axis (for example PlotRange->{0, 2}). Ian McInnes. > I would expect that Plot[Sin[x]/Sin[x], {x, -2.5, -1.5}] would produce a horizontal line at y=1. However, on my Windows XP computer it produces a graph where the y value is > less than 1 at several points. Most notibly between x=-1.6 and x=-1.8 Is this just an isolated case? Or does it happen to others? If so - why? Ken. > ==== I get very small dips (vees?) at the same spots using 4.1. What is your experience with the presentation feature of version 4.2 ? That is what is attracting me to upgrade and I want to hear experiences. > I would expect that Plot[Sin[x]/Sin[x], {x, -2.5, -1.5}] would produce a horizontal line at y=1. However, on my Windows XP computer it produces a graph where the y value is > less than 1 at several points. Most notibly between x=-1.6 and x=-1.8 Is this just an isolated case? Or does it happen to others? If so - why? Ken. > ==== I eventually figured this one out: (1) change the default font to smaller (10 pts vs 12). This solves the problem, but makes the help text illegibly small. This is cured by step 2: (2) go into preferences and change the default zoom to larger (1.25 from 1). > The Windows, the Mathematica Help browser has a categories section, where > the headings and subheadings of each help file appear. In version 3.x, those > fonts (by default) appear nice and small (smaller than the text on the > menu). In 4.1, the font is so large I cannot read the entire heading. How > can I revert to the proper display? > Nicholas > ==== I am fairly new to Mathematica and once before asked a question and received some very helpful responses. This time the problem seems very odd and I may be making a very elementary error. Here is the context: I define a function of the form: f[...,listA_, newEntry_,...]:= Which[...] Here Which has the form of a set of logically exclusive and exhausive tests, each test with its own action that modifies the concrete list subsituted for listA_. For instance, if there were only two tests the rhs above would be one that puts the newEntry at the start of listA and the other that puts it at the end: Which[ test1, listA = Insert[listA, newEntry, 1], test2, listA = Insert[listA, newEntry, -1] ] Then I try to use the function, substituting values for the arguments: f[..., listA, newEntry, ...]. The output should be the appropriately modified list. But my actual output reproduces the input form, i.e., it is simply f[...listA,newEntry,...]. Yet, the program does do something, as the use of evaluate in placeshows: Suppose that test1 is satisfied by the particular values of the arguments. Then when I apply evaluate in place to the lhs of the action that is supposed to occur when test1 is true, in fact the value of Insert[listA,newEntry,1] is correct, but the rhs gives only the initial value of listA and not the modified value that is on the rhs. Concretely, suppose that in the function argument listA is {121} and newEntry is 200. Then after evaluation of the function (input to the kernel), that line reads, according to evaluate in place: true, {121} = {200, 121} So it seems that only part of the correct action was taken: 200 was put at the start of listA. But the assignment of this value -- the extended list -- to be the new value of listA did not take place. I then tried using a new name for the modified list, substituting this program line for test1: test1, newListA = Insert[listA, newEntry, 1] What I get here, applying evaluate in place after evaluating the function with concrete values as above is: true, newListA = {200, 121} Trace doesn't help because all I get back is the function name with its concrete arguments. Any thoughts? Tom ==== > > > In order to do some transformations on a tree I need to be able to replace > an expression with head hdA if and if only its parent has head hdB and its > grandparent had head hdC. Furthermore, the item itself and its parent may > have any number sibling elements. > > What I do now is the following. Give the expression: > > ttexpr = grandparent[ > parent1[grandchild2[], grandchild1[], grandchild4[], grandchild1[]], > grandchild1[], > parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]]; > > I apply a rule: > > ttexpr /. { > grandparent[left1___, parent1[left2___, grandchild1[], right2___], > right1___] - grandparent[left1, parent1[left2, MATCHED[], right2], right1]} > > which gives the desired expression: > > grandparent[parent1[grandchild2[], MATCHED[], grandchild4[], grandchild1[]], > grandchild1[], > parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]] > > But I have the feeling that it should be possible to do this more elegantly. > Does anybody have an idea in this respect? > > > Sidney Cadot I think your technique is fine for small to medium size trees. For large ones it might be very slow due to all the work of patten matching. If you anticipate large inputs you might thus want to code a simple tree-walk using old-fashioned procedural code. Any time you match a grandparent head, put that subtree onto a stack that enters the next state, looking for parent nodes, etc. Daniel Lichtblau Wolfram Research ==== with the output your own solution is giving you. I would have thought not, since only one grandchild1[] with parent parent1 and grandparent grandparent. is being matched. You can get a complete match by using ReplaceRepeated instead of ReplaceAll: In[33]:= ttexpr// .{grandparent[left1___,parent1[left2___,grandchild1[],right2___], right1___]-> grandparent[left1,parent1[left2,MATCHED[],right2],right1]} Out[33]= grandparent[parent1[grandchild2[],MATCHED[],grandchild4[],MATCHED[]], grandchild1[], parent2[grandchild2[],grandchild1[],grandchild4[],grandchild1[]]] exactly the same result can be achieved in a rather different way, which may perhaps be seen as more elegant. In[34]:= ttexpr /. expr_grandparent :> (expr /. expr1_parent1 :> (expr1 /. expr2_grandchild1 :> Matched[])) Out[34]= grandparent[parent1[grandchild2[], Matched[], grandchild4[], Matched[]], grandchild1[], parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]] Andrzej Kozlowski Toyama International University JAPAN In order to do some transformations on a tree I need to be able to > replace > an expression with head hdA if and if only its parent has head hdB and > its > grandparent had head hdC. Furthermore, the item itself and its parent > may > have any number sibling elements. What I do now is the following. Give the expression: ttexpr = grandparent[ > parent1[grandchild2[], grandchild1[], grandchild4[], > grandchild1[]], > grandchild1[], > parent2[grandchild2[], grandchild1[], grandchild4[], > grandchild1[]]]; I apply a rule: ttexpr /. { > grandparent[left1___, parent1[left2___, grandchild1[], right2___], > right1___] - grandparent[left1, parent1[left2, MATCHED[], right2], right1]} which gives the desired expression: grandparent[parent1[grandchild2[], MATCHED[], grandchild4[], > grandchild1[]], > grandchild1[], > parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]] > But I have the feeling that it should be possible to do this more > elegantly. > Does anybody have an idea in this respect? > Sidney Cadot ==== >I'm finding that the ImageSize option in Export has no effect when >exporting Cell or Notebook objects. For instance, the following two >commands produce precisely the same graphic: Export[image1.jpg, Cell[Some cell contents, Text, FontSize -> 100]] Export[image2.jpg, Cell[Some cell contents, Text, FontSize -100], ImageSize -> {576, 288}] > >Has anyone encountered this problem before? (This is with Mathematica 4.1.5 and Mac OS X.) ---- >Selwyn Hollis >slhollis@mac.com Export takes two options that control the size of a graphic, ImageSize and ImageResolution. The difference is sometimes subtle. ImageSize changes the coordinates while ImageResolution changes the size of objects. This may sound like the same thing, but they're actually different. If I have a plot with a line. Changing ImageSize changes the location of the points in the line, which may make the line shorter or longer, but the thickness is unchanged (if it is an AbsoluteThichness). ImageResolution draws the image with a different number of pixels, so lengths and thicknesses are changed. The same is true with fonts. Why does it matter? Because there is no equivalent to ImageSize for cells or notebooks. However, Magnification is a good equivalent of ImageResolution. So ImageSize does nothing, but ImageResolution does. In[1]:= cont=Cell[Some cell contents, Text, FontSize -> 100] In[2]:= Show@ImportString[ExportString[cont, JPEG], JPEG] In[3]:= Show@ImportString[ExportString[cont, JPEG, ImageResolution ->72*3/2], JPEG] -Dale ==== I was wondering if there is a method for resizing Raster graphics (resizing the actual matrix of pixels, not just the display size). I am processing a large number of JPEG images, and we sometimes need to reduce the image size to allow data processing algorithms to function without running out of memory. In the past we simply used a program such as Photoshop to resize them before importing them into Mathematica. Due to the number of images we are processing now this is very inconvenient and it would be very useful if there was a method for accomplishing it in Mathematica, but I can't find one. I also thought about doing something simple like sampling every few pixels or averaging, but I thought there might be a method with more efficacy than this. I also tried exporting the graphics with the Export command as new JPEGs and manipulating the ImageResolution and ImageSize options but this seemed to have no effect. Any help would be much appreciated. Aaron Urbas Reply-To: kuska@informatik.uni-leipzig.de ==== take the matrix of gray values or the matrix of the color channels, apply ListInterpolation[] and generate a resampled table with the interpolated function. Jens > > I was wondering if there is a method for resizing Raster graphics > (resizing the actual matrix of pixels, not just the display size). I > am processing a large number of JPEG images, and we sometimes need to > reduce the image size to allow data processing algorithms to function > without running out of memory. In the past we simply used a program > such as Photoshop to resize them before importing them into > Mathematica. Due to the number of images we are processing now this > is very inconvenient and it would be very useful if there was a method > for accomplishing it in Mathematica, but I can't find one. I also > thought about doing something simple like sampling every few pixels or > averaging, but I thought there might be a method with more efficacy > than this. I also tried exporting the graphics with the Export command > as new JPEGs and manipulating the ImageResolution and ImageSize > options but this seemed to have no effect. Any help would be much > appreciated. > Aaron Urbas ==== > I was wondering if there is a method for resizing Raster graphics > (resizing the actual matrix of pixels, not just the display size). I > am processing a large number of JPEG images, and we sometimes need to > reduce the image size to allow data processing algorithms to function > without running out of memory. In the past we simply used a program > such as Photoshop to resize them before importing them into > Mathematica. Due to the number of images we are processing now this > is very inconvenient and it would be very useful if there was a method > for accomplishing it in Mathematica, but I can't find one. I also > thought about doing something simple like sampling every few pixels or > averaging, but I thought there might be a method with more efficacy > than this. I also tried exporting the graphics with the Export command > as new JPEGs and manipulating the ImageResolution and ImageSize > options but this seemed to have no effect. Any help would be much > appreciated. > Aaron Urbas > Aaron, with the Digital Image Processing package see Downsample, Decimate or Resize. Else, the simplest method is to take every k'th sample, which can be done with the Take command. This imports the image and returns the raw data. img = Import[somefile.jpg][[1,1]]; For an image with dimensions nr x nc, and if you want to take every other sample use: small = Take[img, {1, nr, 2}, {1, nc, 2}]; You can also perform smoothing using ListConvolve prior to downsampling to eliminate some of the visual artifacts of downsampling. Done. -- =============================== Mariusz Jankowski University of Southern Maine mjkcc@usm.maine.edu 207-780-5580 ==== Yesterday I posted a question on using named patterns in a rule. I received a number of useful replies and thank all those who responded. Today I have a question that actually generated yesterday's question. I am using a new subject heading to reflect the actual nature of the question. What is the best way in Mathematica to operate on some, but not all, level parts of an expression or subexpression? Suppose I have the following expression... expr = f1[a]f2[b]f3[c]f4[d]; and I want to do an operation, op, separately on f1[a]f3[c] and f2[b]f4[d]. The operation must be done on the given pairs and not on all four factors at once. One method is to use explicit exact substitution rules. expr /. f1[a]f3[c] :> op[f1[a]f3[c]] /. f2[b]f4[d] :> op[f2[b]f4[d]] op[f1[a] f3[c]] op[f2[b] f4[d]] If a,b,c,d were long expressions, we might not want to type or copy them in. This raised my question of using named patterns. Hartmut Wolf pointed out that each factor must be named to create a match with flat expressions. So we could use... expr /. (a : f1[_])(b : f3[_])(c : f2[_])(d : f4[_]) :> op[a b]op[c d] op[f1[a] f3[c]] op[f2[b] f4[d]] Andrzej Kozlowski suggested a method using Take, but using Part works better here, so we could use... expr /. a_ :> op[a[[{1, 3}]]]*op[a[[{2, 4}]]] op[f1[a] f3[c]] op[f2[b] f4[d]] All of the above methods use rules. Is it possible to do it with ReplacePart? I don't think so, but maybe somebody knows how to do it. How about using MapAt? I don't think that works either in regular Mathematica. Ted Ersek and I did a package, Algebra`ExpressionManipulation` at my web site, that implements extended positions. An extended position gives the position of an expression and a list of the desired subparts and is packaged in a header eP. So the extended position of a + c in f[a + b + c + d] is eP[{1},{1,3}]. The package modifies MapAt to accept extended positions. Then we can use... MapAt[op, expr, {eP[{}, {1, 3}], eP[{}, {2, 4}]}] op[f1[a] f3[c]] op[f2[b] f4[d]] However, I don't always like to drag in the package just to do that. I think that operating on selected level parts of a subexpression is not all that uncommon. Here is another example. 1 - Cos[x]^2 % // TrigFactor 1 - Cos[x]^2 Sin[x]^2 But... 1 - a - Cos[x]^2 % // TrigFactor 1 - a - Cos[x]^2 (1/2)*(1 - 2*a - Cos[2*x]) I was hoping for -a + Sin[x]^2. What are the best methods for handling this kind of problem in regular Mathematica? David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ ==== and from kde2 to kde3 my Mathematica 3.0 doesn't work as usual any more: All the characters have become little rectangles, I can't read even the error message at the beginning. I followed the wolfram support page How do I resolve certain font-related error message when very carefully, but the error remains. Markus Koecher ==== I look for an operator, which has a higher precedence than @ and can be oberloaded with a new definition. According to the table in A.2, only PatternTest (?) could be a candidate. But according to my tests, PartitionTest cannot be overloaded with an new definition. What is your opinion? Hermann Schmitt ==== I have been trying to get emmathfnt to work for the past few hours but whatever I do the output file is slightly smaller than the input so I guess it isn't working and emmathfnt cannot find the font files. I also set FONTDIR. I am using the dos command emmathfnt -d C:Progra~1Wolfra~1Mathem~14.2System~1FontsType1 -o c:output.eps c:input.eps and the following is output C:WINDOWS>dir c:*put.eps Volume in drive C has no label Volume Serial Number is 0508-1ED9 Directory of C: OUTPUT EPS 26,324 08-30-02 9:57a output.eps INPUT EPS 26,324 08-30-02 10:21a input.eps 2 file(s) 52,648 bytes 0 dir(s) 4,896.69 MB free and if i run dir C:Progra~1Wolfra~1Mathem~14.2System~1FontsType1 I see the font files OK. input.eps was produced using the following Mathematica gr = Plot[Sin[[Alpha]], {[Alpha], -[Pi], [Pi]}, AxesLabel -> {[Alpha], Sin([Alpha])}] Export[c:input.eps, gr, EPS] both input and output set to StandardForm I wonder what I am doing wrong. C:WINDOWS>SET TMP=C:WINDOWSTEMP TEMP=C:WINDOWSTEMP PROMPT=$p$g winbootdir=C:WINDOWS COMSPEC=C:WINDOWSCOMMAND.COM PATH=C:DOWNLOADFONTZEMMATH~1;C:UTILSGHOSTGHOSTGUMGSVIEW;C:TE XMFMIKTEXB IN;C:WINDOWS;C:WINDOWSCOMMAND;C:MATLAB_SV12BINWIN32 FONTDIR=C:Program FilesWolfram ResearchMathematica4.2SystemFilesFontsType 1 windir=C:WINDOWS BLASTER=A220 I5 D3 T4 CMDLINE=emmathfnt -d C:Progra~1Wolfra~1Mathem~14.2System~1FontsType1 -o c:output.eps c:input.eps thankyou ==== > I would expect that Plot[Sin[x]/Sin[x], {x, -2.5, -1.5}] would produce a horizontal line at y=1. However, on my Windows XP computer it produces a graph where the y value is > less than 1 at several points. Most notibly between x=-1.6 and x=-1.8 Is this just an isolated case? Or does it happen to others? If so - why? > 4.1 for Mac OS X (November 5, 2001) p = Plot[Sin[x]/Sin[x],{x,-2.5,-1.5}]; Note that the Ticks on the y-axis are all 1, that is, in trying to find something of interest the adaptive range has zoomed in and is looking at the machine precision representations of 1. (First /@(Ticks /. AbsoluteOptions[p])[[2]])//InputForm Zoom out using the PlotRange Plot[Sin[x]/Sin[x],{x,-2.5,-1.5}, PlotRange->{-0.1,2.1}]; Or as stated in the on-line help for Plot: You should use Evaluate to evaluate the function to be plotted if this can safely be done before specific numerical values are supplied. Plot[Evaluate[Sin[x]/Sin[x]],{x,-2.5,-1.5}]; Bob Hanlon Chantilly, VA USA ==== I am trying to implement the inner product in the space of complex-valued, square integrable functions over [-1/2,1/2], which can be expressed in Mathematica code as inner[f_Function,g_function]:=Integrate[Conjugate[f[x]]*g[x],{x,-1/2,1/2}] This is simple enough. Problem is, Mathematica seamingly cannot evaluate the Integral for even the simplest of functions: In[10]:=inner[#&,#&] Out[10]:=!([Integral]_(-(1/2))%(1/2)(x Conjugate[ x]) [DifferentialD]x) As you see, the Integrate returns unevaluated. It works fine if I remove the Conjugate. Unfortunately the Conjugate is needed for positive definiteness. Various variants with Composition, Re and Im etc. don't work either. This should be a So how do I get Integrate to work with Conjugate? Andreas -- True Pleasure in this society is more dangerous than bank robbery. ==== Andreas Dietrich schrieb: > > I am trying to implement the inner product in the space of > complex-valued, square integrable functions over [-1/2,1/2], which can > be expressed in Mathematica code as > > inner[f_Function,g_function]:=Integrate[Conjugate[f[x]]*g[x],{x,-1/2,1/2}] > > This is simple enough. Problem is, Mathematica seamingly cannot > evaluate the Integral for even the simplest of functions: > In[10]:=inner[#&,#&] > > Out[10]:=!([Integral]_(-(1/2))%(1/2)(x Conjugate[ > x]) [DifferentialD]x) > Andreas, Conjugate does not evaluate the expression, if the variables aren't known to be real. Your example (inner[#&,#&]) works if you define your function using ComplexExpand: inner[f_,g_]:=Integrate[ComplexExpand[Conjugate[f[x]]]g[x], ...] You may also use a home-made Conjugate, I'll call it Konjugiert, eg: ruKonjugiert={Complex[re_,im_]:>Complex[re,-im]}; Konjugiert[ausdr__]:=ausdr /. ruKonjugiert; Replacing Conjugate with Konjugiert in your Definition works for your simple Example, but more komplex functions will need a ComplexExpand to get the wanted real result. Gru§ Peter -- =--=--=--=--=--=--=--=--=--=--=--=--=--= http://home.t-online.de/home/phbrf ==== Steve, here...). I am sending it pretty much in the same way as last time, with cc to mathgroup@smc.vnet.net (only this time with the intent that it not appear there). Daniel ------------------------------------------- > > > NDSolve seems to have difficulties with solving integral equation. > > n = 5; NDSolve[{D[[Sigma]norm[z, t], t] == 3*z*Integrate[[Sigma]norm[z, > t]^n*z, {z, 0, 1}] - [Sigma]norm[z, t]^n, > [Sigma]norm[z, 0] == 1.5*z, [Sigma]norm[0, t] == 0}*[Sigma]norm[z, > t], {z, 0.01, 1}, {t, 0.01, 2}] > > Mathematica returns a message > > NDSolve::deql: The first argument must have both an equation and an > initial condition. > > which I cannot understand. > Can anybody tell what's wrong with my attempt? > > -Toshi I'll show a couple of approaches to this sort of problem. The first is to iteratively solve for sn[k][z,t] in terms of sn[k-1][z,t], with sn[0][z,t] initialized to something appropriate (I used 3/2*z). The sn's are computed as interpolating functions based on results from solving ODEs in t for many fixed values of z. The code below does this for n=2. The plots at first appear to flip between two states but eventually stabilize. Note that this takes many minutes to run to completion. n = 2; sn[0][z_,t_] := 3/2*z; Do [ Do [ sn[k][z,t_] = sn[k][z,t] /. First[NDSolve[{D[sn[k][z,t], t] == 3*z*NIntegrate[sn[k-1][w,t]^n*w, {w,0,1}] - sn[k-1][z,t]^n, sn[k][z,0] == 3/2*z}, sn[k][z,t], {t,0,2}]], {z,0,1,1/100} ]; snew = Interpolation[Flatten[Table[{z,t,sn[k][z,t]}, {z,0,1,1/100}, {t,0,2,1/100}], 1], InterpolationOrder->7]; sn[k] = snew; Print[iteration , k]; Plot3D[sn[k][z,t], {z,0,1}, {t,0,2}], {k, 1, 15} ] One can test for convergence as below; it is apparently quite good. NIntegrate[Abs[sn[15][z,t]-sn[14][z,t]], {z,0,1}, {t,0,2}] A drawback to this method is that it appears to break down beyond n = 2. Possibly one simply needs a much better starting function for sn[0], I'm not sure. Below is another method that Michael Trott showed me. We expand in a set of basis functions in z, set up a system of ODEs in t, and solve them. I tried this using monomials in z for basis functions and ran into some trouble with the ODE solving, so I will show Michael's attempt using trig functions for the basis. Note that we now handle the desired case n=5; another advantage is that this is alot faster than the method above, though still not exactly blinding in speed. Michael used the interval {0,2} for z so as to achieve pointwise (not just L^2) convergence; otherwise there would be a sharp drop-off just before z=1 as all the trigs vanish there. In other words, the basis functions are of the form Sin[k/2*Pi] rather than Sin[k*Pi] for 1<=k<=deg. Cosines are excluded due to the vanishing condition at z=0. integrate[p_Plus, {z_, 0, 1}] := Integrate[#, {z, 0, 1}]& /@ p; integrate[p_, {z_, 0, 1}] := Integrate[p, {z, 0, 1}]; n = 5; deg = 6; vars[t_] = Map[#[t]&,Array[a,deg]]; zFuns = Sin[Range[deg] Pi/2 z]; sn[z_,t_] = vars[t].zFuns; eqs1 = 3*z*integrate[Expand[sn[w,t]^n*w],{w,0,1}] - sn[z,t]^n - D[sn[z,t],t]; eqs2 = integrate[Expand[eqs1 #], {z, 0, 1}]& /@ zFuns; iCs = integrate[Expand[(sn[z,0] - 3/2*z) #], {z, 0, 1}]& /@ zFuns; fulleqns = # == 0& /@ Join[eqs2, iCs]; nsd = NDSolve[fulleqns, vars[t], {t,0,2}, SolveDelayed->True]; Plot3D[Evaluate[sn[z,t] /. nsd[[1]]],{z,0,1},{t,0,2}]; an initializer for the iteration/interpolation method above in an attempt to refine the solution. Daniel Lichtblau Wolfram Research ==== > > > NDSolve seems to have difficulties with solving integral equation. > > n = 5; NDSolve[{D[[Sigma]norm[z, t], t] == 3*z*Integrate[[Sigma]norm[z, > t]^n*z, {z, 0, 1}] - [Sigma]norm[z, t]^n, > [Sigma]norm[z, 0] == 1.5*z, [Sigma]norm[0, t] == 0}*[Sigma]norm[z, > t], {z, 0.01, 1}, {t, 0.01, 2}] > > Mathematica returns a message > > NDSolve::deql: The first argument must have both an equation and an > initial condition. > > which I cannot understand. > Can anybody tell what's wrong with my attempt? > > -Toshi I'll show a couple of approaches to this sort of problem. The first is to iteratively solve for sn[k][z,t] in terms of sn[k-1][z,t], with sn[0][z,t] initialized to something appropriate (I used 3/2*z). The sn's are computed as interpolating functions based on results from solving ODEs in t for many fixed values of z. The code below does this for n=2. The plots at first appear to flip between two states but eventually stabilize. Note that this takes many minutes to run to completion. n = 2; sn[0][z_,t_] := 3/2*z; Do [ Do [ sn[k][z,t_] = sn[k][z,t] /. First[NDSolve[{D[sn[k][z,t], t] == 3*z*NIntegrate[sn[k-1][w,t]^n*w, {w,0,1}] - sn[k-1][z,t]^n, sn[k][z,0] == 3/2*z}, sn[k][z,t], {t,0,2}]], {z,0,1,1/100} ]; snew = Interpolation[Flatten[Table[{z,t,sn[k][z,t]}, {z,0,1,1/100}, {t,0,2,1/100}], 1], InterpolationOrder->7]; sn[k] = snew; Print[iteration , k]; Plot3D[sn[k][z,t], {z,0,1}, {t,0,2}], {k, 1, 15} ] One can test for convergence as below; it is apparently quite good. NIntegrate[Abs[sn[15][z,t]-sn[14][z,t]], {z,0,1}, {t,0,2}] A drawback to this method is that it appears to break down beyond n = 2. Possibly one simply needs a much better starting function for sn[0], I'm not sure. Below is another method that Michael Trott showed me. We expand in a set of basis functions in z, set up a system of ODEs in t, and solve them. I tried this using monomials in z for basis functions and ran into some trouble with the ODE solving, so I will show Michael's attempt using trig functions for the basis. Note that we now handle the desired case n=5; another advantage is that this is alot faster than the method above, though still not exactly blinding in speed. Michael used the interval {0,2} for z so as to achieve pointwise (not just L^2) convergence; otherwise there would be a sharp drop-off just before z=1 as all the trigs vanish there. In other words, the basis functions are of the form Sin[k/2*Pi] rather than Sin[k*Pi] for 1<=k<=deg. Cosines are excluded due to the vanishing condition at z=0. integrate[p_Plus, {z_, 0, 1}] := Integrate[#, {z, 0, 1}]& /@ p; integrate[p_, {z_, 0, 1}] := Integrate[p, {z, 0, 1}]; n = 5; deg = 6; vars[t_] = Map[#[t]&,Array[a,deg]]; zFuns = Sin[Range[deg] Pi/2 z]; sn[z_,t_] = vars[t].zFuns; eqs1 = 3*z*integrate[Expand[sn[w,t]^n*w],{w,0,1}] - sn[z,t]^n - D[sn[z,t],t]; eqs2 = integrate[Expand[eqs1 #], {z, 0, 1}]& /@ zFuns; iCs = integrate[Expand[(sn[z,0] - 3/2*z) #], {z, 0, 1}]& /@ zFuns; fulleqns = # == 0& /@ Join[eqs2, iCs]; nsd = NDSolve[fulleqns, vars[t], {t,0,2}, SolveDelayed->True]; Plot3D[Evaluate[sn[z,t] /. nsd[[1]]],{z,0,1},{t,0,2}]; an initializer for the iteration/interpolation method above in an attempt to refine the solution. Daniel Lichtblau Wolfram Research ==== On 8/23/02 at 12:25 AM, meshii@mech.fukui-u.ac.jp (Toshiyuki (Toshi) >NDSolve seems to have difficulties with solving integral equation. >n = 5; NDSolve[{D[[Sigma]norm[z, t], t] == >3*z*Integrate[[Sigma]norm[z, t]^n*z, {z, 0, 1}] - [Sigma]norm[z, >t]^n, [Sigma]norm[z, 0] == 1.5*z, [Sigma]norm[0, t] == >0}*[Sigma]norm[z, t], {z, 0.01, 1}, {t, 0.01, 2}] >Mathematica returns a message > >NDSolve::deql: The first argument must have both an equation and an > initial condition. A general solution to a differential equation includes a constant of integration. It isn't possible to arrive a numerical solution without providing sufficient information to determine this constant. Specifying the initial condition provides this information. Look at the examples using the help browser to see what NDSolve needs. ==== -----Original Message----- >a number of useful replies and thank all those who responded. >Today I have a >question that actually generated yesterday's question. I am using a new >subject heading to reflect the actual nature of the question. > >What is the best way in Mathematica to operate on some, but >not all, level >parts of an expression or subexpression? > >Suppose I have the following expression... > >expr = f1[a]f2[b]f3[c]f4[d]; > >and I want to do an operation, op, separately on f1[a]f3[c] >and f2[b]f4[d]. >The operation must be done on the given pairs and not on all >four factors at >once. One method is to use explicit exact substitution rules. > >expr /. f1[a]f3[c] :> op[f1[a]f3[c]] /. f2[b]f4[d] :> op[f2[b]f4[d]] >op[f1[a] f3[c]] op[f2[b] f4[d]] > >If a,b,c,d were long expressions, we might not want to type or >copy them in. >This raised my question of using named patterns. Hartmut Wolf >pointed out >that each factor must be named to create a match with flat >expressions. So >we could use... > >expr /. (a : f1[_])(b : f3[_])(c : f2[_])(d : f4[_]) :> op[a b]op[c d] >op[f1[a] f3[c]] op[f2[b] f4[d]] > >Andrzej Kozlowski suggested a method using Take, but using >Part works better >here, so we could use... > >expr /. a_ :> op[a[[{1, 3}]]]*op[a[[{2, 4}]]] >op[f1[a] f3[c]] op[f2[b] f4[d]] > >All of the above methods use rules. Is it possible to do it with >ReplacePart? I don't think so, but maybe somebody knows how to >do it. How >about using MapAt? I don't think that works either in regular >Mathematica. >Ted Ersek and I did a package, Algebra`ExpressionManipulation` >at my web >site, that implements extended positions. An extended position >gives the >position of an expression and a list of the desired subparts >and is packaged >in a header eP. So the extended position of a + c in >f[a + b + c + d] is eP[{1},{1,3}]. The package modifies MapAt to accept >extended positions. Then we can use... > >MapAt[op, expr, {eP[{}, {1, 3}], eP[{}, {2, 4}]}] >op[f1[a] f3[c]] op[f2[b] f4[d]] > >However, I don't always like to drag in the package just to do >that. I think >that operating on selected level parts of a subexpression is >not all that >uncommon. > >Here is another example. 1 - Cos[x]^2 >% // TrigFactor >1 - Cos[x]^2 >Sin[x]^2 > >But... 1 - a - Cos[x]^2 >% // TrigFactor >1 - a - Cos[x]^2 >(1/2)*(1 - 2*a - Cos[2*x]) > >I was hoping for -a + Sin[x]^2. What are the best methods for >handling this >kind of problem in regular Mathematica? > >David Park >djmp@earthlink.net >http://home.earthlink.net/~djmp/ > >David Park >djmp@earthlink.net >http://home.earthlink.net/~djmp/ > Dear David, it's possible that I miss something..., but look at In[6]:= 1 - a - Cos[x]^2 /. {1 - Cos[x_]^2 :> Sin[x]^2} Out[6]= -a + Sin[x]^2 I don't know what TrigFactor is doing exactly (or intended to do), its answer might well be consistent with that. if... In[7]:= expr = f1[a]f2[b]f3[c]f4[d] ...whats wrong with.. In[8]:= op[#[[{1, 3}]]]op[#[[{2, 4}]]]Take[expr, {5, -1}] &[expr] Out[8]= op[f1[a] f3[c]] op[f2[b] f4[d]] ...? The problem with this of course is, that you must know the Sequence of the elements of the expression in advance (at programming time). The following needs not, uses extract and rebuilds the expression (it is assumed the f are at level {1}, this must be checked, not well done here, just to pass the idea): In[7]:= betteropat[ee : head_[__], {e1_, e3_}, {e2_, e4_}, op_] /; (len = Length[ee]) >= 4 := Module[{pos13 = Position[ee, e1[___] | e3[___], {1}], pos24 = Position[ee, e2[___] | e4[___], {1}], posr}, posr = List /@ Complement[Range[len], Flatten[{pos13, pos24}]]; head @@ Join[{op[head @@ Extract[ee, pos13]]}, {op[ head @@ Extract[ee, pos24]]}, Extract[ee, posr]] ] In[8]:= betteropat[expr, {f1, f3}, {f2, f4}, ox] Out[8]= ox[f1[a] f3[c]] ox[f2[b] f4[d]] In[9]:= betteropat[[Alpha] f1[a]f4[b][Beta] f2[c]f3[d], {f1, f3}, {f2, f4}, ox] Out[9]= [Alpha] [Beta] ox[f1[a] f3[d]] ox[f2[c] f4[b]] If you don't need all of this functionality, just reduce. -- Hartmut ___________________ Addendum: Here two other solutions, one using Part, the other ReplacePart + Replace: is not possible, since you _must_ reorder your data, not applying a function at parts of it). Here now another, simpler opat version (using Part, instead of Extract): In[19]:= mapopat[ee : head_[__], {e1_, e3_}, {e2_, e4_}, op_] /; (len = Length[ee]) >= 4 := Block[{pos13 = Flatten[Position[ee, e1[___] | e3[___], {1}]], pos24 = Flatten[Position[ee, e2[___] | e4[___], {1}]], posr}, posr = Complement[Range[len], pos13, pos24]; head[op[ee[[pos13]]], op[ee[[pos24]]], ee[[posr]]] ] Of course this all is most senseful only for heads with Flat attribute. In[20]:= mapopat[expr, {f4, f2}, {f1, f3}, ox] Out[20]= ox[f1[a] f3[c]] ox[f2[b] f4[d]] In[23]:= mapopat[[Alpha] f1[a]f4[b][Beta] f2[c]f3[d], {f1, f3}, {f2, f4}, ox] Out[23]= [Alpha] [Beta] ox[f1[a] f3[d]] ox[f2[c] f4[b]] In[22]:= mapopat[h[f1[a], f4[b], f2[c], f3[d]], {f1, f3}, {f2, f4}, ox] Out[22]= h[ox[h[f1[a], f3[d]]], ox[h[f4[b], f2[c]]], h[]] finally another version using ReplacePart; not all ReplacePart though, but in that spirit: In[99]:= expr = f1[a]f2[b]f3[c]f4[d] In[100]:= rplopat[ee : head_[__], {e1_, e3_}, {e2_, e4_}, op_] /; (len = Length[ee]) >= 4 := Block[{head}, Module[{ pos = Join @@ (Position[ee, #, {1}] &) /@ Through[{e1, e3, e2, e4}[___]], posr, allpos = List /@ Range[len], rr}, posr = Complement[allpos, pos]; rr = ReplacePart[ee, ee, allpos, Join[pos, posr]]; Replace[rr, head[a_, b_, c_, d_, r___] :> head[op[head[a, b]], op[head[c, d]], head[r]]] ]] Blocking head prevents reordering (of rr) in case head has the Orderless attribute. In[101]:= rplopat[expr, {f4, f2}, {f1, f3}, ox] Out[101]= ox[f1[a] f3[c]] ox[f2[b] f4[d]] In[103]:= rplopat[[Alpha] f1[a]f4[b][Beta] f2[c]f3[d], {f1, f3}, {f2, f4}, ox] Out[103]= [Alpha] [Beta] ox[f1[a] f3[d]] ox[f2[c] f4[b]] In[104]:= rplopat[h[f1[a], f4[b], f2[c], f3[d]], {f1, f3}, {f2, f4}, ox] Out[104]= h[ox[h[f1[a], f3[d]]], ox[h[f2[c], f4[b]]], h[]] -- Hartmut ==== > >I need FrameLabels of the kind of H^s_z / H^p_Z and tried something >like > >FrameLabel->{FontForm{HSuperscript[s]Subscript[z] ...}} > >but s is too far away from z. How can I manage it that s is >directly above z ? Are there some backspace-characters to be used? > >Harry Subsuperscript[H, s, z] -Dale ==== >I would expect that > >Plot[Sin[x]/Sin[x], {x, -2.5, -1.5}] > >would produce a horizontal line at y=1. > >However, on my Windows XP computer it produces a graph where the y value is >less than 1 at several points. Most notibly between x=-1.6 and x=-1.8 > >Is this just an isolated case? Or does it happen to others? If so - why? > >Ken. The y axis has a very narrow range. The differences are very small. To see that, you can pull out the tick marks. In[13]:= yticks=FullOptions[gr,Ticks][[2]] In[15]:= InputForm[First/@yticks] Out[15]//InputForm= {0.9999999999999981, 0.9999999999999991, 1., 1.000000000000001, 1.000000000000002, 0.9999999999999983, 0.9999999999999986, 0.9999999999999987, 0.9999999999999989, 0.9999999999999993, 0.9999999999999996, 0.9999999999999997, 0.9999999999999999, 1.0000000000000002, 1.0000000000000004, 1.0000000000000007, 1.0000000000000009, 1.0000000000000013, 1.0000000000000016, 1.0000000000000018, 1.000000000000002, 0.9999999999999979, 0.9999999999999977, 1.0000000000000022} The ragged shape is caused by roundoff error, if you increase the PlotRange of the y-axis you see what you expect. gr = Plot[Sin[x]/Sin[x], {x, -2.5, -1.5}, PlotRange -> {0, 2}] -Dale ==== Harald, You could try something like this... Plot[x, {x, 0, 1}, Frame -> True, FrameLabel -> {z, DisplayForm[