A56 == I want to get some F and R such that:> F[n,p] + R[n,p] = Sum[Binomial[n,k] p^(n-k) (1-p)^k, {k, 0, Floor[n/2] - 1}],> when F[n,p] is an approximation to the sum and the R is the remaining error.> Constantine.>>I'm looking for a way of finding the approximation for partitial binomialÓ>>sum.>>I'll be pleasant for any hint..> [...]> Office: Taub 411ÓYou can get a closed form in terms of special functions if you splitÓÓinto two cases depending on whether n is even or odd.ÓIn[39]:= n = 2*m;ÓIn[40]:= InputForm[Sum[Binomial[n,k]*p^(n-k)*(1-p)^k, {k,0,m-1}]]ÓOut[40]//InputForm= p^(2*m)*((p^(-1))^(2*m) - ((-4 + 4/p)^m*Gamma[1/2 + m]* Hypergeometric2F1[1, -m, 1 + m, (-1 + p)/p])/(Sqrt[Pi]*Gamma[1 +Óm]))ÓIn[41]:= n = 2*m+1;ÓIn[42]:= InputForm[Sum[Binomial[n,k]*p^(n-k)*(1-p)^k, {k,0,m-1}]]ÓOut[42]//InputForm= p^(1 + 2*m)*((p^(-1))^(1 + 2*m) - (2^(1 + 2*m)*(-1 + p^(-1))^m*Gamma[3/2+ m]* Hypergeometric2F1[1, -1 - m, 1 + m, (-1 + p)/p])/(Sqrt[Pi]*Gamma[2 +Óm]))ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== ÓI want to get some F and R such that:ÓF[n,p] + R[n,p] = Sum[Binomial[n,k] p^(n-k) (1-p)^k, {k, 0, Floor[n/2] - 1}],Ówhen F[n,p] is an approximation to the sum and the R is the remaining error.ÓConstantine.>>I'm looking for a way of finding the approximation for partitial binomial >>sum.>>I'll be pleasant for any hint..>Use the standard add-on package Statistics`NonlinearFit` to do a >NonlinearFit to whatever model you want to use for the approximation.>Bob HanlonÓ>Chantilly, VA USAÓÓConstantine ElsterÓÓComputer Science Dept.ÓTechnion I.I.T.ÓOffice: Taub 411 ==== ÓConstantine,ÓIf you break your problem up into two cases, even n and odd n, thenÓÓMathematica can sum up your problem and get results, albeit withÓÓhypergeometric functions. Consider the following (make sure you look at thisÓÓwith a fixed font):ÓIn[21]:=Óevenans = Sum[Binomial[2*n, k]*p^(2*n - k)*(1 - p)^k, {k, 0, n - 1}];ÓIn[22]:=ÓPowerExpand[FunctionExpand[FullS implify[evenans , n [Element] Integers]]]ÓOut[22]= 2 n n n 1 p - 1 2 (1 - p) p Gamma[n + -] Hypergeometric2F1[1, -n, n + 1, -----] 2 pÓ1 - ------------------------------------------------------------- ------- Sqrt[Pi] Gamma[n + 1]ÓIn[23]:=Óoddans = Sum[Binomial[2*n + 1, k]*p^(2*n + 1 - k)*(1 - p)^k, {k, 0, n - 1}];ÓIn[24]:=ÓPowerExpand[FunctionExpand[FullS implify[oddans , n [Element] Integers]]]ÓOut[24]= 2 n + 1 n n + 1 3Óp - 1 2 (1 - p) p Gamma[n + -] Hypergeometric2F1[1, -n - 1, n +1, -----] 2ÓpÓ1 - ------------------------------------------------------------ -------------------- Sqrt[Pi] Gamma[n + 2]ÓIs this what you were looking for?ÓCarl WollÓÓPhysics DeptÓÓU of WashingtonÓ> I want to get some F and R such that:>> F[n,p] + R[n,p] = Sum[Binomial[n,k] p^(n-k) (1-p)^k, {k, 0, Floor[n/2] -1}],> when F[n,p] is an approximation to the sum and the R is the remainingÓÓerror.>> Constantine.>>I'm looking for a way of finding the approximation for partitialÓÓbinomialÓ> >>sum.>>I'll be pleasant for any hint..>Use the standard add-on package Statistics`NonlinearFit` to do aÓ> >NonlinearFit to whatever model you want to use for the approximation.>Bob HanlonÓ>Chantilly, VA USAÓ>> Constantine ElsterÓ> Computer Science Dept.> Technion I.I.T.> Office: Taub 411>> ==== >I want to do these operations:>>eq = m x^2 + 2(m + 1)x + m + 2>l = {}>For[i = -30, i < 30, i++, AppendTo[l, eq /. m -> i]]>Plot[l, {x, -50, 50}]>>but i get this error:>l is not a machine-size real number at x = -49.99999583333334>>Can someone exaplain to me what i am doing wrong here??>Óeq = m x^2 + 2(m + 1)x + m + 2;Ól = {};ÓFor[i = -30, i < 30, i++, AppendTo[l, eq /. m -> i]];ÓIt would be more straightforward and efficient to define the list using TableÓÓl == Table[eq, {m, -30, 29}]ÓTrueÓÓTo Plot, use EvaluateÓÓPlot[Evaluate[l], {x, -50, 50}];ÓBob HanlonÓ ==== >What is a efficient way to use output expression to define new function.ÓUse the menu command Input/Copy Output from AboveÓÓor use % (Out)ÓBob HanlonÓ ==== >-----Original Message----->Sent: Wednesday, September 04, 2002 8:57 AMÓ>The problem is that I do not think there is any bounded 3d body >described by your conditions. Anyway, this is how you can use >Mathematica (in general) to solve this sort of problem.>You need two packages:>>In[1]:=><>In[2]:=><< Calculus`Integration`>To see your object use:>InequalityPlot3D[y > 3x && y < 4 - x^2 && z < x^2 + 4, {x}, {y}, {z}]>>However, you will just get some error messages and a picture >that looks >two dimensional. If you wanted the volume, evaluate:>>In[3]:=>Integrate[Boole[y>3x&&y<4-x^2&&z>Out[3]=>-InfinityÓ>>If you impose some limits on z you will get a finite positive answer, >but one that clearly is unbounded:>>In[20]:=>NIntegrate[Boole[y>3x&&y<4-x^2&&z>Out[20]=>2239.58>>In[21]:=>NIntegrate[ Boole[y>3x&&y<4-x^2&&z>Out[21 ]=>20989.6>>AndrzejÓ>> Sorry, I must have something missing in my previous description.>> I need to find out the volumn of a 3D object which form by the >> equation :>> z=x^2 +4 (as bottom surface)>> and on the xy plane which bounded by a parabola y=4-x^2 and >y=3x line.>> How would I use Mathematica to plot out this 3D object or >find out its >> volumn with only the equation given?>> Shz ShzÓ> Andrzej Kozlowski 3/September/2002 04:33pm > Mathematica could do this sort of thing if there were a threeÓ>> dimensional object described by your equations (as boundaries) butÓ>> there isn't one. More precisely, the pair of equations {z=x^2 +4,>> y=4-x^2} describes a parabola in three space which you can >plot with:>> g1=ParametricPlot3D[{x, 4 - x^2, x^2 + 4}, {x, -5, 5}]>> The equation y=3x describes the plane:>> g2 = ParametricPlot3D[{x, 3x, z}, {x, -5, 5}, {z, -25, 25}]>> You can see the two together inÓ>> <> Show[{g1,g2}]>> There are clearly two points of intersection. They can be found with:>> Solve[{z == x^2 + 4, y == 4 - x^2, y == 3*x}, {x, y, z}]>> {{z -> 5, y -> 3, x -> 1}, {z -> 20, y -> -12, x -> -4}}>> So where is the 3D object whose volume you want to find?>> Andrzej KozlowskiÓ>> Toyama International UniversityÓ>> JAPANÓ>> Can I use Mathematica to find out the volumn of this 3 dimensionalÓ> object fromÓ> the equations :>> z=x^2 +4, y=4-x^2, y=3xÓ> Shz ShzÓ> >ÓShz Shz,Óas Andrzej having said everything about the calculation of the volume, andÓÓas still your specification is incomplete, I'm going to show how you canÓÓplot at least all you have (communicated).ÓAs you said something obout the Óbottom -- which direction is Óup? --Óassuming positive z-direction the I come to the inequalities: y >= 3 x, y <= 4 -x^2, z >= 4 + x^2Óand arbitrarily, to make the example complete I'll show only parts with z < 20Óbut do not complete the shape.ÓTo begin building the graphics we draw the boundary surfaces:[1] the bottomÓ{xmin, xmax} = x /. NSolve[4 - x^2 == 3x, {x}]{-4., 1.}ÓPlot[{4 - x^2, 3x}, {x, xmin, xmax}]{ymin, ymax} = {3 xmin, 4}Óg3 = Graphics3D[Plot3D[x^2 + 4, {x, xmin, xmax}, {y, ymin, ymax}]][2] the wallsÓÓg = ParametricPlot3D[{{x, 4 - x^2, z}, {x, 3x, z}}, {x, xmin, xmax}, {z, 0, 20}]ÓOne idea now would be to exploit the Mathematica rendering algorithm, to cutÓÓoff the undesired parts of the boundary surfaces:Ógg = Show[g3, g, PolygonIntersections -> False][Epsilon] = 1. 10^-4Óg4 = gg /. Line[_] -> {} /. p : Polygon[pts_] :> If[Or @@ (#2 > 4 - #1^2 + [Epsilon] || #2 < 3 #1 - [Epsilon] || #3 < #1^2 + 4 - [Epsilon] &) @@@ pts, {}, p]ÓShow[g4 /. Line[_] -> {}, BoxRatios -> {1, 1, .5}, ViewPoint -> {1.3, -2.4, 5}]ÓBut alas! The edges are rather gnawed off. Increasing epsilon doesn't help,Óunwanted parts will show up and still some polygons are nibbled away.ÓSo we have to do it ourselves:ÓWe defineÓÓtag[inequality_][p_] := Block[{x, y, z}, {x, y, z} = p; If[inequality, {p, inside}, {p, outside}]]...tags points whether inside ore outside.Ósol[equality_, {p1_, _}, {p2_, _}] := Block[{p, d, x, y, z}, {x, y, z} = p = p1 (1 - d) + p2 d; First[Cases[Solve[equality, d], s_ /; NonNegative[d /. s] :> (p /. s)]] ]...computes the cut on the line between to points of opposite sides.Ósep[equality_][pp1_, pp2_] := If[pp1[[2]] === pp2[[2]], {pp1}, ppx = sol[equality, pp1, pp2]; {pp1, {ppx, pp1[[2]]}, {ppx, pp2[[2]]}}]...effectively cuts a segment crossing the border into two pieces.ÓcutGraphics3D[g_, inequality_] := Module[{equality = Equal @@ inequality}, g /. Polygon[pts_] :> Block[{tagpts = tag[inequality] /@ pts}, With[{t = sep[equality] @@@ Transpose[{tagpts, RotateLeft[tagpts]}]}, With[{newpts = Cases[t, {p_, label_} /; label == inside :> p,2]}, If[Length[newpts] > 2, Polygon[newpts], {}]] ]]]...Polygons crossing a border are cut, only those inside are kept.ÓWe first cut the bottom...Óg3new = Fold[cutGraphics3D, g3, {y >= 3x, y <= 4 - x^2}]...next the sides...Ógnew = cutGraphics3D[g, z >= 4 + x^2]...and display:ÓShow[gnew, g3new, BoxRatios -> {1, 1, .5}, ViewPoint -> {1.3, -2.4, 5}]ÓShow[gnew, g3new, BoxRatios -> {1, 1, .5}, ViewPoint -> {1.3, -2.4, 15}]ÓShow[gnew, g3new, BoxRatios -> {1, 1, .5}, ViewPoint -> {1.3, -2.4, -2}]ÓShow[gnew, g3new, BoxRatios -> {1, 1, .5}, ViewPoint -> {1.3, 2.5, 2}]ÓHere I have brought a method, I had already posted twice, to a more handyÓÓform.ÓTo make that reminiscence complete, we could also define a coloring functionÓÓcolorGraphics3D[g_, inequality_, colorinside_, coloroutside_] := Module[{equality = Equal @@ inequality}, g /. Polygon[pts_] :> Block[{tagpts = tag[inequality] /@ pts}, With[{t = sep[equality] @@@ Transpose[{tagpts, RotateLeft[tagpts]}]}, {With[{newpts = Cases[t, {p_, label_} /; label == outside :> p, 2]}, If[Length[newpts] > 2,{FaceForm[SurfaceColor[coloroutside]], Polygon[newpts]}, {}]], With[{newpts = Cases[t, {p_, label_} /; label == inside :> p, 2]}, If[Length[newpts] > 2, {FaceForm[SurfaceColor[colorinside]], Polygon[newpts]}, {}]]} ]]]Óand with...Óg3D = Graphics3D[Plot3D[E^(-(x^2/2) - y^2/2)/(2*Pi) , {x, -2, 2}, {y, -2,2}]]ÓShow[colorGraphics3D[g3D, With[{e = Take[{x, y, z}, 2] - {0.8, -0.5}}, e.e] <= 1, Hue[0, 0.3, 1], Hue[0.6, 0.3, 1]]]--ÓHartmut WolfÓ ==== ÓThis result seems to me to be wrong (it's right?):ÓIn[1]:=ÓIntegrate[Sqrt[a^2*Cos[t]^2 + b^2*Sin[t]^2], {t, 0, 2*Pi}, Assumptions->{Im[a]==0, Im[b]==0}]ÓOut[1]=0....but written in another way, it's right:ÓIn[2]:=ÓIntegrate[Sqrt[a^2 + (b^2 - a^2)*Sin[t]^2], {t, 0, 2*Pi}, Assumptions -> {Im[a] == 0, Im[b] == 0}]ÓOut[2]=ÓIf[a^2/(-a^2 + b^2) >= 0 || b^2/(-a^2 + b^2) <= 0 || Im[a^2/(-a^2 + b^2)] != 0, (4*a^2*Sqrt[-1 + b^2/a^2]*EllipticE[ 1 - b^2/a^2])/Sqrt[-a^2 + b^2], Integrate[Sqrt[a^2 + (-a^2 + b^2)*Sin[t]^2], {t, 0, 2*Pi}]]ÓSomeone can explane me this difference?ÓRaf. ==== Óinvolved Bessel equationsÓ(electro-magnetic field in coaxial) but when I initialize and calculate thatÓ2 eqs for the 2nd or 3rd time, Ôcause I changed some parameters, I see aÓÓstrange ÓRemoved[n] instead of the value of Ón (=0).ÓI use the lineÓ Remove[ÓGlobal`*];Óat the beginning to clear any variable and I think it could be the problem.ÓSo, have I always to quit and restart the program in order to recalculateÓÓthat equations?ÓFilippo SolaÓ ==== ÓCan someone provide me more information on how ListIntegrate worksÓÓthan what is contained in the version 4 manual ? Is there a websiteÓÓperhaps or tutorial ?ÓI would like to know how the beginning and end of a list of {x,y}Ópairs that is being integrated is dealt with by ListIntegrate.ÓI know a series of polynomials is somehow used but how ? Do theseÓÓoverlap ? Are they piecewise continuous ?ÓAre these polynomials available for inspection ? How do they change asÓÓa function of Ók ?Óoptimum Ók value for a given list ? For any given list, will accuracyÓÓmonotonically increase with increasing values of Ók ? Is thereÓÓanything in the Option Inspector that could cause unexpected behaivorÓÓwith ListIntegrate ?ÓAre there any good rules of thumb or procedures that will help ensureÓÓa reasonable answer is produced ?ÓIs there a way of estimating the error or accuracy of integrationÓÓperformed by ListIntegrate ? ==== ÓBe sure to note the following and what comes after it near the end of the Help Browser info on ListIntegrate:``This package has been included for compatibility with previous versions of Mathematica. The functionality of this package has been superseded by improvements made to InterpolatingFunction.ÓIn other words, ListIntegrate is a dinosaur that you don't need at all!ÓTo integrate a list of data with Mathematica, one can proceed in either of two ways: (1) Construct an interpolating function and use NIntegrate (or, better, NIntegrateInterpolatingFunction) on that (which is what ListIntegrate apparently does); or (2) apply a simple routine that implements the trapezoidal rule, Simpson's rule, or maybe some higher order method.ÓAssuming you've chosen to take path #1, you need to realize the following:(a) NIntegrate[Interpolation[data, InterpolationOrder->1][x], {x,a,b}] is equivalent to the trapezoidal rule;(b) NIntegrate[Interpolation[data, InterpolationOrder->2][x], {x,a,b}] is *not* equivalent to Simpson's rule (because of the peculiar way that Interpolation works);(c) Interpolation[data, InterpolationOrder->k] generally does not return a smooth function unless you set InterpolationOrder->n-1, where n is the number of data points, which is the case where a single polynomial of degree n-1 fits the data points.(d) If you want to integrate a smooth interpolant, you can do this: <k][x], {x, 0, 5}, PlotRange -> All], {k, 1, 6}](The last of those plots will give a warning message.)ÓHaving said all that, you really should consider path #2 instead. Here are a couple of links to a MathGroup discussion of last July (somehow the thread got split up):Óhttp://library.wolfram.com/mathgroup/archive/2002/Jul/ msg00490.htmlÓÓhttp://library.wolfram.com/math group/archive/ 2002/Jul/msg00519.htmlÓÓI hope all this helps some.----ÓSelwyn HollisÓ > Can someone provide me more information on how ListIntegrate worksÓ > than what is contained in the version 4 manual ? Is there a websiteÓ > perhaps or tutorial ? > I would like to know how the beginning and end of a list of {x,y} > pairs that is being integrated is dealt with by ListIntegrate. > I know a series of polynomials is somehow used but how ? Do theseÓ > overlap ? Are they piecewise continuous ? > Are these polynomials available for inspection ? How do they change asÓ > a function of Ók ? > optimum Ók value for a given list ? For any given list, will accuracyÓ > monotonically increase with increasing values of Ók ? Is thereÓ > anything in the Option Inspector that could cause unexpected behaivorÓ > with ListIntegrate ? > Are there any good rules of thumb or procedures that will help ensureÓ > a reasonable answer is produced ? > Is there a way of estimating the error or accuracy of integrationÓ > performed by ListIntegrate ? > > ==== ÓI timed Daniel's three solutions and Gary's one (plus a couple of my ownÓÓa little later):Óperps1[v_] := If[v[[1]] == v[[2]] == 0, {{1, 0, 0}, {0, 1, 0}}, {{v[[2]], -v[[ 1]], 0}, Cross[v, {v[[2]], -v[[1]], 0}]}]Óperps2[v_] := With[{vecs = NullSpace[{v}]}, {vecs[[ 1]], vecs[[2]] - (vecs[[2]].vecs[[1]])*vecs[[1]]}]Óperps2C = Compile[{{v, _Real, 1}}, Module[{vecs = NullSpace[{v}]}, { vecs[[1]], vecs[[2]] - (vecs[[2]].vecs[[1]])*vecs[[1]]}]]Óhelzer[v : {a1_, a2_, a3_}] := With[{w = First[Sort[{{a2, -a1, 0}, {a3, 0, -a1}, {0, a3, -a2}}, OrderedQ[{Plus @@ Abs[#2], Plus @@ ÓAbs[#1]}] &]]}, {w, Cross[v, w]}]Óvecs = Table[Random[], {10000}, {3}]; Timing[perps1 /@ vecs; ]ÓTiming[perps2 /@ vecs; ]ÓTiming[perps2c /@ vecs; ]ÓTiming[helzer /@ vecs; ]{1.7350000000000012*Second, Null}{0.5619999999999994*Second, Null}{0.219 Second, Null}{2.7349999999999994*Second, Null}ÓI made a small change to Daniel's perps1, and got a solution as fast asÓÓperps2c, WITHOUT compiling. Compiling tripled the speed again, soÓÓtreatC is the fastest solution I've seen so far.Ótreat[{a_, b_, c_}] := If[a == b == 0, {{1, 0, 0}, {0, 1, 0}}, {{b, -a, 0}, {a*c, b*c, -a^2 -Ób^2}}]ÓtreatC = Compile[{{v, _Real, 1}}, If[v[[1]] == v[[2]] == 0, {{1, 0, 0}, {0, 1, 0}}, {{v[[2]], -v[[1]], 0}, {v[[1]]*v[[3]], v[[2]]*v[[3]], -v[[1]]^2 - v[[2]]^2}}]]Óvecs = Table[Random[], {10000}, {3}]; Timing[perps2c /@ vecs; ]ÓTiming[helzer /@ vecs; ]ÓTiming[treat /@ vecs; ]ÓTiming[treatC /@ vecs;]{0.2190000000000083*Second, Null}{2.7339999999999947*Second, Null}{0.25*Second, Null}{0.07800000000000296*Second, Null}ÓNone of these solutions reliably return normalized vectors.ÓBobby TreatÓ-----Original Message-----> pose the problem to MathGroup. Who has the most elegant MathematicaÓ> routine...> > OrthogonalUnitVectors::usage = ÓOrthogonalUnitVectors[v:{_,_,_}] willÓÓreturnÓ> two unit vectors orthogonal to each other and to v.> You can assume that v is nonzero.> David ParkÓ> djmp@earthlink.netÓ> http://home.earthlink.net/~djmp/ÓSome possibilities:Óperps1[v_] := If [v[[1]]==v[[2]]==0, {{1,0,0},{0,1,0}}, {{v[[2]],-v[[1]],0}, Cross[v,{v[[2]],-v[[1]],0}]} ]Óperps2[v_] := With[{vecs=NullSpace[{v}]}, {vecs[[1]], vecs[[2]] - (vecs[[2]].vecs[[1]])*vecs[[1]]} ]ÓThis appears to be 2-3 times faster than perps1 for vectors of machineÓÓreals. I get another factor of 2 using Compile, which is appropriate forÓÓe.g. graphics use.Óperps2C = Compile[{{v,_Real,1}}, Module[{vecs=NullSpace[{v}]}, {vecs[[1]], vecs[[2]] - (vecs[[2]].vecs[[1]])*vecs[[1]]} ]]ÓIn[61]:= vecs = Table[Random[], {10000}, {3}];ÓIn[62]:= Timing[p2 = Map[perps1C,vecs];]ÓOut[62]= {0.49 Second, Null}ÓThis is on a 1.5 GHz processor.ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== >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ÓÓIn 4.2, the following should work (as long as you define newsize).Óin = Import[Ófile.jpg];ÓExport[[Capit alOAcute]newfile.jpg, in, ImageSize->newsize]ÓIn 4.1 and earlier, this will not work because an optimization interferes with the ImageSize and rasters are written out with the raster size, not the ImageSize. There is a ConversionOption to force the behavior you want.Óin = Import[Ófile.jpg];ÓExport[[Capita lOAcute]newfile.jpg, Show[in, ImageSize->newsize], ConversionOptions->{ÓRasterExport->Graphics}]-Dale[CapitalOA cute] ==== Ó Borrowing liberally from Daniel, I like the following:ÓClearAll[sumBin, sumBinOdd, sumBinEven, index]ÓsumBinOdd = Sum[Binomial[2index + 1, k]*p^(2index + 1 - k)*(1 - p)^k, { k, 0, index - 1}];ÓsumBinEven = Sum[Binomial[2index, k]* p^(2index - k)*(1 - p)^k, {k, 0, index - 1}];ÓsumBin[n_, Odd] = sumBinOdd /. {index -> (n - 1)/2};ÓsumBin[n_, Even] = sumBinEven /. {index -> n/2};ÓsumBin[n_?EvenQ] = sumBin[n, Even];ÓsumBin[n_?OddQ] = sumBin[n, Odd];ÓIt allows you to see the solution symbolically for both odd and even n,Óand also to calculate it when n is a known integer. We also have theÓÓopportunity, for instance, to assume that 3x is even and calculateÓÓsumBin[3x, Even]Óp^(3*x)*((1/p)^(3*x) - ((-4 + 4/p)^((3*x)/2)* Gamma[1/2 + (3*x)/2]*Hypergeometric2F1[1, -((3*x)/2), 1 + (3*x)/2, (-1 + p)/p])/(Sqrt[Pi]*Gamma[1 +(3*x)/2]))Óor assume 3x is odd and calculateÓÓsumBin[3*x, Odd]Óp^(3*x)*((1/p)^(3*x) - (2^(3*x)*(-1 + 1/p)^((1/2)*(-1 + 3*x))* Gamma[3/2 + (1/2)*(-1 + 3*x)]*Hypergeometric2F1[1, -1 + (1/2)*(1 - 3*x), 1 + (1/2)*(-1 + 3*x), (-1 +Óp)/p])/(Sqrt[Pi]* Gamma[2 + (1/2)*(-1 + 3*x)]))ÓBobby TreatÓ-----Original Message-----> when F[n,p] is an approximation to the sum and the R is the remainingÓÓerror.> > Constantine.>In a message dated 8/28/02 4:44:13 AM, celster@cs.technion.ac.ilÓ>>I'm looking for a way of finding the approximation for partitialÓÓbinomialÓ>>sum.> >>I'll be pleasant for any hint..> [...]> Office: Taub 411ÓYou can get a closed form in terms of special functions if you splitÓÓinto two cases depending on whether n is even or odd.ÓIn[39]:= n = 2*m;ÓIn[40]:= InputForm[Sum[Binomial[n,k]*p^(n-k)*(1-p)^k, {k,0,m-1}]]ÓOut[40]//InputForm= p^(2*m)*((p^(-1))^(2*m) - ((-4 + 4/p)^m*Gamma[1/2 + m]* Hypergeometric2F1[1, -m, 1 + m, (-1 + p)/p])/(Sqrt[Pi]*Gamma[1 +Óm]))ÓIn[41]:= n = 2*m+1;ÓIn[42]:= InputForm[Sum[Binomial[n,k]*p^(n-k)*(1-p)^k, {k,0,m-1}]]ÓOut[42]//InputForm= p^(1 + 2*m)*((p^(-1))^(1 + 2*m) - (2^(1 + 2*m)*(-1 + p^(-1))^m*Gamma[3/2+ m]* Hypergeometric2F1[1, -1 - m, 1 + m, (-1 + p)/p])/(Sqrt[Pi]*Gamma[2 +Óm]))ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== ÓI've found that Mathematica 4.2 takes too long to finish to generate firstÓÓtime help browser. Is this normal? How many time should it take?ÓCalimeroÓ ==== ÓPlease excuse me if this has been discussed before; I haven't been monitoring the group very much.ÓA long time ago I posted to this group as well as to Wolfram about the errors in many or all functions involving Fourier transforms when values of FourierParameters other than the default values are used. The group responded that indeed there was a problem so I'm wondering if it was ever fixed. My version (then and now) is 4.0.1 for Macintosh.ÓJerryÓ ==== ÓCould you help me?ÓI'm to solve heat conductivity equation (Laplas equation) - partial differential equation. Are there any ready-to-use packages that will help me do the job?ÓStandard function ÓDSolve cannot! And so do functions from package ÓCalculus`DSolveIntegrals`.ÓMore info: the space where the equation is to be solved is cylindre (not infinite). Andrew. ==== When I multiply an expression with 0 it is giving 0.expression whichÓÓis creating problem in the further calculation.Óeg.ÓIn[1]:=func1[r_]:=Exp[-r/2][ CapitalOAcute]In[2]:coeff[[1,1 ]]=0.0;;;ÓIn[34]:=func1[r]coeff[[1,1]]ÓOut[34] :=0.Exp[-r/2]ÓI want anything to be multiply by zero must be zero. How can I do that? Your suggestion will be highly appreciated. RajÓ ==== > When I multiply an expression with 0 it is giving 0.expression whichÓ> is creating problem in the further calculation.ÓNo. Your trouble comes when you multiply an expression by theÓÓßoating-point number 0.0, rather than by the precise symbolic 0 (having noÓÓdecimal point). Merely make the coefficient 0 (rather than 0.0) andÓÓeverything should work as you wish.ÓDavidÓ> eg.>> In[1]:=func1[r_]:=Exp[-r/2]> In[2]:coeff[[1,1]]=0.0;> ;> ;> In[34]:=func1[r]coeff[[1,1]]>> Out[34]:=0.Exp[-r/2]>> I want anything to be multiply by zero must be zero.>> How can I do that?-- -------------------- http://NewsReader.Com/ -------------------- Usenet Newsgroup ServiceÓÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== ÓUnprotect[Times]ÓTimes[0 ., __] := 0ÓProtect[Times] JensÓ> When I multiply an expression with 0 it is giving 0.expression whichÓ> is creating problem in the further calculation.> eg.> In[1]:=func1[r_]:=Exp[-r/2]> In[2]:coeff[[1,1]]=0.0;> ;> ;> In[34]:=func1[r]coeff[[1,1]]> Out[34]:=0.Exp[-r/2]> I want anything to be multiply by zero must be zero.> How can I do that?> Your suggestion will be highly appreciated.> RajÓ ==== ÓNow I'm trying to calculate this formula:ÓDelta[eq_, x_]:=Coefficient[eq, x]^2 - 4 Coefficient[eq, x^2] Coefficient[eq, x^0]Óeq has this form a x^2 + b x + cÓÓBut there is a problem with the x^0 coefficient!ÓHow can I overcome that?ÓCeZaRÓÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== ÓandÓÓDelta[eq_, x_]:=Coefficient[eq, x]^2 - 4 Coefficient[eq, x,2]ÓCoefficient[eq, x,0]Ódoes what you want. Because the Help-Browser say:ÓCoefficient[expr, form, 0] picks out terms that are not proportional toÓÓform. JensÓ> Now I'm trying to calculate this formula:> Delta[eq_, x_]:=Coefficient[eq, x]^2 - 4 Coefficient[eq, x^2] Coefficient[eq, x^0]> eq has this form a x^2 + b x + cÓ> But there is a problem with the x^0 coefficient!> How can I overcome that?> CeZaRÓ ==== ÓI need to fill the space between two contour lines, C1 and C2, withÓÓred color, and leave the other place white. What trick I have to use?ÓAny suggestion and advice will be appreciated.ÓJun LinÓÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== Ógr = ContourPlot[x^2 + y^2, {x, -1, 1}, {y, -1, 1}, Contours -> {0.2, 0.4}, ColorFunction -> (If[# >= 0.2 && # <= 0.4, RGBColor[1, 0, 0], RGBColor[1, 1, 1]] &), ColorFunctionScaling -> FalseÓ ] JensÓ> > I need to fill the space between two contour lines, C1 and C2, withÓ> red color, and leave the other place white. What trick I have to use?> Any suggestion and advice will be appreciated.> Jun LinÓ ==== ÓI am trying to find an example that will demonstrate the difference betweenÓ$PrePrint and $Post. I found an old thread in this news group where aÓÓuser wanted to display all matrices using MatrixForm. Some users suggestedÓÓthe following: In[1]:= $Post=(#/.mtrx_?MatrixQ:>MatrixForm[mtrx]&);ÓThen Dave Withoff said it's better to assign this to $PrePrint since theÓÓobjective here is to adjust the display rather than the result of theÓÓcalculation. With the assignment to $Post you could, for example, getÓÓunexpected results from calculations using %, since matrices will be wrappedÓÓin MatrixForm.--------ÓHowever, if we use $Post above, the next input will compute the inverseÓÓthe matrix. I did verify that Inverse can't take a matrix wrapped inÓÓMatrixForm. Can somebody give an example where doing this with $PrePrintÓÓinstead of $Post gives a different result. In[2]:= m={{2,3},{0,1}}; Inverse[%] Out[3]= (* Inverse of (m) in MatrixForm, not shown. *)------ Ted ErsekÓ Get Mathematica tips, tricks fromÓ http://www.verbeia.com/mathematica/tips/Tricks.htmlÓ[Capital OAcute]Reply-To : kuska@informatik.uni-leipzig.deÓ ==== Óyo can just tryÓÓIn[]:=$Post = (# /. mtrx_?MatrixQ :> AnyHead[mtrx] &);ÓIn[]:=m = {{2, 3}, {0, 1}}ÓIn[]:=q=%;ÓIn[]:=Head[q]Óan dÓÓIn[]:=$PrePost = (# /. mtrx_?MatrixQ :> AnyHead[mtrx] &);ÓIn[]:=m = {{2, 3}, {0, 1}}ÓIn[]:=q=%;ÓIn[]:=Head[q]ÓBu t you are right -- the behaviour of MatrixForm[] in your exampleÓÓis strange. JensÓ> > I am trying to find an example that will demonstrate the difference betweenÓ> $PrePrint and $Post. I found an old thread in this news group where aÓ> user wanted to display all matrices using MatrixForm. Some users suggestedÓ> the following:> In[1]:= $Post=(#/.mtrx_?MatrixQ:>MatrixForm[mtrx]&);> Then Dave Withoff said it's better to assign this to $PrePrint since theÓ> objective here is to adjust the display rather than the result of theÓ> calculation. With the assignment to $Post you could, for example, getÓ> unexpected results from calculations using %, since matrices will be wrappedÓ> in MatrixForm.> --------> However, if we use $Post above, the next input will compute the inverseÓ> the matrix. I did verify that Inverse can't take a matrix wrapped inÓ> MatrixForm. Can somebody give an example where doing this with $PrePrintÓ> instead of $Post gives a different result.> > In[2]:= m={{2,3},{0,1}};> Inverse[%]> Out[3]= (* Inverse of (m) in MatrixForm, not shown. *)> ------> Ted ErsekÓ> Get Mathematica tips, tricks fromÓ> http://www.verbeia.com/mathematica/tips/Tricks.htmlÓ ==== Ó myArray is a list of triplets which look like {n,k,p}, where n and kÓÓare integers and p is real number. repetitions in n and k are allowedÓÓbut no two triplets ar the same.ÓI define a function, myfunc[n_,pthreshold_] as follows.Ómyfunc[n_,pthreshold_] := Module[{t},Ót=Max[Cases[myArray, {n, k_, p_} /; (p >= pthreshold) -> p, 2]];ÓIf[t>=0,t,-1]]ÓIt prints the largest k for which p is greater than pthreshold for aÓÓgiven n andÓ-1 if there is no such k. The function does its job fine. My problem is as follows. I would like to plot a collection of plots,Ómyfunc[n,p], for 1<=n<=21 with respect to p. unfortunately theÓÓfollowing does not work as desired.ÓPlot[Table[myfunc[n,p],{n,1,21}],{p,0.0,1.0}] because the Table gets evaluated to numeric value (-1) before Plot isÓÓinvoked. ==== ÓI made a mistake in the definition of the question. The function is correctly defined as myfunc[n_,pthreshold_] := Module[{t}, t=Max[Cases[myArray, {n, k_, p_} /; (p >= pthreshold) -> k, 2]]; If[t>=0,t,-1]]ÓPlease note that inserting Evaluate before Table does not workÓÓcorrectly either, because evaluating myfunc[n,p] when p is not aÓÓnumber, gives -1.> Plot[Table[myfunc[n,p],{n,1,21}],{p,0.0,1.0}] > because the Table gets evaluated to numeric value (-1) before Plot isÓ> invoked.ÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== Ócould you supply a complete example next time ?ÓTry myfunc[] with a more restrictive pattern and it works:ÓmyArray = Flatten[Table[{n, 1, Random[]}, {15}, {n, 1, 21}], 1];Ómyfunc[n_, pthreshold_?NumericQ] := Module[{t}, t = Max[Cases[myArray, {n, k_, p_} /; (p >= pthreshold) -> p, 2]]; If[t >= 0, t, -1]]ÓPlot[Evaluate[Table[myfunc[n, p], {n, 1, 21}]], {p, 0.0, 1.0}] JensÓ> myArray is a list of triplets which look like {n,k,p}, where n and kÓ> are integers and p is real number. repetitions in n and k are allowedÓ> but no two triplets ar the same.> I define a function, myfunc[n_,pthreshold_] as follows.> myfunc[n_,pthreshold_] := Module[{t},> t=Max[Cases[myArray, {n, k_, p_} /; (p >= pthreshold) -> p, 2]];> If[t>=0,t,-1]]> > It prints the largest k for which p is greater than pthreshold for aÓ> given n andÓ> -1 if there is no such k. The function does its job fine.> My problem is as follows. I would like to plot a collection of plots,> myfunc[n,p], for 1<=n<=21 with respect to p. unfortunately theÓ> following does not work as desired.> Plot[Table[myfunc[n,p],{n,1,21}],{p,0.0,1.0}]> because the Table gets evaluated to numeric value (-1) before Plot isÓ> invoked. ==== ÓFor my PDE class we have been calculating Fourier transforms. The instructorÓÓarrived today with a printout of two plots of a certain Fourier transform,Ódone with a different CAS. The first plot was to 30 terms, the second was toÓ120 terms. Curious, I translated the functions into Mathematica (4.0 on Windows2000Óon a PIII 700) to see how much time this required to process. I wasÓÓStaggered at how much time it took. Here's the code:ÓL = 2;Óf[x_] := UnitStep[x - 1];Ób[n_] := (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];ÓFS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];ÓTiming[Plot[FS[30, x], {x, 0, 2}]]ÓOut[23]={419.713 Second, [SkeletonIndicator]Graphics[SkeletonIndicator]}ÓIn this case the number of terms is 30.ÓThe time required per number of terms seems to fit the following polynomial:Óy = 0.3926x^2 + 2.2379xÓÓThis is a large amount of time. I understand that the code is not optimized,Óand was more or less copied from the code in the other CAS, but is this aÓÓreasonable amount of time, or is something going wrong? I don't use MathematicaÓÓbecause of the speed, but should it be this slow?ÓJust curious,ÓSteve StoryÓ ==== > I don't use MathematicaÓ> because of the speed, but should it be this slow?ÓMathematica has become more competitive in the speed department in recentÓÓyears. See for example the attached comparison (not sent to newsgroup) byÓÓStephan Steinhaus (steinhaus-net.de). So when Mathematica takes a very longÓÓtime, you should investigate. In this case inserting Evaluate[] in twoÓÓplacesÓÓIn[9 1]:=b[n_] := Evaluate[(2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}]];....ÓIn[104]:=Timing[Plot[Evaluate[FS[120, x]], {x, 0, 2}]]ÓOut[104]={0.18 Second,[SkeletonIndicator]Graphics[SkeletonIndicator]}Ó speeds the process enormously (18 milliseconds to plot 120 terms on myÓÓfeeble old 500MHz PowerBook).ÓWhy was it so slow before? When I switch from an ordinary numerical languageÓÓto Mathematica, I enter into an implicit bargain withÓÓMathematica: the software will go the extra mile to get me a good answer,Óincluding (1) using exra precision (sometimes without being asked) and (2)Ócarrying around unevaluated mathematical expressions (usually without beingÓÓasked) that could possibly be evaluated more appropriately at a later time.ÓMost tools cannot do either of these things, so I don't have to worry aboutÓÓit, except for the bad answers that result now and then. But I need to takeÓÓcare that Mathematica does not burden itself unnecessarily. That's my sideÓÓof the bargain.ÓNumber (2) is the issue here. Your definition of b[n] is written so thatÓÓMathematica analytically evaluates b separately for each n. But you know inÓÓthis case that the integration can be done safely once for all n. So do it!ÓThe huge difference, though, comes from pre-evaluating the argument to Plot.ÓRead the on-line help! You should pre-evaluate where possible. In someÓÓcases, the most common of which involve branching within the definition ofÓÓfunction to plot, you cannot pre-evaluate so, in keeping with the bargain,ÓMathematica goes the extra mile and holds back just in case. You need toÓÓsteer it into the shortcut when it's OK.ÓHope this helps,ÓTom BurtonÓ-- Reply-To: kuska@informatik.uni-leipzig.deÓ ==== Ówith your code you compute the expansion coefficents everyÓÓtime when FS[] is evaluated. Store the values for b[n] withÓÓL = 2;Óf[x_] := UnitStep[x - 1];Ób[n_] := b[n] = (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];ÓFS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];ÓTiming[Plot[FS[30, x], {x, 0, 2}]]Óand you need only a 1-3 seconds (depending on your machine) JensÓ> For my PDE class we have been calculating Fourier transforms. The instructorÓ> arrived today with a printout of two plots of a certain Fourier transform,> done with a different CAS. The first plot was to 30 terms, the second was toÓ> 120 terms.> Curious, I translated the functions into Mathematica (4.0 on Windows2000> on a PIII 700) to see how much time this required to process. I wasÓ> Staggered at how much time it took. Here's the code:> L = 2;> f[x_] := UnitStep[x - 1];> b[n_] := (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];> FS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];> Timing[Plot[FS[30, x], {x, 0, 2}]]> Out[23]=> {419.713 Second, [SkeletonIndicator]Graphics[SkeletonIndicator]}> In this case the number of terms is 30.> The time required per number of terms seems to fit the following polynomial:> y = 0.3926x^2 + 2.2379xÓ> This is a large amount of time. I understand that the code is not optimized,> and was more or less copied from the code in the other CAS, but is this aÓ> reasonable amount of time, or is something going wrong? I don't use MathematicaÓ> because of the speed, but should it be this slow?> Just curious,> Steve StoryÓ ==== ÓI would like to use mathematica type papers for my math courses, butÓÓI'm having trouble formatting documents. Despite searching, I've beenÓÓunable to find a complete guide to word processing with mathematica.ÓDoes anyone know where such a document could be found? ==== ÓLook at in the Help browser or in the Mathematica Book ÓStyle Sheet Also, you have the documentation included for package Author ToolsÓ(only in Mathematica 4.2).ÓGuillermo Sanchez > I would like to use mathematica type papers for my math courses, butÓ> I'm having trouble formatting documents. Despite searching, I've beenÓ> unable to find a complete guide to word processing with mathematica.> Does anyone know where such a document could be found? ==== ÓKenny,ÓSympathy but no solution.ÓI too have been trying to use Mathematica (v4.2 most recently) to typeÓÓmaths papers and the like but I'm not ready to ditch LaTeX yet. ThereÓÓare just too many cases where I cannot figure out how to achieve what IÓÓwant in Mathematica, things like:- left brackets spanning multiple lines for defining hybrid functions;- vertical alignment of equals signs in multi-line equations orÓÓderivations;- setting typefaces in tables of material.ÓI figure most of this is do-able, but I don't have the time, orÓÓpatience, to spend too much time on it. So, I'll be the first customerÓÓwhen you write the guide to math publishing in Mathematica - I just hopeÓÓyou won't have to use LaTeX to write it.ÓMark WestwoodÓ> I would like to use mathematica type papers for my math courses, butÓ> I'm having trouble formatting documents. Despite searching, I've beenÓ> unable to find a complete guide to word processing with mathematica.> Does anyone know where such a document could be found? ==== ÓOrthogonalUnitVectors that I sent a few minutes ago doesn't do what IÓÓthought it would.ÓAfter making either definition below I get the following:ÓIn[2]:= s1=OrthogonalUnitVectors[{1,0,1/2,1,0},{0,1,-1,1/2,2}]ÓOut[2] = {{0, -2/Sqrt[5], 0, 0, 1/Sqrt[5]}, {-2/3, -1/3, 0, 2/3, 0}, {-1/3, 2/3,2/3, 0, 0}}ÓThe dot products below aren't zero, so the vectors aren't orthogonal. WhatÓÓwent wrong?ÓIn[3]:= Part[s1,1].Part[s1,2]ÓOut[3]= 2/(3*Sqrt[5])ÓIn[4]:= Part[s1,1].Part[s1,3]ÓOut[3]= -4/(3*Sqrt[5])--------------> 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Ó> ==== ÓDaniel Lichtblau has pointed out that NullSpace does not generally giveÓÓorthogonal vectors. Therefore the routines that depended upon that were inÓÓerror. He says that it does give orthogonal vectors when the input vectorÓÓcontains approximate numbers. For graphical purposes this will be goodÓÓenough for me. Therefore I modify Ted's routine toÓÓOrthogonalUnitVectors[vect__?(VectorQ[#, NumericQ] &)] /; (SameQ @@ Length /@ {vect}) && (Length[First[{vect}]] > 1) := #/Sqrt[#.#] & /@ NullSpace[{vect}// N]Óand the short version for 3D vectorsÓÓOrthogonalUnitVectors[v : {_, _, _}] := #/Sqrt[#.#] & /@ NullSpace[{v//N}]ÓFor exact vectors I might use for 3DÓÓOrthogonalUnitVectors[v : {_, _, _}] := #/Sqrt[#.#] & /@ {temp = First[NullSpace[{v}]], v[Cross]temp}ÓI'm still looking for something that is easy to remember.ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/Ó 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 am unsure if my messages are making it through to the usegroup so I will try again. I have several differential equations I would like to plot in Mathematica. I would like to plot the Slope Fields of them though. Can anyone lead me in the right direction? I can solve the equations trivially but I want to display the slope fields. An example follows :Óy' + 2y = 3-JohnÓ ==== ÓJohn,ÓYou can do it from scratch with PlotVectorField from the Graphics`PlotField` package, but you make make your life easier (and get prettier plots) by using my DEGraphics package, which can be found at MathSource (it's part of the ÓDiffEqs suite of packages) or here:Óhttp://www.math.armstrong.edu/faculty/hollis/mmade/ DiffEqsÓ---ÓSelwyn HollisÓ> I am unsure if my messages are making it through to the usegroup so I > will try again. I have several differential equations I would like to > plot in Mathematica. I would like to plot the Slope Fields of them > though. Can anyone lead me in the right direction? I can solve the > equations trivially but I want to display the slope fields. An example > follows :> y' + 2y = 3> -JohnÓ> Reply-To: kuska@informatik.uni-leipzig.deÓ ==== ÓNeeds[ÓGraphics` PlotField`]ÓPlotVectorField[{x, 3 - 2 y}, {x, 0, 4}, {y, -1, 4}, Axes -> True]??? JensÓ> I am unsure if my messages are making it through to the usegroup so IÓ> will try again. I have several differential equations I would like toÓ> plot in Mathematica. I would like to plot the Slope Fields of themÓ> though. Can anyone lead me in the right direction? I can solve theÓ> equations trivially but I want to display the slope fields. An exampleÓ> follows :> y' + 2y = 3> -JohnÓ ==== ÓYou can proceed like this :Ódelta[poly2_, var_] := Coefficient[poly2, var, 1]^2 - 4*Coefficient[poly2,Óvar, 0]*Coefficient[poly2, var, 2]ÓMeilleures salutationsÓÓFlorian JaccardÓ-----Message d'origine-----ÓEnvoy.8e : ven., 6. septembre 2002 09:17è : mathgroup@smc.vnet.netÓÓObjet : Coefficient problemÓÓNow I'm trying to calculate this formula:ÓDelta[eq_, x_]:=Coefficient[eq, x]^2 - 4 Coefficient[eq, x^2]ÓCoefficient[eq, x^0]Óeq has this form a x^2 + b x + cÓÓBut there is a problem with the x^0 coefficient!ÓHow can I overcome that?ÓCeZaRÓ ==== ÓThis works:Óeq = a x^2 + b x + cÓÓdiscriminant[eq_, x_] := Coefficient[eq, x]^2 - 4 Coefficient[eq, x, 2] Coefficient[eq, x, 0]Ódiscriminant[eq, x]Óx^0 is reduced to 1 and the Coefficient of 1 doesn't make sense toÓÓMathematica, because it depends on what the variable is (a, b, c, orÓÓx?). So, the other form of the Coefficient call is needed. I used itÓÓfor the second power too, but that wasn't necessary. I think that formÓÓis best, though, since it allows no ambiguity.ÓI renamed the function because that's what the quantity is often called,Ófor a quadratic.ÓBobby TreatÓ-----Original Message-----ÓCeZaRÓ ==== >-----Original Message----->Sent: Friday, September 06, 2002 9:17 AMÓ>myArray is a list of triplets which look like {n,k,p}, where n and kÓ>are integers and p is real number. repetitions in n and k are allowedÓ>but no two triplets ar the same.>>I define a function, myfunc[n_,pthreshold_] as follows.>>myfunc[n_,pthreshold_] := Module[{t},>t=Max[Cases[myArray, {n, k_, p_} /; (p >= pthreshold) -> p, 2]];>If[t>=0,t,-1]]>>It prints the largest k for which p is greater than pthreshold for aÓ>given n andÓ>-1 if there is no such k. The function does its job fine. >>My problem is as follows. I would like to plot a collection of plots,>myfunc[n,p], for 1<=n<=21 with respect to p. unfortunately theÓ>following does not work as desired.>>Plot[Table[myfunc[n,p],{n,1,21}],{p,0.0,1.0}] >>because the Table gets evaluated to numeric value (-1) before Plot isÓ>invoked.>ÓThe problem with your calculation indented is (1) to evaluate Table (withinÓÓPlot), which gives {myfunc[1, p], ..., myfunc[21, p]}Óbut (2) *then* to prevent further evaluation of myfunc[.., p] to -1. ThereÓÓare several tricks to do so, e.g. ...ÓHold[Plot[toPlot, {p, 0, 1}]] /. toPlot -> Table[headPlaceholder[n, p], {n, 3}] /. headPlaceholder -> myfunc // ReleaseHoldÓ...but in your case just simply prevent evaluation of myfunc[.., p] with pÓÓbeing a Symbol by defining:Ómyfunc2[n_, pthreshold_?NumericQ] := ...Ónow...ÓPlot[Evaluate[Table[myfunc2[n, p], {n, 21}]], {p, 0, 1}]...works as expected.ÓBTW, what do you want to read off the plot, that you didn't know fromÓÓTable[myfunc[n, 0], {n, 21}] ?--ÓHartmut WolfÓ ==== >-----Original Message----->Sent: Friday, September 06, 2002 9:17 AMÓ>> When I multiply an expression with 0 it is giving 0.expression whichÓ>is creating problem in the further calculation.>>eg.>>In[1]:=func1[r_]:=Exp[-r/2]>In[2]:coeff[[ 1,1]]=0.0;>;>;>In[34]:=func1[r]coeff[[1,1]]>>Out[34]:=0.Exp[- r/2]>>I want anything to be multiply by zero must be zero.>> How can I do that? >Your suggestion will be highly appreciated.> RajÓ>ÓRaj,Óthis simply is, because 0. Exp[-r/2] is not always zero! func1[-Infinity]coeff[[1, 1]]ÓInfinity::Óindet: ÓIndeterminate expression 0. Infinity encountered.ÓOut[90]= IndeterminateÓ--ÓHartmut WolfÓ ==== ÓI have a mathematica notebook showing using the alternating direction implicit method for solving heat conduction in 2D via finite difference methods. Moving from 2D to 3D is pretty simple although I can't find my notebook on this anymore :( . The 3D method is sometimes called Brian's method. http://mid-ohio.mse.berkeley.edu/scott/projects/index.htmlÓ[ CapitalOAcute] ScottÓ> Could you help me?> I'm to solve heat conductivity equation (Laplas > equation) - partial differential equation. Are there > any ready-to-use packages that will help me do the job?> Standard function ÓDSolve cannot! And so do functions > from package ÓCalculus`DSolveIntegrals`.> More info: the space where the equation is to be > solved is cylindre (not infinite).> Andrew.> ==== I am working with Mathematica 4.0, and I would like pass my data toÓÓdo one graphic in Origin 5.0. How can I do this in more simple manner? ==== > I need to fill the space between two contour lines, C1 and C2, withÓ> red color, and leave the other place white. What trick I have to use?> Any suggestion and advice will be appreciated.ÓOver the years I have alighted upon the following scheme. Suppose I want toÓÓcolor only between contour levels 1 and 2:ÓIn[84]:=Needs[ÓGraphics`Colors`][CapitalOA cute]In[88]:=ContourPlot[x, {x, -1, 3}, {y, 0, 1}, Contours -> {0, 1, 2, 3, 4}, ColorFunction -> (If[1 < # < 2, Red, White] & ), ColorFunctionScaling -> False];1. Specify the specific contour levels instead of specifying only the count.2. Disable ColorFunctionScaling so the argument to ColorFunction correspondsÓÓto the contour levels.ÓHope this helps,ÓTom BurtonÓ ==== ÓDavid Park replied withÓ----------------ÓDaniel Lichtblau has pointed out that NullSpace does not generally giveÓÓorthogonal vectors. Therefore the routines that depended upon that were inÓÓerror. He says that it does give orthogonal vectors when the input vectorÓÓcontains approximate numbers. For graphical purposes this will be goodÓÓenough for me. Therefore I modify Ted's routine toÓÓOrthogonalUnitVectors[vect__?(VectorQ[#, NumericQ] &)] /; (SameQ @@ Length /@ {vect}) && (Length[First[{vect}]] > 1) := #/Sqrt[#.#] & /@ NullSpace[{vect}// N]----------------ÓLets see what NullSpace does with approximate complex vectors.ÓIn[1]:= v1 = {1.0 I, 0.0, 0.5 I, 0.0, 1.0}; v2 = {0.0, 2.0, 1.0 I, 2.0, 0.5}; {v3,v4,v5} = NullSpace[{v1,v2}]ÓOut[3]= {{-0.730153 + 0.*I, 0. - 0.138254*I, 0.250585 + 0.*I, 0. - 0.138254*I, 0.+ 0.60486*I}, {0. + 0.*I, -0.515861 + 0.*I, 0. + 0.457321*I, 0.687357 + 0.*I, 0.22866+ 0.*I}, {0. + 0.*I, 0.510406 + 0.*I, 0. + 0.740442*I, -0.23274 + 0.*I, 0.370221+ 0.*I}}--------ÓIn the next line we see NullSpace returned vectors that are orthogonal toÓÓthe vectors we gave NullSpace.ÓIn[4]:= {v1.v3, v1.v4, v1.v5, v2.v3, v2.v4, v2.v5}//ChopÓÓOut[4]= {0, 0, 0, 0, 0, 0}----------ÓHowever, the vectors returned aren't orthogonal to each other.ÓIn[5]:= {v3.v4, v3.v5, v4.v5}//ChopÓÓOut[5]= {0.229195*I, 0.371087*I, -0.677239}---------ÓI suppose an OrthogonalUnitVectors function that uses NullSpace should (1) Only accept real valued vectors. (2) Ensure NullSpace is given approximate vectors.------ Ted ErsekÓ ==== >OrthogonalUnitVectors[vect__?(VectorQ[#, NumericQ] &)] /;> (SameQ @@ Length /@ {vect}) && (Length[First[{vect}]] > 1) :=> #/Sqrt[#.#] & /@ NullSpace[{vect}// N]>>---------------->>Lets see what NullSpace does with approximate complex vectors.>>In[1]:=> v1 = {1.0 I, 0.0, 0.5 I, 0.0, 1.0};> v2 = {0.0, 2.0, 1.0 I, 2.0, 0.5};> {v3,v4,v5} = NullSpace[{v1,v2}]>>Out[3]=> {{-0.730153 + 0.*I, 0. - 0.138254*I, 0.250585 + 0.*I, 0. - 0.138254*I,>0.>+ 0.60486*I}, > {0. + 0.*I, -0.515861 + 0.*I, 0. + 0.457321*I, 0.687357 + 0.*I, 0.22866>+ 0.*I}, > {0. + 0.*I, 0.510406 + 0.*I, 0. + 0.740442*I, -0.23274 + 0.*I, 0.370221>+ 0.*I}}>>-------->In the next line we see NullSpace returned vectors that are orthogonal toÓ>the vectors we gave NullSpace.>>In[4]:=> {v1.v3, v1.v4, v1.v5, v2.v3, v2.v4, v2.v5}//ChopÓ>>Out[4]=> {0, 0, 0, 0, 0, 0}>>---------->However, the vectors returned aren't orthogonal to each other.>>In[5]:=> {v3.v4, v3.v5, v4.v5}//ChopÓ>>Out[5]=> {0.229195*I, 0.371087*I, -0.677239}>>--------->I suppose an OrthogonalUnitVectors function that uses NullSpace should > (1) Only accept real valued vectors. > (2) Ensure NullSpace is given approximate vectors.>>------> Ted ErsekÓÓI think you will find that the output vectors are orthogonal if you use theÓÓcomplex conjugate. for example v4.Conjugate[v5] is zero.ÓDennis WangsnessÓ ==== >I need to fill the space between two contour lines, C1 and C2, withÓ>red color, and leave the other place white. What trick I have to use?>Any suggestion and advice will be appreciated.ÓNeeds[ÓGraphics`FilledPlot`];[Ca pitalOAcute]Needs[ÓGraphics `Colors`];ÓFilledPlot[{4 - x^2, 3x}, {x, -4, 1}, Fills -> Red];ÓBob HanlonÓ ==== >For my PDE class we have been calculating Fourier transforms. The instructorÓ>arrived today with a printout of two plots of a certain Fourier transform,>done with a different CAS. The first plot was to 30 terms, the second wasÓ>toÓ>120 terms.> Curious, I translated the functions into Mathematica (4.0 on Windows2000>on a PIII 700) to see how much time this required to process. I wasÓ>Staggered at how much time it took. Here's the code:>>L = 2;>f[x_] := UnitStep[x - 1];>b[n_] := (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];>>FS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];>>Timing[Plot[FS[30, x], {x, 0, 2}]]>>Out[23]=>{419.713 Second, [SkeletonIndicator]Graphics[SkeletonIndicator]}>>In this case the number of terms is 30.>>The time required per number of terms seems to fit the following polynomial:>>y = 0.3926x^2 + 2.2379xÓ>>This is a large amount of time. I understand that the code is not optimized,>and was more or less copied from the code in the other CAS, but is thisÓ>aÓ>reasonable amount of time, or is something going wrong? I don't use MathematicaÓ>because of the speed, but should it be this slow?>>Just curious,ÓYour definition of b recalculates the integral for every call. To evaluate Óthe integral onceÓÓinclude Evaluate.ÓClear[f, b, FS];ÓL = 2;Óf[x_] := UnitStep[x - 1];Ób[n_] := Evaluate[ (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}]];ÓIn the case of FS it is best to wait for an integer value of N prior to performing the Sum.ÓFS[N_Integer, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];ÓNow Evaluate the argument of the Plot to cause the Sum to be done once.ÓTiming[Plot[Evaluate[FS[120, x]], {x, 0, 2}]][[1]]0.366667 SecondÓÓWhile my computer may be faster than yours, this result for N=120 is 1000 times faster than your result for N=30.ÓBob HanlonÓ ==== > Now I'm trying to calculate this formula:> Delta[eq_, x_]:=Coefficient[eq, x]^2 - 4 Coefficient[eq, x^2] Coefficient[eq, x^0]> eq has this form a x^2 + b x + cÓ> But there is a problem with the x^0 coefficient!> How can I overcome that?> CeZaRÓÓCoefficient cannot figure out who is and is not a variable when aÓÓvariable of 1 is specified. To work around this you might instead doÓÓdelta1[poly_, x_] := Coefficient[poly,x]^2 - 4*Coefficient[poly,x,2]*Coefficient[poly,x,0][Cap italOAcute]I prefer instead to use CoefficientList:Ódelta2[poly_, x_] := (#[[2]]^2 - 4*#[[1]]*#[[3]])&[CoefficientList[poly,x]]ÓIn[25 ]:= poly = a*x^2+b*x+c;ÓIn[26]:= delta1[poly,x] === delta2[poly,x]ÓOut[26]= TrueÓÓDaniel LichtblauÓÓWolfram ResearchÓ ==== >>Delta[eq_, x_]:=Coefficient[eq, x]^2 - 4 Coefficient[eq, x^2] Coefficient[eq,>x^0]>>eq has this form a x^2 + b x + cÓ>>But there is a problem with the x^0 coefficient!>How can I overcome that?Ósee on-line help for CoefficientÓÓdelta[eq_, x_] := Coefficient[eq, x, 1]^2 - 4 *Coefficient[eq, x, 2] *Coefficient[eq, x, 0];Óeq = a*x^2 + b*x + c;Ódelta[eq, x]Ób^2 - 4*a*cÓÓBob HanlonÓ ==== ÓWould someone with a very fast machine and lots of memory be willing to try Óthis Solve for me?ÓIt is the inverse of the 20 node quadratic hexahedral mapping used in finite element analysis.ÓNone of my computers can handle this - they run out of memory (using (*Hex20 Node definition in global coordinates *)ÓClear[x1, y1, z1,Óx2, y2, z2,Óx3, y3, z3,Óx4, y4, z4,Óx5, y5, z5,Óx6, y6, z6,Óx7, y7, z7,Óx8, y8, z8,Óx9, y9, z9,Óx10, y10, z10,Óx11, y11, z11,Óx12, y12, z12,Óx13, y13, z13,Óx14, y14, z14,Óx15, y15, z15,Óx16, y16, z16,Óx17, y17, z17,Óx18, y18, z18,Óx19, y19, z19,Óx20, y20, z20];(* local coordinates *)ÓClear[u, v, w];(* Global co-ordinates *)ÓClear[x, y, z];(* corner nodes *)ÓN1= (1-u)*(1-v)*(1-w)*(-2-u-v-w)/8;ÓN3= (1+u)*(1-v)*(1-w)*(-2+u-v-w)/8;ÓN5= (1+u)*(1+v)*(1-w)*(-2+u+v-w)/8;ÓN7= (1-u)*(1+v)*(1-w)*(-2-u+v-w)/8;ÓN13=(1-u)*(1-v)*(1+w)*(-2-u-v +w)/8;ÓN15=(1+u)*(1-v)*(1+w)*(-2+u-v+w)/8;ÓN17 =(1+u)*(1+v)*(1 +w)*(-2+u+v+w)/8;ÓN19=(1-u)*(1+v)*(1+w)*(-2-u+v+w)/8;(* to u nodes *)ÓN2= (1-u^2)*(1-v)*(1-w)/4;ÓN6= (1-u^2)*(1+v)*(1-w)/4;ÓN14=(1-u^2)*(1-v)*(1+w)/4;[CapitalOAc ute]N18=(1-u^2) *(1+v)*(1+w)/4;(* to v nodes *)ÓN4= (1+u)*(1-v^2)*(1-w)/4;ÓN8= (1-u)*(1-v^2)*(1-w)/4;ÓN16=(1+u)*(1-v^2)*(1+w)/4;[CapitalOAc ute]N20=(1-u)*( 1-v^2)*(1+w)/4;(* to w nodes *)ÓN9= (1-u)*(1-v)*(1-w^2)/4;ÓN10=(1+u)*(1-v)*(1-w^2)/4;[CapitalOAc ute]N11=(1+u)*( 1+v)*(1-w^2)/4;ÓN12=(1-u)*(1-v)*(1-w^2)/4;(* solve the inverse transform *)ÓSolve[{x1*N1+x2*N2+x3*N3+x4*N4+x5*N5+x6*N6+x7*N7+x8*N8+x9 *N9+x10*N10+Óx11*N11+x12*N12+x13*N13+x14*N14+x15*N15+x16*N16+ x17*N17+x18*N18+x19*N19+x20*N20-x==0,Óy1*N1+y2*N2+y3*N3+y4* N4+y5*N5+y6*N6+y7*N7+y8*N8+y9*N9+y10*N10+Óy11*N11+y12*N12+y13 *N13+y14*N14+y15*N15+y16*N16+y17*N17+y18*N18+y19*N19+y20*N20 -y==0,Óz1*N1+z2*N2+z3*N3+z4*N4+z5*N5+z6*N6+z7*N7+z8*N8+z9*N9+ z10*N10+Óz11*N11+z12*N12+z13*N13+z14*N14+z15*N15+z16*N16+z17* N17+z18*N18+z19*N19+z20*N20-z==0},{u,v,w}]ÓChristopher J. PurcellÓÓDefence R&D Canada .9a AtlanticÓ9 Grove St., PO Box 1012ÓDartmouth NS Canada B2Y 3Z7 ==== ÓNeeds[ÓGraphics`Colors`];ÓCont ourPlot[Sin[x y], {x, -5, 5}, {y, -5, 5}, ColorFunction -> (If[0.5 < # < 0.7, Red, White] &)];ÓBob HanlonÓ>ContourPlot?>Jun LinÓ>> In a message dated 9/6/02 3:53:58 AM,>I need to fill the space between two contour lines,>> C1 and C2, withÓ>>red color, and leave the other place white. WhatÓ>> trick I have to use?>>Any suggestion and advice will be appreciated.>> >> Needs[ÓGraphics`FilledPlot`];>> Needs[ÓGraphics`Colors`];>> FilledPlot[{4 - x^2, 3x}, {x, -4, 1}, Fills -> Red]; ==== ÓJun Lin,ÓHere is an example.ÓNeeds[ÓGraphics`Colors`][CapitalOAcu te]Let's make a contour plot of this function.Óf[x_, y_] := Sin[x]Sin[2y]ÓLet's specify the exact contours to use. I got rid of the 0. contour becauseÓÓit is difficult to obtain in this plot.Ócontourvalues = Complement[Range[-1, 1, 0.2], {0.}]{-1, -0.8, -0.6, -0.4, -0.2, 0.2, 0.4, 0.6, 0.8, 1.}ÓNow we define a ColorFunction for the plot. I actually colored two differentÓÓbands to show how you can make a general color function to give each band aÓÓdesired color.Ócfun[z_] := Which[ -0.6 < z < -0.42, RoyalBlue, 0.4 < z < 0.6, Red, True, White]ÓContourPlot[f[x, y], {x, 0, Pi}, {y, 0, Pi}, PlotPoints -> 30, ColorFunctionScaling -> False, ColorFunction -> cfun, Contours -> contourvalues];ÓUsing the option ColorFunctionScaling -> False says that the z value will beÓÓthe actual value of f[x,y]. Otherwise, in general, it will be scaled betweenÓ0 and 1. It is easier to write a color function when z is the actual valueÓÓof the function.ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/Ó Sender: steve@smc.vnet.netÓÓApproved: Steven M. Christensen , ModeratorÓÓReply-To: ==== ÓI checked again the six solutions I had previously timed, and they DOÓÓgive orthogonal results. (None of them depend on NullSpace for that.)ÓBy the way, I reused my Ócombinations function (from a recent problemÓÓon adding fractions to get 1) to check for orthogonality: ClearAll[orthogonalQ] orthogonalQ[v : {__?VectorQ}] := And @@ (Chop@(Dot @@ #) == 0 & /@ combinations[v, {2}]) << 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]]ÓBobbyÓ-----Original Message----- (SameQ @@ Length /@ {vect}) && (Length[First[{vect}]] > 1) := #/Sqrt[#.#] & /@ NullSpace[{vect}// N]Óand the short version for 3D vectorsÓÓOrthogonalUnitVectors[v : {_, _, _}] := #/Sqrt[#.#] & /@ÓNullSpace[{v//N}]ÓFor exact vectors I might use for 3DÓÓOrthogonalUnitVectors[v : {_, _, _}] := #/Sqrt[#.#] & /@ {temp = First[NullSpace[{v}]], v[Cross]temp}ÓI'm still looking for something that is easy to remember.ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/Ó OrthogonalUnitVectors[vect__?VectorQ]:= #/Sqrt[#.#]&/@NullSpace[{vect}]-------------ÓThe version above will give a set of unit orthogonal vectors if givenÓÓanyÓÓnumb er 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 substituted the letters SS, CC, X, Y and Z1 and Z2 for some complicated expressions just to illustrate the form of the function. This function works and all the conditions are necessary but I am sure a more elegant programming solution perhaps using While could be found. Any f[{Sa_, Ca_, Aa_, Sb_, Cb_, Ab_, a_, b_}] := {If[Aa == Ab, a Sa + b Sb, If[Ca == 0 || Cb == 0, a Sa + b Sb, SS]], If[Aa == Ab, a Ca + b Cb, If[Ca == 0 || Cb == 0, a Ca + b Cb, CC]], If[Ca == 0 && Cb == 0, ÓNil, If[Z1 == Z2, If[Ca < 0, Aa, If[Cb < 0, Ab, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} ==== ÓCheck out the Help for Coefficient.ÓCoefficient[expr, form, 0] picks out terms that are not proportional toÓÓform.ÓDelta[eq_, x_] := Coefficient[eq, x]^2 - 4 Coefficient[eq, x^2] Coefficient[eq, x, 0]ÓDelta[a x^2 + b x + c, x]Ób^2 - 4*a*cÓÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/=== =ÓDear all,1.) How to find the General Solution for below's partial differential equation? (y + u) du/dx + y (du/dy) = x - yÓ** I use Ód to represent the partial differential symbol.ÓCan it be solved by function NDSolve in mathematica 4.1? How?2.) I manage to get the roots of complex equation z^5 = i fromÓÓSolve[z^5 == i, z]. It gave me straight the 5 roots in the output.ÓIs there any way to view the steps in mathematica?ÓShz ShzÓ ==== ===================================================== ==== =====================Óof the individual or entity to which they are addressed. Any disclosure, copying,Ódistribution and diversion contrary to the applicable export control laws andÓÓregulations including US Export Administration Regulations is strictly prohibited.Óand do not disclose it to others. Please notify the Ópostmaster@hitachi.com.myÓof the delivery error by replying to this message and then delete it from yourÓ ==== =================================================== ==== ===========================Ó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ÓÓ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/). ==== ÓCaution: the definitionÓÓb[n_] := Evaluate[(2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}]];Ódoesn't immediately compute the integral unless f is already defined atÓÓthis point, and in that case you may as well writeÓÓb[n_] = (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];Óinstead. If b will be computed more than once for the same n, its evenÓÓbetter to do it THIS way (if f and L do not change):Óf[x_] = Cos[x] (* for example *)ÓSimplify[Integrate[f[x]*Sin[n*Pi*(x/L)], {x, 0, L}]](L*((-n)*Pi + n*Pi*Cos[L]*Cos[n*Pi] + L*Sin[L]*Sin[n*Pi]))/ ((L - n*Pi)*(L + n*Pi))Ób[n_] := b[n] = (L*((-n)*Pi + n*Pi*Cos[L]*Cos[n*Pi] + L*Sin[L]*Sin[n*Pi]))/ ((L - n*Pi)*(L + n*Pi))ÓBobbyÓ-----Original Message-----ÓStephan Steinhaus (steinhaus-net.de). So when Mathematica takes a veryÓÓlongÓÓtime, you should investigate. In this case inserting Evaluate[] in twoÓÓplacesÓÓIn[ 91]:=b[n_] := Evaluate[(2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0,ÓL}]];....ÓIn[104]:=Timing[Plot[Evaluate[FS[ 120, x]], {x, 0, 2}]]ÓOut[104]={0.18 Second,[SkeletonIndicator]Graphics[SkeletonIndicator]}Ó speeds the process enormously (18 milliseconds to plot 120 terms on myÓÓfeeble old 500MHz PowerBook).ÓWhy was it so slow before? When I switch from an ordinary numericalÓÓlanguageÓ[CapitalOAc ute]to Mathematica, I enter into an implicit bargain withÓÓMathematica: the software will go the extra mile to get me a goodÓÓanswer,Óincluding (1) using exra precision (sometimes without being asked) andÓ(2)Ócarrying around unevaluated mathematical expressions (usually withoutÓÓbeingÓÓ asked) that could possibly be evaluated more appropriately at a laterÓÓtime.ÓMost tools cannot do either of these things, so I don't have to worryÓÓaboutÓÓit, except for the bad answers that result now and then. But I need toÓÓtakeÓÓcare that Mathematica does not burden itself unnecessarily. That's myÓÓsideÓÓof the bargain.ÓNumber (2) is the issue here. Your definition of b[n] is written so thatÓÓMathematica analytically evaluates b separately for each n. But you knowÓÓinÓÓthis case that the integration can be done safely once for all n. So doÓÓit!ÓThe huge difference, though, comes from pre-evaluating the argument toÓÓPlot.ÓRead the on-line help! You should pre-evaluate where possible. In someÓÓcases, the most common of which involve branching within the definitionÓÓofÓ[Ca pitalOAcute]function to plot, you cannot pre-evaluate so, in keeping with theÓÓbargain,ÓMathematica goes the extra mile and holds back just in case. You need toÓÓsteer it into the shortcut when it's OK.ÓHope this helps,ÓTom BurtonÓ-- ==== ÓWith the second method below (mine), the times add up to 40% less than with the first method (Jens-Peer's), for what SEEMS to be exactly the same work. Go figure!ÓCan anybody explain that?(* Jens-Peer *)ÓClearAll[f, b, FS]ÓL = 2;Óf[x_] := UnitStep[x - 1];Ób[n_] := b[n] = (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];ÓFS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];ÓTiming[Plot[FS[30, x], {x, 0, 2}]]{0.547 Second, .89»¡Graphics.89»[DownExcl amation]}(* Treat #1 *)ÓTiming[(2/L)*Integrate[f[x]*Sin[n*Pi*(x/L)], {x, 0, L}]]{0.016000000000000014*Second, (2*(Cos[(n*Pi)/2] - Cos[n*Pi]))/(n*Pi)}ÓClearAll[f, b, FS]ÓL = 2;Óf[x_] := UnitStep[x - 1];Ób[n_] := b[n] = (2*(Cos[(n*Pi)/2] - Cos[n*Pi]))/(n*Pi);ÓFS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}];ÓTiming[Plot[FS[30, x], {x, 0, 2}]]{0.297 Second, .89»¡Graphics.89»[DownExcl amation]}ÓEven stranger, it SLOWS the Plot if we precompute b before Timing starts:(* Treat #2 *)ÓClearAll[f, b, FS]ÓL = 2; f[x_] := UnitStep[x - 1]; b[n_] := b[n] = (2*(Cos[(n*Pi)/2] - (-1)^n))/(n*Pi); b /@ Range[30]; FS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}]; Timing[Plot[FS[30, x], {x, 0, 2}]]{0.328 Second, .89»¡Graphics.89»[DownExcl amation]}ÓBut here's a winner:(* Treat #3 *)ÓClearAll[f, b, FS]ÓL = 2; f[x_] := UnitStep[x - 1]; b[n_] := b[n] = N[(2*(Cos[(n*Pi)/2] - (-1)^n))/ (n*Pi)]; FS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}]; Timing[Plot[FS[30, x], {x, 0, 2}]]{0.204 Second, .89»¡Graphics.89»[DownExcl amation]}ÓApparently, computing b within the Plot causes machine-precision arithmetic to be used, and that saves time. Precomputing b and then converting exact expressions to approximate ones within the Plot seems to take longer. For that to make sense, I think it must be that n is approximate (not Integer) when it is passed to b within Plot.ÓBobby TreatÓ-----Original Message-----Óand you need only a 1-3 seconds (depending on your machine) JensÓ>> For my PDE class we have been calculating Fourier transforms. The instructorÓ> arrived today with a printout of two plots of a certain Fourier transform,> done with a different CAS. The first plot was to 30 terms, the second was toÓ> 120 terms.> Curious, I translated the functions into Mathematica (4.0 on Windows2000> on a PIII 700) to see how much time this required to process. I wasÓ> Staggered at how much time it took. Here's the code:>> L = 2;> f[x_] := UnitStep[x - 1];> b[n_] := (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];>> FS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];>> Timing[Plot[FS[30, x], {x, 0, 2}]]>> Out[23]=> {419.713 Second, [SkeletonIndicator]Graphics[SkeletonIndicator]}>> In this case the number of terms is 30.>> The time required per number of terms seems to fit the following polynomial:>> y = 0.3926x^2 + 2.2379xÓ>> This is a large amount of time. I understand that the code is not optimized,> and was more or less copied from the code in the other CAS, but is this aÓ> reasonable amount of time, or is something going wrong? I don't use MathematicaÓ> because of the speed, but should it be this slow?>> Just curious,>> Steve Story ==== ÓEven better -- MUCH better -- add Bob Hanlon's Evaluate to the other tricks:ÓClearAll[f, b, FS]ÓL = 2; f[x_] := UnitStep[x - 1]; b[n_] := b[n] = N[(2*(Cos[(n*Pi)/2] - (-1)^n))/(n*Pi)]; FS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}]; Timing[Plot[Evaluate[FS[30, x]], {x, 0, 2}]]{0.015 Second, .89»¡Graphics.89»[DownExcl amation]}ÓClearAll[f, b, FS]ÓL = 2; f[x_] := UnitStep[x - 1]; b[n_] := b[n] = N[(2*(Cos[(n*Pi)/2] - (-1)^n))/(n*Pi)]; FS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}]; Timing[Plot[Evaluate[FS[120, x]], {x, 0, 2}]]{0.063 Second, .89»¡Graphics.89»[DownExcla mation]}ÓBobby TreatÓ-----Original Message-----ÓTiming[Plot[FS[30, x], {x, 0, 2}]]{0.547 Second, .89»¡Graphics.89»[DownExcla mation]}(* Treat #1 *)ÓTiming[(2/L)*Integrate[f[x]*Sin[n*Pi*(x/L)], {x, 0, L}]]{0.016000000000000014*Second, (2*(Cos[(n*Pi)/2] - Cos[n*Pi]))/(n*Pi)}ÓClearAll[f, b, FS]ÓL = 2;Óf[x_] := UnitStep[x - 1];Ób[n_] := b[n] = (2*(Cos[(n*Pi)/2] - Cos[n*Pi]))/(n*Pi);ÓFS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}];ÓTiming[Plot[FS[30, x], {x, 0, 2}]]{0.297 Second, .89»¡Graphics.89»[DownExcl amation]}ÓEven stranger, it SLOWS the Plot if we precompute b before Timing starts:(* Treat #2 *)ÓClearAll[f, b, FS]ÓL = 2; f[x_] := UnitStep[x - 1]; b[n_] := b[n] = (2*(Cos[(n*Pi)/2] - (-1)^n))/(n*Pi); b /@ Range[30]; FS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}]; Timing[Plot[FS[30, x], {x, 0, 2}]]{0.328 Second, .89»¡Graphics.89»[DownExcl amation]}ÓBut here's a winner:(* Treat #3 *)ÓClearAll[f, b, FS]ÓL = 2; f[x_] := UnitStep[x - 1]; b[n_] := b[n] = N[(2*(Cos[(n*Pi)/2] - (-1)^n))/ (n*Pi)]; FS[N_, x_] := Sum[b[n]*Sin[n*Pi*(x/L)], {n, 1, N}]; Timing[Plot[FS[30, x], {x, 0, 2}]]{0.204 Second, .89»¡Graphics.89»[DownExcl amation]}ÓApparently, computing b within the Plot causes machine-precision arithmetic to be used, and that saves time. Precomputing b and then converting exact expressions to approximate ones within the Plot seems to take longer. For that to make sense, I think it must be that n is approximate (not Integer) when it is passed to b within Plot.ÓBobby TreatÓ-----Original Message-----Óand you need only a 1-3 seconds (depending on your machine) JensÓ>> For my PDE class we have been calculating Fourier transforms. The instructorÓ> arrived today with a printout of two plots of a certain Fourier transform,> done with a different CAS. The first plot was to 30 terms, the second was toÓ> 120 terms.> Curious, I translated the functions into Mathematica (4.0 on Windows2000> on a PIII 700) to see how much time this required to process. I wasÓ> Staggered at how much time it took. Here's the code:>> L = 2;> f[x_] := UnitStep[x - 1];> b[n_] := (2/L)*Integrate[f[x]*Sin[n*Pi*x/L], {x, 0, L}];>> FS[N_, x_] := Sum[b[n]*Sin[n*Pi*x/L], {n, 1, N}];>> Timing[Plot[FS[30, x], {x, 0, 2}]]>> Out[23]=> {419.713 Second, [SkeletonIndicator]Graphics[SkeletonIndicator]}>> In this case the number of terms is 30.>> The time required per number of terms seems to fit the following polynomial:>> y = 0.3926x^2 + 2.2379xÓ>> This is a large amount of time. I understand that the code is not optimized,> and was more or less copied from the code in the other CAS, but is this aÓ> reasonable amount of time, or is something going wrong? I don't use MathematicaÓ> because of the speed, but should it be this slow?>> Just curious,>> Steve Story ==== Ó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Ó ==== Ó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).> ==== ÓOther than Plot[{x,x^2},...] you can use Show[] as well.Óplt1=Plot[x,{x,0,1}];Óplt2=Plot[x^2,{x,0 ,1}];ÓShow[plt1 ,plt2]ÓLawrenceÓ> How can I plot with Mathematica two function in the same graphic?> I explain better:> compare a and b).> Mario,> Here is a fancy version of your plot. I used Text statements within anÓ> Epilog option to label the two curves. The regular plot statement allows youÓ> to plot a series of functions inclosed in a list.> Needs[ÓGraphics`Colors`]> Plot[{x, x^2}, {x, 0, 1},> PlotStyle -> {Black, Blue},> Frame -> True,> FrameLabel -> {x, y},> PlotLabel -> ÓComparison of Two Functions,> Epilog -> {Text[x, {0.5, 0.55}], Blue, Text[x^2, {0.7, 0.4}]},> Background -> Linen,> ImageSize -> 500];> David ParkÓ> djmp@earthlink.netÓ> http://home.earthlink.net/~djmp/> How can I plot with Mathematica two function in the same graphic?> I explain better:> compare a and b).> ==== (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Ó ==== Ó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) ==== ÓYour method 1), below, does not produce correct results if one thenÓÓuses menu>Save As Special>HTML+MathML.ÓI view the resulting .xml file in a MathML-enabled browser (e.g.,ÓMozilla with appropriate TrueType fonts installed -- the four BaKoMaÓÓcm fonts, the Óold Mathematica ÓMath1, etc., fonts, and the two MTÓÓfonts. Then the everything in the originally multi-line inline cellÓÓappears on one line separate by a ?, as do the alignment markers. InÓÓthe page source, these unrendered symbols have codes #8289 and #63328,Órespectively.ÓIs there an issue of the encoding used in the browser here? I did tryÓÓUnicode-7, Unicode-8, and several of the ÓWestern encodings availableÓÓunder Mozilla's Default Character Encoding.ÓOr is it something else? Note that I do also have the ÓnewÓMathematica TrueType fonts (ÓMathematica1, etc.).ÓP.S. I don't think Mathematica documents this, but if one wants a fileÓÓexported from Mathematica as HTML+MathML to be rendered correctly by aÓÓbrowser, it seems to require an extension of .xml rather than .html. >>When writing a series of equations in mathematica (in a text cell) >>is there any way to align the equations at the = similar toÓ >>what can be done in the equation editor made by math type (usedÓ >>in word etc.)? > > Mike, > Two waysÓ > 1) Start an inline cell in your text cell (menu>Edit>ExpressionÓÓInput>Start[CapitalOAcu te] > Inline Cell) > Type in your equations with the alignment marker (Esc am Esc) inÓÓafter eachÓ > equal sign. > Close the inline cell (menu>Edit>Expression Input>End Inline Cell). > Select the text cell (or the inline cell, though this is a delicateÓ > operation, do it by repeatedly double clicking in it}. > Use menu> Format>Text Alignment>On Alignment Marker. > -- you will find that all single letters are now italic - you canÓ selectÓ > individual letters and change this - alternatively you can selectÓ theÓÓinlineÓ > cell and use the option inspector (menu>Format>Option Inspector) toÓ setÓ > SingleLetterItalics->False) > -- you can put existing text in an inline cell by selcting it andÓ usingÓ > menu>Edit>Expression Input>Start Inline Cell, but you may have toÓ adjustÓ > the line breaks after this.... -- Murray Eisenberg Internet: murray@math.umass.eduÓ Mathematics & Statistics Dept. Voice: 413-545-2859 (W) University of Massachusetts 413-549-1020 (H) ==== ÓGroup,ÓCan anyone help me with the following? I guess this is something trivial for most of you, but I have being struggling with it for weeks.ÓThe problem is to construct a taxonomic hierarchy whose structure is hereby Ódescribed by example:<< DiscreteMath`Combinatorica`Ón[1]:= m = 10;(*with the following I get the 1th level (1--element) partition*)Óin[2]:= ks1 = Partition[Range[m], 1](*Now the following gives all the 2th-level (?) different partitions that can be set up by joining two elements in the 1-element partition and leaving the rest as they are?*)(*First, these are all possible Ôjoinings' to generate the two elements Ôpieces' from 1th level (1--element) partition*)Óin[3]:= ks2 = KSubsets[Range[m], 2](*And this generates all the 2th-level (?) different partitions that can be Óset up by joining two elements in the 1-element partition and leaving the rest as they are.*)Óin[4]:= p2 = MapThread[Complement[Append[#1, #2], (Sequence @@ {#} & /@ Partition[#2, 1])] &, {Array[ks1&, Length[ks2]], ks2}];ÓLength[p2]Óin[5]:= p2[[1]]Óout[5]:= {{3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {1, 2}}Óin[6]:= p2[[Length[p2]]]Óout[6]:= {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9, 10}}(*compute in[4] t and see the full output*)(*Now I need to solve the problem of given the ith-level (?) different partitions to set up all the i+1th different partitions by joining two elements in the ith level partition and leaving the rest as they are? *)(*for example given the following 2th-level partition*){3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {1, 2}(*we should get*){{{4}, {5}, {6}, {7}, {8}, {9}, {10}, {1, 2, 3}},{{3}, {5}, {6}, {7}, {8}, {9}, {10}, {1, 2, 4}},{{3}, {4}, {6}, {7}, {8}, {9}, {10}, {1, 2, 5}},{{3}, {4}, {5}, {7}, {8}, {9}, {10}, {1, 2, 6}},{{3}, {4}, {5}, {6}, {8}, {9}, {10}, {1, 2, 7}},{{3}, {4}, {5}, {6}, {7}, {9}, {10}, {1, 2, 8}},{{3}, {4}, {5}, {6}, {7}, {8}, {10}, {1, 2, 9}},{{3}, {4}, {5}, {6}, {7}, {8}, {9}, {1, 2, 10}}}(*The process would end up to *){1,{2,3,4,5,6,7,8,9,10}}{2,{1,3,4,5,6,7,8,9,10}}{3,{ 1,2,4,5,6,7,8,9,10}}{4,{1,2,3,5,6,7,8,9,10}}{5,{ 1,2,3,4,6,7,8,9,10}}{6,{1,2,3,4,5,7,8,9,10}}{7,{ 1,2,3,4,5,6,8,9,10}}{8,{1,2,3,4,5,6,7,9,10}}{9,{ 1,2,3,4,5,6,7,8,10}}{10,{1,2,3,4,5,6,7,8,9}}(* and*){1,2,3,4,5,6,7,8,9,10}ÓEmilio Martin-SerranoÓ ==== > I too have been trying to use Mathematica (v4.2 most recently) to typeÓ> maths papers and the like but I'm not ready to ditch LaTeX yet. ThereÓ> are just too many cases where I cannot figure out how to achieve what IÓ> want in Mathematica, things like:> - left brackets spanning multiple lines for defining hybrid functions;ÓYou can accomplish this by doing the following:1) Put your function braches in the rows of a grid box structure.2) Add the following options to your cell: ShowAutoStyles -> FalseÓ SpanMaxSize -> InfinityÓÓThe following cell snippet demonstrates how this inßuences the result. To view it, paste the Cell[] expression into a notebook and then click on Yes when you are prompted on whether the front end should interpret the result.ÓCell[BoxData[ FormBox[ RowBox[{ RowBox[{Óf, (, Óx, )}], =, RowBox[{{, GridBox[{ {Óx, RowBox[{Óx, , <, 0}]}, { SuperscriptBox[Óx, 2], RowBox[{0, [LessEqual], Óx, <, 1}]}, { RowBox[{Ósin, (, Óx, )}], RowBox[{1, [LessEqual], Óx, <, 2}]}, { RowBox[{[CapitalGamma], (, Óx, )}], RowBox[{Óx, [GreaterEqual], 2}]} }]}]}], TraditionalForm]], ÓDisplayFormula, ShowAutoStyles->False, SpanMaxSize->Infinity]> - vertical alignment of equals signs in multi-line equations orÓ> derivations;ÓPut your equations in a GridBox and set the ColumnAlignments option to a string containing the equal sign.ÓCell[BoxData[ FormBox[GridBox[{ { RowBox[{ RowBox[{ RowBox[{3, Óx}], , +, , RowBox[{4, , Óy}]}], , =, , 9}]}, { RowBox[{ RowBox[{ RowBox[{2, Óx}], , -, , RowBox[{7, , Óy}]}], =, RowBox[{32, , -, , RowBox[{Ósin, (, Óx, )}]}]}]} }], TraditionalForm]], ÓDisplayFormula, GridBoxOptions->{ColumnAlignments->{=}}]> - setting typefaces in tables of material.ÓI think the Author Tools material that comes with Mathematica 4.2 might be able to help you do this.-- User Interface Programmer paulh@wolfram.comÓÓWolfram Research, Inc. ==== ÓYou have three nonlinear (fourth-order) equations and 23 unknowns. AÓÓfaster computer won't help any.ÓBobbyÓ-----Original Message-----(*Hex20 Node definition in global coordinates *)ÓClear[x1, y1, z1,Óx2, y2, z2,Óx3, y3, z3,Óx4, y4, z4,Óx5, y5, z5,Óx6, y6, z6,Óx7, y7, z7,Óx8, y8, z8,Óx9, y9, z9,Óx10, y10, z10,Óx11, y11, z11,Óx12, y12, z12,Óx13, y13, z13,Óx14, y14, z14,Óx15, y15, z15,Óx16, y16, z16,Óx17, y17, z17,Óx18, y18, z18,Óx19, y19, z19,Óx20, y20, z20];(* local coordinates *)ÓClear[u, v, w];(* Global co-ordinates *)ÓClear[x, y, z];(* corner nodes *)ÓN1= (1-u)*(1-v)*(1-w)*(-2-u-v-w)/8;ÓN3= (1+u)*(1-v)*(1-w)*(-2+u-v-w)/8;ÓN5= (1+u)*(1+v)*(1-w)*(-2+u+v-w)/8;ÓN7= (1-u)*(1+v)*(1-w)*(-2-u+v-w)/8;ÓN13=(1-u)*(1-v)*(1+w)*(-2-u-v +w)/8;ÓN15=(1+u)*(1-v)*(1+w)*(-2+u-v+w)/8;ÓN17 =(1+u)*(1+v)*(1 +w)*(-2+u+v+w)/8;ÓN19=(1-u)*(1+v)*(1+w)*(-2-u+v+w)/8;(* to u nodes *)ÓN2= (1-u^2)*(1-v)*(1-w)/4;ÓN6= (1-u^2)*(1+v)*(1-w)/4;ÓN14=(1-u^2)*(1-v)*(1+w)/4;[CapitalOAc ute]N18=(1-u^2) *(1+v)*(1+w)/4;(* to v nodes *)ÓN4= (1+u)*(1-v^2)*(1-w)/4;ÓN8= (1-u)*(1-v^2)*(1-w)/4;ÓN16=(1+u)*(1-v^2)*(1+w)/4;[CapitalOAc ute]N20=(1-u)*( 1-v^2)*(1+w)/4;(* to w nodes *)ÓN9= (1-u)*(1-v)*(1-w^2)/4;ÓN10=(1+u)*(1-v)*(1-w^2)/4;[CapitalOAc ute]N11=(1+u)*( 1+v)*(1-w^2)/4;ÓN12=(1-u)*(1-v)*(1-w^2)/4;(* solve the inverse transform *)ÓSolve[{x1*N1+x2*N2+x3*N3+x4*N4+x5*N5+x6*N6+x7*N7+x8*N8+x9 *N9+x10*N10+Óx11*N11+x12*N12+x13*N13+x14*N14+x15*N15+x16*N16+ x17*N17+x18*N18+x19*N19+Óx20*N20-x==0,Óy1*N1+y 2*N2+y3*N3+y4* N4+y5*N5+y6*N6+y7*N7+y8*N8+y9*N9+y10*N10+Óy11*N11+y12*N12+y13 *N13+y14*N14+y15*N15+y16*N16+y17*N17+y18*N18+y19*N19+Óy20*N20 -y==0,Óz1*N1+z2*N2+z3*N3+z4*N4+z5*N5+z6*N6+z7*N7+z8*N8+z9*N9+ z10*N10+Óz11*N11+z12*N12+z13*N13+z14*N14+z15*N15+z16*N16+z17* N17+z18*N18+z19*N19+Óz20*N20-z==0},{u,v,w}]ÓCh ristopher J. PurcellÓÓDefence R&D Canada - AtlanticÓ9 Grove St., PO Box 1012ÓDartmouth NS Canada B2Y 3Z7 ==== ÓIf I haven't missed a step, the following should work nicely -- bestÓÓdone before defining any of the symbols that appear:ÓAttributes[dummyIf] = HoldAll;ÓAttributes[dummyWhich] = HoldAll;Óexpr = {If[Aa == Ab, a Sa + b Sb, If[Ca == 0 || Cb == 0, a Sa + b Sb,ÓSS]], ÓIf[Aa == Ab, a Ca + b Cb, If[Ca == 0 || Cb == 0, a Ca + b Cb, CC]], If[Ca == 0 && Cb == 0, ÓNil, If[Z1 == Z2, If[Ca < 0, Aa, If[Cb < 0, Ab, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[ Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} /. {If -> dummyIf};Órule1 = dummyIf[a_, b_, dummyIf[c_, d_, e_]] -> dummyWhich[a, b, c, d, True, e];Órule2 = dummyIf[a_, dummyIf[ b_, c_, d_], e_] -> dummyWhich[a && b, c, a, d, True,Óe];Órule3 = dummyIf[a_, dummyIf[b_, c_, d_]] -> dummyWhich[a && b, c, a, d];Órule4 = dummyWhich[a__, b_, dummyIf[c_, d_, e_], f___] -> dummyWhich[a, b && c, d, b, e, f];Órule5 = dummyWhich[a__, b_, dummyWhich[c_, d_, e___], f___] -> dummyWhich[a, b && c, d, b, dummyWhich[e], f];Órule6 = dummyWhich[] :> Null;Órule7 = HoldPattern[True && a_] :> a;Óexpr //. {rule1, rule2, rule3, rule4, rule5, rule6, rule7} /. {dummyWhich -> WhichÓÓThe result of that last line is:{Which[Aa == Ab, a Sa + b Sb, Ca == 0 || Cb == 0, a Sa + b Sb, True, SS], Which[Aa == Ab, a Ca + b Cb, Ca == 0 || Cb == 0, a Ca + b Cb, True, CC], Which[Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, X > 180, X - 180, X < 0, X + 180, True, X]}ÓI've used Null where that would be the result of your original logic --Ómaybe you want it to be ÓNil. Or maybe you want to use Null instead ofÓÓNil. Your choice. Wherever you see Null, there's possibly a case youÓÓhaven't covered.ÓBobby TreatÓ-----Original Message----- If[Aa == Ab, a Ca + b Cb, If[Ca == 0 || Cb == 0, a Ca + b Cb, CC]], If[Ca == 0 && Cb == 0, ÓNil, If[Z1 == Z2, If[Ca < 0, Aa, If[Cb < 0,ÓAb, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} ==== Ó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[CapitalOAc ute] ==== Ó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.> ==== ÓExpanding on my earlier simplification of the Moran Research code, IÓÓstudied the problem a little more and found another useful Rule and aÓÓRule that should help but doesn't. Maybe somebody can explain what I'mÓÓdoing wrong on that one.ÓMy earlier result (after applying rule1, ... rule7) had the following asÓÓthird element of a List in the definition of f:ÓWhich[ Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, X > 180, X - 180, X < 0, X + 180, True, X]ÓSeveral things occurred to me in terms of simplifying this. The firstÓÓwas that the last six arguments of Which could be replaced with two, asÓÓfollows:ÓWhich[ Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True,Mod[X,180]]ÓThis probably has no advantage other than clarity, but that's worthÓÓthe others:Órule8 = dummyIf[a_ > b_, a_ - b_, dummyIf[a_ < 0, a_ + b_, a_]] :>ÓMod[a, b];Óbut it had no effect on the expression. Apparently there was no match,Óand I can't see why.ÓThe second thing I noticed was that the conditionÓÓCa == 0 && Cb == 0Óoccurs twice in the Which statement. The following rule fixes that kindÓÓof situation:Órule9 = dummyWhich[a___, b_, c_, d__, b_, e_, f__] /; EvenQ[Length[List[a]]] &&ÓEvenQ[Length[List[d]]] && EvenQ[Length[List[f]]] :> dummyWhich[a, b, c, d, f];Óexpr //. {rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule9}ÓThe third thing I noticed was the treatment of Aa and Ab. TheÓÓexpressionsÓ[CapitalOAcut e]If[Aa > 90, Aa - 90, Aa + 90]ÓIf[Ab > 90, Ab - 90, Ab + 90]Óin the original expression may be equivalent (depending on what's knownÓÓabout Aa and Ab a priori) to:ÓMod[Aa+90,180]ÓMod[Ab+90,180][CapitalOAcut e]If that is a valid assumption in the situation (no way for me to know),Óthe expression is nowÓÓWhich[ Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, Z1 == Z2 && Ca > 0, Mod[Aa + 90, 180], Z1 == Z2 && Cb > 0, Mod[Ab + 90, 180], Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True, Mod[X, 180]]ÓThe next thing I notice is that the sixth condition, Z1==Z2, whichÓÓresults in Null if found True, isn't needed. If Z1==Z2 then one of theÓÓfirst five conditions is also true, so execution wouldn't get that far.ÓHence we can delete that condition-response pair.ÓFinally, I'm stopping with this:ÓWhich[ Ca == 0 == Cb, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, Z1 == Z2 && Ca > 0, Mod[Aa + 90, 180], Z1 == Z2 && Cb > 0, Mod[Ab + 90, 180], Aa == Ab, Aa, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True, Mod[X, 180]]ÓI have no idea what you're actually doing with this code, but it looksÓÓweird even AFTER I've simplified it.ÓBobby TreatÓ-----Original Message----- 0, Aa, If[Cb < 0, Ab, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[ Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} /. {If -> dummyIf};Órule1 = dummyIf[a_, b_, dummyIf[c_, d_, e_]] -> dummyWhich[a, b, c, d, True, e];Órule2 = dummyIf[a_, dummyIf[ b_, c_, d_], e_] -> dummyWhich[a && b, c, a, d, True,Óe];Órule3 = dummyIf[a_, dummyIf[b_, c_, d_]] -> dummyWhich[a && b, c, a, d];Órule4 = dummyWhich[a__, b_, dummyIf[c_, d_, e_], f___] -> dummyWhich[a, b && c, d, b, e, f];Órule5 = dummyWhich[a__, b_, dummyWhich[c_, d_, e___], f___] -> dummyWhich[a, b && c, d, b, dummyWhich[e], f];Órule6 = dummyWhich[] :> Null;Órule7 = HoldPattern[True && a_] :> a;Óexpr //. {rule1, rule2, rule3, rule4, rule5, rule6, rule7} /. {dummyWhich -> WhichÓÓThe result of that last line is:{Which[Aa == Ab, a Sa + b Sb, Ca == 0 || Cb == 0, a Sa + b Sb, True, SS], Which[Aa == Ab, a Ca + b Cb, Ca == 0 || Cb == 0, a Ca + b Cb, True, CC], Which[Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, X > 180, X - 180, X < 0, X + 180, True, X]}ÓI've used Null where that would be the result of your original logic --Ómaybe you want it to be ÓNil. Or maybe you want to use Null instead ofÓÓNil. Your choice. Wherever you see Null, there's possibly a case youÓÓhaven't covered.ÓBobby TreatÓ-----Original Message----- If[Aa == Ab, a Ca + b Cb, If[Ca == 0 || Cb == 0, a Ca + b Cb, CC]], If[Ca == 0 && Cb == 0, ÓNil, If[Z1 == Z2, If[Ca < 0, Aa, If[Cb < 0,ÓAb, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} ==== ÓSorry... ONE MORE simplification:ÓWhich[ Ca == 0 == Cb, ÓNil, Z1 == Z2, Which[Ca < 0, Aa, Cb < 0, Ab, Ca > 0, Mod[Aa + 90, 180], Cb > 0, Mod[Ab + 90, 180]], Aa == Ab, Aa, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True, Mod[X, 180]]ÓI didn't like repeating the Z1==Z2 test.ÓUpon noticing this, I thought at first that my rule5 caused thisÓÓsituation to occur, but actually I have to delete both rule 4 AND rule5Óto eliminate it, and the resulting expression wouldn't be as easy toÓÓunderstand.ÓBobby TreatÓ-----Original Message----- Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, X > 180, X - 180, X < 0, X + 180, True, X]ÓSeveral things occurred to me in terms of simplifying this. The firstÓÓwas that the last six arguments of Which could be replaced with two, asÓÓfollows:ÓWhich[ Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True,Mod[X,180]]ÓThis probably has no advantage other than clarity, but that's worthÓÓthe others:Órule8 = dummyIf[a_ > b_, a_ - b_, dummyIf[a_ < 0, a_ + b_, a_]] :>ÓMod[a, b];Óbut it had no effect on the expression. Apparently there was no match,Óand I can't see why.ÓThe second thing I noticed was that the conditionÓÓCa == 0 && Cb == 0Óoccurs twice in the Which statement. The following rule fixes that kindÓÓof situation:Órule9 = dummyWhich[a___, b_, c_, d__, b_, e_, f__] /; EvenQ[Length[List[a]]] &&ÓEvenQ[Length[List[d]]] && EvenQ[Length[List[f]]] :> dummyWhich[a, b, c, d, f];Óexpr //. {rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule9}ÓThe third thing I noticed was the treatment of Aa and Ab. TheÓÓexpressionsÓ[CapitalOAcut e]If[Aa > 90, Aa - 90, Aa + 90]ÓIf[Ab > 90, Ab - 90, Ab + 90]Óin the original expression may be equivalent (depending on what's knownÓÓabout Aa and Ab a priori) to:ÓMod[Aa+90,180]ÓMod[Ab+90,180][CapitalOAcut e]If that is a valid assumption in the situation (no way for me to know),Óthe expression is nowÓÓWhich[ Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, Z1 == Z2 && Ca > 0, Mod[Aa + 90, 180], Z1 == Z2 && Cb > 0, Mod[Ab + 90, 180], Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True, Mod[X, 180]]ÓThe next thing I notice is that the sixth condition, Z1==Z2, whichÓÓresults in Null if found True, isn't needed. If Z1==Z2 then one of theÓÓfirst five conditions is also true, so execution wouldn't get that far.ÓHence we can delete that condition-response pair.ÓFinally, I'm stopping with this:ÓWhich[ Ca == 0 == Cb, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, Z1 == Z2 && Ca > 0, Mod[Aa + 90, 180], Z1 == Z2 && Cb > 0, Mod[Ab + 90, 180], Aa == Ab, Aa, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, True, Mod[X, 180]]ÓI have no idea what you're actually doing with this code, but it looksÓÓweird even AFTER I've simplified it.ÓBobby TreatÓ-----Original Message----- 0, Aa, If[Cb < 0, Ab, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[ Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} /. {If -> dummyIf};Órule1 = dummyIf[a_, b_, dummyIf[c_, d_, e_]] -> dummyWhich[a, b, c, d, True, e];Órule2 = dummyIf[a_, dummyIf[ b_, c_, d_], e_] -> dummyWhich[a && b, c, a, d, True,Óe];Órule3 = dummyIf[a_, dummyIf[b_, c_, d_]] -> dummyWhich[a && b, c, a, d];Órule4 = dummyWhich[a__, b_, dummyIf[c_, d_, e_], f___] -> dummyWhich[a, b && c, d, b, e, f];Órule5 = dummyWhich[a__, b_, dummyWhich[c_, d_, e___], f___] -> dummyWhich[a, b && c, d, b, dummyWhich[e], f];Órule6 = dummyWhich[] :> Null;Órule7 = HoldPattern[True && a_] :> a;Óexpr //. {rule1, rule2, rule3, rule4, rule5, rule6, rule7} /. {dummyWhich -> WhichÓÓThe result of that last line is:{Which[Aa == Ab, a Sa + b Sb, Ca == 0 || Cb == 0, a Sa + b Sb, True, SS], Which[Aa == Ab, a Ca + b Cb, Ca == 0 || Cb == 0, a Ca + b Cb, True, CC], Which[Ca == 0 && Cb == 0, ÓNil, Z1 == Z2 && Ca < 0, Aa, Z1 == Z2 && Cb < 0, Ab, (Z1 == Z2 && Ca > 0) && Aa > 90, Aa - 90, Z1 == Z2 && Ca > 0, Aa + 90, Z1 == Z2 && (Cb > 0 && Ab > 90), Ab - 90, Z1 == Z2 && Cb > 0, Ab + 90, Z1 == Z2, Null, Aa == Ab, Aa, Ca == 0 && Cb == 0, ÓNil, Ca == 0, Ab, Cb == 0, Aa, Y == 0, ÓNil, X > 180, X - 180, X < 0, X + 180, True, X]}ÓI've used Null where that would be the result of your original logic --Ómaybe you want it to be ÓNil. Or maybe you want to use Null instead ofÓÓNil. Your choice. Wherever you see Null, there's possibly a case youÓÓhaven't covered.ÓBobby TreatÓ-----Original Message----- If[Aa == Ab, a Ca + b Cb, If[Ca == 0 || Cb == 0, a Ca + b Cb, CC]], If[Ca == 0 && Cb == 0, ÓNil, If[Z1 == Z2, If[Ca < 0, Aa, If[Cb < 0,ÓAb, If[Ca > 0, If[Aa > 90, Aa - 90, Aa + 90], If[Cb > 0, If[Ab > 90, Ab - 90, Ab + 90]]]]], If[Aa == Ab, Aa, If[Ca == 0 && Cb == 0, ÓNil, If[Ca == 0, Ab, If[Cb == 0, Aa, If[Y == 0, ÓNil, If[X > 180, X - 180, If[X < 0, X + 180, X]]]]]]]]]} ==== ÓIf x1 through x20 aren't unknowns, you should have told me their values.ÓIf you can't, they are UNKNOWN.ÓTrue, you're not solving for them... but they affect the dimensionalityÓÓof the problem just as if you WERE solving for them. You have aÓ20-dimensional space full of contingencies -- solution forms that dependÓÓon the values of x1 through x20. The Solve function won't deal withÓÓcontingencies even if it could, and if it tried, there would be tooÓÓmany.ÓBobbyÓ -----Original Message----->BobbyÓ>>-----Original Message----->Sent: Saturday, September 07, 2002 1:54 AMÓ>resendÓ>Would someone with a very fast machine and lots of memory be willing toÓ>tryÓ>this Solve for me?>It is the inverse of the 20 node quadratic hexahedral mapping used inÓ>finite element analysis.>None of my computers can handle this - they run out of memory (usingÓ>>(*Hex20 Node definition in global coordinates *)>Clear[>x1, y1, z1,>x2, y2, z2,>x3, y3, z3,>x4, y4, z4,>x5, y5, z5,>x6, y6, z6,>x7, y7, z7,>x8, y8, z8,>x9, y9, z9,>x10, y10, z10,>x11, y11, z11,>x12, y12, z12,>x13, y13, z13,>x14, y14, z14,>x15, y15, z15,>x16, y16, z16,>x17, y17, z17,>x18, y18, z18,>x19, y19, z19,>x20, y20, z20];>>(* local coordinates *)>Clear[u, v, w];>>(* Global co-ordinates *)>Clear[x, y, z];>>(* corner nodes *)>N1= (1-u)*(1-v)*(1-w)*(-2-u-v-w)/8;>N3= (1+u)*(1-v)*(1-w)*(-2+u-v-w)/8;>N5= (1+u)*(1+v)*(1-w)*(-2+u+v-w)/8;>N7= (1-u)*(1+v)*(1-w)*(-2-u+v-w)/8;>N13=(1-u)*(1-v)*(1+w)*(-2-u-v +w)/8;>N15=(1+u)*(1-v)*(1+w)*(-2+u-v+w)/8;>N17=(1+u)*(1+v)*(1 +w)*(-2+u+v+w)/8;>N19=(1-u)*(1+v)*(1+w)*(-2-u+v+w)/8;>(* to u nodes *)>N2= (1-u^2)*(1-v)*(1-w)/4;>N6= (1-u^2)*(1+v)*(1-w)/4;>N14=(1-u^2)*(1-v)*(1+w)/4;>N18=(1-u^2) *(1+v)*(1+w)/4;>(* to v nodes *)>N4= (1+u)*(1-v^2)*(1-w)/4;>N8= (1-u)*(1-v^2)*(1-w)/4;>N16=(1+u)*(1-v^2)*(1+w)/4;>N20=(1-u)*( 1-v^2)*(1+w)/4;>(* to w nodes *)>N9= (1-u)*(1-v)*(1-w^2)/4;>N10=(1+u)*(1-v)*(1-w^2)/4;>N11=(1+u)*( 1+v)*(1-w^2)/4;>N12=(1-u)*(1-v)*(1-w^2)/4;>>(* solve the inverse transform *)>Solve[{>x1*N1+x2*N2+x3*N3+x4*N4+x5*N5+x6*N6+x7*N7+x8*N8+x9 *N9+x10*N10+>x11*N11+x12*N12+x13*N13+x14*N14+x15*N15+x16*N16+ x17*N17+x18*N18+x19*N19+>x20*N20-x==0,>y1*N1+y2*N2+y3*N3+y4* N4+y5*N5+y6*N6+y7*N7+y8*N8+y9*N9+y10*N10+>y11*N11+y12*N12+y13 *N13+y14*N14+y15*N15+y16*N16+y17*N17+y18*N18+y19*N19+>y20*N20 -y==0,>z1*N1+z2*N2+z3*N3+z4*N4+z5*N5+z6*N6+z7*N7+z8*N8+z9*N9+ z10*N10+>z11*N11+z12*N12+z13*N13+z14*N14+z15*N15+z16*N16+z17* N17+z18*N18+z19*N19+>z20*N20-z==0},>{u,v,w}]>Christopher J. PurcellÓ>Defence R&D Canada - AtlanticÓ>9 Grove St., PO Box 1012>Dartmouth NS Canada B2Y 3Z7ÓChristopher J. PurcellÓÓDefence R&D Canada - AtlanticÓ9 Grove St., PO Box 1012ÓDartmouth NS Canada B2Y 3Z7 ==== ÓIf we do think of x1...x20 as constants, it's still fourth-order, withÓÓthree simultaneous equations. Evaluate this:ÓSolve[a x^4 + b x^3 + c x^2 + d x + e == 0, x]Óand look at the four solutions found -- for a single variable and oneÓÓequation!ÓFor your problem, I'm thinking there'd be at least 4^3 solutions, eachÓÓof them even more complicated than these, and an unknown number ofÓÓcontingencies to deal with, depending on values of the xi. Check eachÓÓradical for a negative argument, and the special cases multiply quickly.ÓFor some values of the xi, there'd be no solutions; for other values,Ómany solutions.ÓIf you do manage to solve this, I'd love to see the method!ÓBobbyÓ-----Original Message-----Ómany.ÓBobbyÓ-----O riginal Message----->BobbyÓ>>-----Original Message----->Sent: Saturday, September 07, 2002 1:54 AMÓ>resendÓ>Would someone with a very fast machine and lots of memory be willing toÓ>tryÓ>this Solve for me?>It is the inverse of the 20 node quadratic hexahedral mapping used inÓ>finite element analysis.>None of my computers can handle this - they run out of memory (usingÓ>>(*Hex20 Node definition in global coordinates *)>Clear[>x1, y1, z1,>x2, y2, z2,>x3, y3, z3,>x4, y4, z4,>x5, y5, z5,>x6, y6, z6,>x7, y7, z7,>x8, y8, z8,>x9, y9, z9,>x10, y10, z10,>x11, y11, z11,>x12, y12, z12,>x13, y13, z13,>x14, y14, z14,>x15, y15, z15,>x16, y16, z16,>x17, y17, z17,>x18, y18, z18,>x19, y19, z19,>x20, y20, z20];>>(* local coordinates *)>Clear[u, v, w];>>(* Global co-ordinates *)>Clear[x, y, z];>>(* corner nodes *)>N1= (1-u)*(1-v)*(1-w)*(-2-u-v-w)/8;>N3= (1+u)*(1-v)*(1-w)*(-2+u-v-w)/8;>N5= (1+u)*(1+v)*(1-w)*(-2+u+v-w)/8;>N7= (1-u)*(1+v)*(1-w)*(-2-u+v-w)/8;>N13=(1-u)*(1-v)*(1+w)*(-2-u-v +w)/8;>N15=(1+u)*(1-v)*(1+w)*(-2+u-v+w)/8;>N17=(1+u)*(1+v)*(1 +w)*(-2+u+v+w)/8;>N19=(1-u)*(1+v)*(1+w)*(-2-u+v+w)/8;>(* to u nodes *)>N2= (1-u^2)*(1-v)*(1-w)/4;>N6= (1-u^2)*(1+v)*(1-w)/4;>N14=(1-u^2)*(1-v)*(1+w)/4;>N18=(1-u^2) *(1+v)*(1+w)/4;>(* to v nodes *)>N4= (1+u)*(1-v^2)*(1-w)/4;>N8= (1-u)*(1-v^2)*(1-w)/4;>N16=(1+u)*(1-v^2)*(1+w)/4;>N20=(1-u)*( 1-v^2)*(1+w)/4;>(* to w nodes *)>N9= (1-u)*(1-v)*(1-w^2)/4;>N10=(1+u)*(1-v)*(1-w^2)/4;>N11=(1+u)*( 1+v)*(1-w^2)/4;>N12=(1-u)*(1-v)*(1-w^2)/4;>>(* solve the inverse transform *)>Solve[{>x1*N1+x2*N2+x3*N3+x4*N4+x5*N5+x6*N6+x7*N7+x8*N8+x9 *N9+x10*N10+>x11*N11+x12*N12+x13*N13+x14*N14+x15*N15+x16*N16+ x17*N17+x18*N18+x19*N19+>x20*N20-x==0,>y1*N1+y2*N2+y3*N3+y4* N4+y5*N5+y6*N6+y7*N7+y8*N8+y9*N9+y10*N10+>y11*N11+y12*N12+y13 *N13+y14*N14+y15*N15+y16*N16+y17*N17+y18*N18+y19*N19+>y20*N20 -y==0,>z1*N1+z2*N2+z3*N3+z4*N4+z5*N5+z6*N6+z7*N7+z8*N8+z9*N9+ z10*N10+>z11*N11+z12*N12+z13*N13+z14*N14+z15*N15+z16*N16+z17* N17+z18*N18+z19*N19+>z20*N20-z==0},>{u,v,w}]>Christopher J. PurcellÓ>Defence R&D Canada - AtlanticÓ>9 Grove St., PO Box 1012>Dartmouth NS Canada B2Y 3Z7ÓChristopher J. PurcellÓÓDefence R&D Canada - AtlanticÓ9 Grove St., PO Box 1012ÓDartmouth NS Canada B2Y 3Z7 ==== ÓThe documentation you're talking about doesn't even deserve to be calledÓÓdocumentation. A few hints; that's it.ÓBobby TreatÓ-----Original Message-----> unable to find a complete guide to word processing with mathematica.> Does anyone know where such a document could be found? ==== ÓThis is a question that's been asked and answered a number of times. One answer, by me, can be found by going to www.wolfram.com and selecting first Resource Library and then MathGroup on the Resource Library page; then search for Ódirection field. You'll find, among many others, the URL: http://library.wolfram.com/mathgroup/archive/2002/Jul/ msg00163.htmlÓ(This is not to chastise you for not first looking there, but to suggest a way for you to find answers more efficiently than waiting for the ou need to load the package, then manufacture a vector field whose plotÓÓis the Óslope field (what you call Óvector ßow diagram). To do theÓÓlatter, let me separately define the function giving the right-hand sideÓÓof the ODE; you don't really have to do that, but could instead directlyÓÓuse as the first argument to PlotVectorField the right-hand side of myÓÓdefinition of f. << Graphics`PlotField` f[t_, y_] := {1, 1/y} field = PlotVectorField[f[t, y], {t, 0, 3}, {y, 0.05, 3}];ÓI gave a name to the graphics result just in order to re-display theÓÓfield below along with the graph of one solution. First, find a generalÓÓsolution: soln = First @ DSolve[{y'[t] == 1/y[t], y[0] == 1}, y[t], t]{y[t] -> Sqrt[2]*Sqrt[1/2 + t]} grf = Plot[y[t] /. soln, {t, 0, 3}];ÓNow combine the plot with the field: Show[grf, field];ÓNote that PlotVectorField does not always give quite the result youÓÓmight want, since the vector lengths are scaled with respect to theÓÓmagnitude of the actual vectors. You might want just a ÓdirectionÓÓfield in which all arrows have the same length. You can produce such aÓÓgraphic by using the ScaleFunction and ScaleFactor options toÓÓPlotVectorField. For example: field = PlotVectorField[f[t, y], {t, 0, 3}, {y, 0.05, 3}, ScaleFunction -> (1 &), ScaleFactor -> 0.175];... I have several differential equations I would like toÓÓplot in Mathematica. I would like to plot the Slope Fields of them though. Can anyone lead me in the right direction? I can solve the equations trivially but I want to display the slope fields. An example follows :Óy' + 2y = 3...-- 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 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[3 27]:=Ó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Ó ==== ÓThe vectors that NullSpace gives do not need to be orthogonal toÓÓeach other. What about the following variant, that adds one vectorÓÓat a time? It may not be fast enough for serious number crunching.ÓOrthogonalComplement[v__ /; MatrixQ[{v}]] := With[{n = Length[NullSpace[{v}]]}, Take[Nest[Join[{First[NullSpace[#]]}, #] &, {v}, n], n]];ÓOrthonormalComplement[v__ /; MatrixQ[{v}]] := Map[#/Sqrt[#.#] &, OrthogonalComplement[v]];ÓWhen the input of OrthogonalComplement is integer, I expect the outputÓÓto be integer too:ÓOrthogonalComplement[{1, 2, 3}]{{1, -5, 3}, {-3, 0, 1}} Gianluca GorniÓ> OrthogonalUnitVectors that I sent a few minutes ago doesn't do what IÓ> thought it would.> After making either definition below I get the following:> In[2]:=> s1=OrthogonalUnitVectors[{1,0,1/2,1,0},{0,1,-1,1/2,2}]> Out[2]=> {{0, -2/Sqrt[5], 0, 0, 1/Sqrt[5]}, {-2/3, -1/3, 0, 2/3, 0}, {-1/3, 2/3,> 2/3, 0, 0}}> The dot products below aren't zero, so the vectors aren't orthogonal. WhatÓ> went wrong?> In[3]:= > Part[s1,1].Part[s1,2]> Out[3]=> 2/(3*Sqrt[5])> In[4]:= > Part[s1,1].Part[s1,3]> Out[3]=> -4/(3*Sqrt[5])> -------------->> 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 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Ó ==== Ó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Ó ==== ÓI noticed the same thing when I attempted to plot data with disjoint x-ranges.ÓOne way is not to use the MultipleListPlot[] function.ÓYou can plot both the lines and the markers by applying Line and Point graphics to your datasets. And use Show[] to display everything on one plot. You can use the PlotSymbol[] function instead of Point. The PlotSymbol function is available in the MultipleListPlot package to get the diamond, star, square, etc.ÓAnother way is to modify the MultipleListPlot[] function. I modified the function to do multiple plots on a polar grid.ÓWARNING - I advise you not to change any of the standpackages. Instead, first make a copy then modify it.ÓOne of the modifications I made was to changeÓ'pts = First[Transpose[data]]' in the handleset function to Ôpts=data'. This seems to work for my application.ÓHope this helps.ÓLawrenceÓ> 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Ó> ==== ÓGroup,ÓSorry for the previous posting. The following solves (to some extent my problem)< (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.)ÓYou could do something like this:Ógrlist = Map[Import[#, ÓGIF]&, {, }]Ócelist = Map[Cell[GraphicsData[ÓPostScript, DisplayString[#]]]&, grlist]ÓCellPrint[Cell[BoxData[GridBox[{celist}]], ÓText]]ÓThis embeds the PostScript versions of these graphics each as inline cellsÓÓin a GridBox[] structure.> (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?ÓAgain, we embed the PostScript graphic within an inline cell. Here is aÓÓfunction that does what you describe:ÓcreateGIFHyperlink[gifImage_String, url_String] := NotebookWrite[EvaluationNotebook[], Cell[BoxData[ ButtonBox[ Cell[GraphicsData[ÓPostScript, DisplayString[Import[gifImage, ÓGIF]]]], ButtonStyle -> ÓHyperlink, ButtonData :> {URL[url], None}]], ÓText]]-- User Interface Programmer paulh@wolfram.comÓÓWolfram Research, Inc. ==== > 1.) How to find the General Solution for below's partial differentialÓ> equation?> (y + u) du/dx + y (du/dy) = x - yÓ> ** I use Ód to represent the partial differential symbol.> Can it be solved by function NDSolve in mathematica 4.1? How?ÓIt's been a while, but I suspect that the presence of the nonlinearÓÓconvective term u du/dx alone makes a general solution unlikely. It's easyÓÓto get a numerical solution for a particular set of boundary conditions, butÓÓyou are not guaranteed a solution. For instance, the following choice of aÓÓand b are skirting failure, as the diagnostic contour plot shows.ÓTom BurtonÓÓNeeds[ÓGraphics`Colors` ]!((soln = With[{a = (-1), b = 1.27, e = 0.001}, solutions = NDSolve[{((y + u[x, y])) [PartialD]_x u[x, y] + y [PartialD]_y u[x, y] == x - y, u[x, b] == 0, u[a, y] == 0}, u, {x, a, 10}, {y, b, 10}]; [IndentingNewLine]Plot3D[ Evaluate[u[x, y] /. [InvisibleSpace]First[solutions]], {x, a, 10}, {y, b, 10}, PlotPoints [Rule] 50]; [IndentingNewLine]ContourPlot[ Evaluate[y + u[x, y] /. [InvisibleSpace]First[solutions]], {x, a, 10}, {y, b, 10}, PlotPoints [Rule] 50, ColorFunction [Rule] ((If[#1 > e, Green, Red] &))][IndentingNewLine]];)) ==== ÓI'd be happier if I could just control pagination, or if automaticÓÓpagination were done sensibly.ÓYes, I can make a page break where I want one, but I can't eliminateÓÓpage-breaks that leave tons of white-space at the end of some pages. InÓÓsome of my notebooks, Mathematica puts the first cell on a page byÓÓitself, using less than an inch --- and NOT because the next cell takesÓÓa whole page. If I force the first two cells to stay together, theÓÓproblem just moves to the next page.ÓIt's enough to make Mathematica useless as a word processor all byÓÓitself.ÓBobby TreatÓ-----Original Message-----Óderivations;- setting typefaces in tables of material.ÓI figure most of this is do-able, but I don't have the time, orÓÓpatience, to spend too much time on it. So, I'll be the first customerÓÓwhen you write the guide to math publishing in Mathematica - I just hopeÓÓyou won't have to use LaTeX to write it.ÓMark WestwoodÓ> I would like to use mathematica type papers for my math courses, butÓ> I'm having trouble formatting documents. Despite searching, I've beenÓ> unable to find a complete guide to word processing with mathematica.> Does anyone know where such a document could be found? ==== ÓBobby,ÓHave a look at the ÓGlue palette found here:---ÓSelwyn HollisÓ> I'd be happier if I could just control pagination, or if automaticÓ> pagination were done sensibly.> Yes, I can make a page break where I want one, but I can't eliminateÓ> page-breaks that leave tons of white-space at the end of some pages. InÓ> some of my notebooks, Mathematica puts the first cell on a page byÓ> itself, using less than an inch --- and NOT because the next cell takesÓ> a whole page. If I force the first two cells to stay together, theÓ> problem just moves to the next page.> It's enough to make Mathematica useless as a word processor all byÓ> itself.> Bobby TreatÓ> -----Original Message-----> Kenny,> Sympathy but no solution.> I too have been trying to use Mathematica (v4.2 most recently) to typeÓ> maths papers and the like but I'm not ready to ditch LaTeX yet. ThereÓ> are just too many cases where I cannot figure out how to achieve what IÓ> want in Mathematica, things like:> - left brackets spanning multiple lines for defining hybrid functions;> - vertical alignment of equals signs in multi-line equations orÓ> derivations;> - setting typefaces in tables of material.> I figure most of this is do-able, but I don't have the time, orÓ> patience, to spend too much time on it. So, I'll be the first customerÓ> when you write the guide to math publishing in Mathematica - I just hopeÓ> you won't have to use LaTeX to write it.> Mark WestwoodÓ>>I would like to use mathematica type papers for my math courses, butÓ>>I'm having trouble formatting documents. Despite searching, I've beenÓ>>unable to find a complete guide to word processing with mathematica.>>Does anyone know where such a document could be found?> ==== > Wouldn't it be nice if NullSpace's behavior were DOCUMENTED? Otherwise,> it's futile to give it approximate numbers expecting any particularÓ> behavior. Even if it always works, it may not work in the next versionÓ> of Mathematica.> BobbyÓÓThe expected, and documented, behavior is that the output should be aÓÓbasis for the null space, that is, solutions of the homogeneous matrixÓÓequation A.x==0. If this were to stop working then that would be aÓÓserious bug. Is this the behavior you mean?ÓThe implementation notes of the manual mention that approximateÓÓNullSpace is based on a singular values decomposition. This in factÓÓgives resulting vectors that are orthonormal by the usualÓÓconjugate-symmetric inner product on C (though these are now notÓÓnormal to the original vector in this same inner product, unless theyÓÓare real-valued). But this basis-orthogonality is not part of theÓÓmission of NullSpace and moreover should not become part of it. HenceÓÓthat particular (and implementation dependent) aspect of NullSpaceÓÓshould not become documented.ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== ÓWouldn't it be nice if NullSpace's behavior were DOCUMENTED? Otherwise,Óit's futile to give it approximate numbers expecting any particularÓÓbehavior. Even if it always works, it may not work in the next versionÓÓof Mathematica.ÓBobbyÓ-----Original Message-----Óenough for me. Therefore I modify Ted's routine toÓÓOrthogonalUnitVectors[vect__?(VectorQ[#, NumericQ] &)] /; (SameQ @@ Length /@ {vect}) && (Length[First[{vect}]] > 1) := #/Sqrt[#.#] & /@ NullSpace[{vect}// N]----------------ÓLets see what NullSpace does with approximate complex vectors.ÓIn[1]:= v1 = {1.0 I, 0.0, 0.5 I, 0.0, 1.0}; v2 = {0.0, 2.0, 1.0 I, 2.0, 0.5}; {v3,v4,v5} = NullSpace[{v1,v2}]ÓOut[3]= {{-0.730153 + 0.*I, 0. - 0.138254*I, 0.250585 + 0.*I, 0. -0.138254*I, 0.+ 0.60486*I}, {0. + 0.*I, -0.515861 + 0.*I, 0. + 0.457321*I, 0.687357 + 0.*I,0.22866+ 0.*I}, {0. + 0.*I, 0.510406 + 0.*I, 0. + 0.740442*I, -0.23274 + 0.*I,0.370221+ 0.*I}}--------ÓIn the next line we see NullSpace returned vectors that are orthogonalÓÓtoÓÓ the vectors we gave NullSpace.ÓIn[4]:= {v1.v3, v1.v4, v1.v5, v2.v3, v2.v4, v2.v5}//ChopÓÓOut[4]= {0, 0, 0, 0, 0, 0}----------ÓHowever, the vectors returned aren't orthogonal to each other.ÓIn[5]:= {v3.v4, v3.v5, v4.v5}//ChopÓÓOut[5]= {0.229195*I, 0.371087*I, -0.677239}---------ÓI suppose an OrthogonalUnitVectors function that uses NullSpace should (1) Only accept real valued vectors. (2) Ensure NullSpace is given approximate vectors.------ Ted ErsekÓ ==== ÓPlot[{x,x^2},{x,0,10}]ÓTomas GarzaÓÓMexico CityÓ----- Original Message ----->> ==== ÓMario,ÓHere is a fancy version of your plot. I used Text statements within anÓÓEpilog option to label the two curves. The regular plot statement allows youÓÓto plot a series of functions inclosed in a list.ÓNeeds[ÓGraphics`Colors`]Ó Plot[{x, x^2}, {x, 0, 1}, PlotStyle -> {Black, Blue}, Frame -> True, FrameLabel -> {x, y}, PlotLabel -> ÓComparison of Two Functions, Epilog -> {Text[x, {0.5, 0.55}], Blue, Text[x^2, {0.7, 0.4}]}, Background -> Linen, ImageSize -> 500];ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/Ó Sender: steve@smc.vnet.netÓÓApproved: Steven M. Christensen , ModeratorÓ ==== >How can I plot with Mathematica two function in the same graphic? IÓ>explain better: I'd like to draw a) y=x and b) y=x^2 in the same axesÓÓPlot[{x, x^2},{x,-2,2}] ==== ÓThis might be a convenient way of defining color functions:ÓClearAll[cfun]Ócfun[colors_List, brkPts_List] /; Length@colors == Length@brkPts := Function[z, Which @@ Sequence@Flatten@Transpose[{Less[z, #] & /@ brkPts,Ócolors}]]Ócolors = {White, RoyalBlue, White, Red, White};ÓbrkPts = {-0.6, -0.42, 0.4, 0.6, Infinity};ÓContourPlot[f[x, y], { x, 0, Pi}, {y, 0, Pi}, PlotPoints -> 30, ColorFunctionScaling ->ÓFalse, ColorFunction -> cfun[colors, brkPts], Contours -> contourvalues];Ócolors = {Yellow, Peru, Salmon, Apricot, HotPink, Linen};ÓbrkPts = {-0.6, -0.42, 0.2, 0.4, 0.6, Infinity};ÓTiming[ContourPlot[f[x, y], {x, 0, Pi}, {y, 0, Pi}, PlotPoints -> 30, ColorFunctionScaling -> False, ColorFunction -> cfun[colors,ÓbrkPts], Contours -> contourvalues];]ÓBobby TreatÓ-----Original Message-----Óit is difficult to obtain in this plot.Ócontourvalues = Complement[Range[-1, 1, 0.2], {0.}]{-1, -0.8, -0.6, -0.4, -0.2, 0.2, 0.4, 0.6, 0.8, 1.}ÓNow we define a ColorFunction for the plot. I actually colored twoÓÓdifferentÓÓ bands to show how you can make a general color function to give eachÓÓband aÓÓdesired color.Ócfun[z_] := Which[ -0.6 < z < -0.42, RoyalBlue, 0.4 < z < 0.6, Red, True, White]ÓContourPlot[f[x, y], {x, 0, Pi}, {y, 0, Pi}, PlotPoints -> 30, ColorFunctionScaling -> False, ColorFunction -> cfun, Contours -> contourvalues];ÓUsing the option ColorFunctionScaling -> False says that the z valueÓÓwill beÓÓthe actual value of f[x,y]. Otherwise, in general, it will be scaledÓÓbetweenÓ0 and 1. It is easier to write a color function when z is the actualÓÓvalueÓÓof the function.ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/Ó Sender: steve@smc.vnet.netÓÓApproved: Steven M. Christensen , ModeratorÓ ==== ÓFor what it's worth, here's a version of Simpson's rule that works with both equally spaced and unequally spaced points.Ósimp = Compile[{x1,y1,x2,y2,x3,y3},ÓWith[{h13=x1-x3, h12=x1-x2, h23=x2-x3},(-y1*h23*(2x1-3x2+x3) - y2*h13^2 + y3*h12*(x1-3x2+2x3))*h13/(6h12*h23)]]; ListSimpson[vals_?VectorQ, dx_Real]:= With[{n=Length[vals]},ÓIf[OddQ[n], (dx/3)*(First[vals] + Last[vals] + 4*Plus@@vals[[Range[2,n-1,2]]] + 2*Plus@@vals[[Range[3,n-2,2]]]), $Failed]];ÓListSimpson[datapts_?MatrixQ] := If[OddQ[Length[datapts]], Plus@@(simp@@Flatten[#]&/@ Partition[datapts,3,2]), $Failed] (* equally spaced points*)Ódata = Table[100*Sin[x], {x, 0, 100, 0.001}];ÓListSimpson[data, .001] // TimingÓ {0.21 Second, 13.7681}(* randomly spaced points *)ÓTable[{data = Sort[Table[With[{x = Random[Real,{0,100}]},{x,100*Sin[x]}],{100001}]];Ó ListSimpson[data] // Timing,ÓWith[{xvals = Transpose[data][[1]]},Ógaps = Drop[RotateLeft[xvals] - xvals, -1];{Min[gaps], Max[gaps]}]},{4}] {{{1.62 Second, 13.8348}, {1.32223*10^-8, 0.0114454}}, {{1.59 Second, 13.8261}, {2.42163*10^-8, 0.0127803}}, {{1.62 Second, 13.8455}, {1.08923*10^-9, 0.0119059}}, {{1.54 Second, 13.7987}, {9.66814*10^-9, 0.0106988}}}---ÓSelwyn HollisÓ> Mathew,>> Some possibilitiesÓ>> <> ListIntegrate[data]//TimingÓ>> {6.59 Second,13.7681}>> The following is suggested in the Help Browser entry for the packageÓ> Integrate[> Interpolation[data, InterpolationOrder[Rule]1][x],> {x,0,100}]//TimingÓ>> {4.56 Second,13.768}>> Trapezium rule with equal steps:>> #[[1]]+#[[-1]]+ 2 Tr[Take[#,{2,-2}]]&[data[[All,2]]] 0.01/2//TimingÓ>> {0.22 Second,13.768}>> Trapezium rule with possibly unequal stepsÓ>> (Drop[#1,1] - Drop[#1,-1]).(Drop[#2,-1] + Drop[#2,1])&[> data[[All,1]], data[[All,2]]]/2//TimingÓ>> {0.83 Second,13.768}>> --> 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> I've tracked down the slow operation of my Mathematica simulation > code toÓ> lie in the ListIntegrate command:>> G[n_] := ListIntegrate[xsec Phi[n], 1]>> where both xsec and Phi[n] are 400 values long.>> Is there a way to speed up ListIntegrate via Compile or a similar > technique?> MattÓ> ---> Matthew RosenÓ> Harvard-Smithsonian Center for AstrophysicsÓ> Mail Stop 59> 60 Garden StreetÓ> Cambridge, MA 02138>> e: mrosen@cfa.harvard.eduÓ> o: (617) 496-7614> ==== ÓP.J.,ÓI'd be very interested in how you created these Ófancy cells. Do youÓÓopen a cell, push Ctrl-Shift-e, type in all that text, then pushÓÓCtrl-Shift-e again?ÓBobby TreatÓ-----Original Message-----1) Put your function braches in the rows of a grid box structure.2) Add the following options to your cell: ShowAutoStyles -> FalseÓ SpanMaxSize -> InfinityÓÓThe following cell snippet demonstrates how this inßuences the result.ÓTo view it, paste the Cell[] expression into a notebook and then clickÓÓon Yes when you are prompted on whether the front end should interpret the result.ÓCell[BoxData[ FormBox[ RowBox[{ RowBox[{Óf, (, Óx, )}], =, RowBox[{{, GridBox[{ {Óx, RowBox[{Óx, , <, 0}]}, { SuperscriptBox[Óx, 2], RowBox[{0, [LessEqual], Óx, <, 1}]}, { RowBox[{Ósin, (, Óx, )}], RowBox[{1, [LessEqual], Óx, <, 2}]}, { RowBox[{[CapitalGamma], (, Óx, )}], RowBox[{Óx, [GreaterEqual], 2}]} }]}]}], TraditionalForm]], ÓDisplayFormula, ShowAutoStyles->False, SpanMaxSize->Infinity]> - vertical alignment of equals signs in multi-line equations orÓ> derivations;ÓPut your equations in a GridBox and set the ColumnAlignments option to aÓÓstring containing the equal sign.ÓCell[BoxData[ FormBox[GridBox[{ { RowBox[{ RowBox[{ RowBox[{3, Óx}], , +, , RowBox[{4, , Óy}]}], , =, , 9}]}, { RowBox[{ RowBox[{ RowBox[{2, Óx}], , -, , RowBox[{7, , Óy}]}], =, RowBox[{32, , -, , RowBox[{Ósin, (, Óx, )}]}]}]} }], TraditionalForm]], ÓDisplayFormula, GridBoxOptions->{ColumnAlignments->{=}}]> - setting typefaces in tables of material.ÓI think the Author Tools material that comes with Mathematica 4.2 mightÓÓbe able to help you do this.-- User Interface Programmer paulh@wolfram.comÓÓWolfram Research, Inc. ==== > I'd be very interested in how you created these Ófancy cells. Do youÓ> open a cell, push Ctrl-Shift-e, type in all that text, then pushÓ> Ctrl-Shift-e again?ÓSurely you have grossly overestimated my expertise with MathematicaÓÓtypesetting language syntax. :-)ÓHere is the walkthrough for creating each sample cell.ÓExample 1:1) Set down a cell insertion point in your notebook.3) Click on the cell's bracket.4) Click on the front end menu command sequence:ÓFormat -> Cell Style -> DisplayFormulaÓ5) Click on the front end menu command sequence:ÓCell -> Display As -> TraditionalFormÓ6) Click on the front end menu command:ÓFormat -> Option Inspector...7) Make sure that the Option Inspector scope indicator is set toÓÓselection.8) Enter the name of the option ShowAutoStyles into the search field andÓÓpress the Lookup button.9) Change the value of the option ShowAutoStyles from True to False. ThisÓÓprevents the front end from showing the left brace with the umatchedÓÓsyntax coloring.10) Look up the option SpanMaxSize as was done in step (8).11) Change the value of this option to Infinity.12) Close the Option Inspector dialog.13) Click within the cell you just created to create an editor caret.14) Type in the textÓ f(x) = {4 x 2.17) Enter in the function branch definitions in the left column, and theÓÓdomains of definition in the right column. You can use the Tab key toÓÓnavigate between grid elements.ÓExample 2:1) Repeat Steps (1) - (11) in Example 1.2) With the cell bracket still selected, look up the option namedÓÓColumnAlignments. Change it from {Center} to {=}.3) Close the Option Inspector dialog.4) Click within the cell you just created to create an editor caret.6) Enter in the equations, with one equation per grid element.ÓI used the front end menu command Edit -> Copy As -> Cell Expression toÓÓget the underlying expressions.ÓHope that demystifies the procedure for you.-- User Interface Programmer paulh@wolfram.comÓÓWolfram Research, Inc. ==== Ó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}150012400005001 (* 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][Capital OAcute]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-----Ó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 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?ÓThe easiest way is to expand your PlotRange to include the errant points.ÓDave. ==== Ó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Ó ==== Ó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Ó ==== ÓI made the algorithm more than twice as fast with very little change,Ówhile eliminating modifications to <,>,<=, and >=. Most of theÓÓimprovement, in fact, was due to eliminating those changes AFTER theÓÓcode was changed so they wouldn't be used anyway. That's because theÓÓcomparisons appear everywhere, so adding rules to those functions reallyÓÓslows down pattern matching.ÓClear[add, node]Ónode[a___, node[b_], c___] = node[a, b, c]; node[node[a__]] = node[a]; 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]]Óadd[node[x_, lower_], y_node] := Which[First[y] >= x, node[x, lower, y], First[y] <= lower, node[lower, y, x], True, node[y, lower, x]]Óadd[node[x_, lower_, higher_], y_node] /; First[y] <= x := node[x, add[lower, y], higher]Óadd[node[x_, lower_, higher_], y_node] := node[x, lower, add[higher, y]]ÓSeedRandom[5]; nums = NullÓÓTiming[Do[nums = add[nums, Random[]], {5000}]; ]{0.968*Second, Null}ÓNone of the other stats changed.ÓBobby TreatÓ-----Original Message-----Ó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}150012400005001 (* 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][Capital OAcute]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-----Ó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Ó ==== > Daniel,> > I don't mean to be overly critical of WRI's documentation -- it's veryÓ> good, as such things go. Nor do I like to overlook chances to make itÓ> better. Do you?ÓI'll try to address your specific remarks below and then return to this.> Your own comments below point out that we should expect vectorsÓ> resulting from NullSpace to be Óorthonormal by the usualÓ> conjugate-symmetric inner product on C. But that's not spelled outÓ> (documented) for dummies like myself who don't know that's a naturalÓ> result of singular values decomposition.ÓMy comments indicate that they will be orthonormal, for approximateÓÓnumericÓ[CapitalOA cute]matrix input, so long as the implementation is based on SVD. But that'sÓÓnot by any means part of what NullSpace is required to do, and it isÓÓquiteÓÓclear ly implementation dependent.> The Ómission of NullSpace (or any function) is to adhere toÓ> documentation, so reasonable persons may differ on whether orthogonalityÓ> is a feature we should depend on.ÓWell... the name ÓNullSpace gives a pretty good idea of what it needsÓÓtoÓÓdo. When you stop to consider all the matrix Ótypes (approximateÓÓnumbers,Óexact numbers, symbolic, numeric but with non-number elements e.g. PiÓÓandÓÓSqrt[2]) you quickly realize that different types will most likely beÓÓhandled by different methods, and these may have differentÓÓcharacteristicsÓ[Ca pitalOAcute]of output e.g. normalized vectors, vectors with last nonzero componentÓÓequal to one, or other quirks. But these are artifacts ofÓÓimplementation,Ónot part of the requirements of a null space.> The mission of documentation is to tell us what to expect. When itÓ> doesn't, the result is that we spend all this time discussing issuesÓ> online, trying to figure things out. A simple Ódon't depend onÓ> orthogonal results would be nice, if that's the intent.ÓPerhaps. If there is strong reason to expect that people might dependÓÓon such results in the first place. I don't think there is.> In any case, I just spent ten minutes LOOKING for implementation notesÓ> for NullSpace, and have not found any. Searching for ÓimplementationÓ> notes doesn't help and there's no link from NullSpace. What use isÓ> documentation I can't find?> In general, I don't like Mathematica's quirky Help Browser, in which IÓ> cannot search for anything that's not indexed. Every other help engineÓ> on my computer (and there are hundreds) allows me to search for words,> and that's exactly what I need in order to find all mentions ofÓ> NullSpace.ÓI found it in the back of the book, appendix A.9, ÓSome Notes onÓÓInternalÓÓIm plementation. See A.9.4, ÓApproximate numerical linear algebra.ÓIn the Help Browser, click on ÓThe Mathematica Book and then typeÓÓimplementation in the window. The second URL it gives is ÓA.9. I'llÓÓgrant you one might reasonably desire a good search engine. I just wantÓÓto indicate that what is there now is not entirely useless in thisÓÓinstance provided you at least know about the existance of these notesÓÓin the book.> Bobby TreatÓ> [...]ÓTo respond to your question at the beginning, yes, I also like to seeÓÓimprovements in documentation. I certainly agree that a good searchÓÓengine would be useful in this case. Though note that I also may notÓÓbe using the Help Browser to its fullest capabilities (I claim noÓÓgreat familiarity with the Mathematica user interface). As for theÓÓspecific issue of what to document about NullSpace, suffice it to sayÓÓthat I do not favor making claims beyond what it is required to do.ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== ÓDaniel,ÓI don't mean to be overly critical of WRI's documentation -- it's veryÓÓgood, as such things go. Nor do I like to overlook chances to make itÓÓbetter. Do you?ÓYour own comments below point out that we should expect vectorsÓÓresulting from NullSpace to be Óorthonormal by the usualÓÓconjugate-symmetric inner product on C. But that's not spelled outÓ(documented) for dummies like myself who don't know that's a naturalÓÓresult of singular values decomposition.ÓThe Ómission of NullSpace (or any function) is to adhere toÓÓdocumentation, so reasonable persons may differ on whether orthogonalityÓÓis a feature we should depend on.ÓThe mission of documentation is to tell us what to expect. When itÓÓdoesn't, the result is that we spend all this time discussing issuesÓÓonline, trying to figure things out. A simple Ódon't depend onÓÓorthogonal results would be nice, if that's the intent.ÓIn any case, I just spent ten minutes LOOKING for implementation notesÓÓfor NullSpace, and have not found any. Searching for ÓimplementationÓÓnotes doesn't help and there's no link from NullSpace. What use isÓÓdocumentation I can't find?ÓIn general, I don't like Mathematica's quirky Help Browser, in which IÓÓcannot search for anything that's not indexed. Every other help engineÓÓon my computer (and there are hundreds) allows me to search for words,Óand that's exactly what I need in order to find all mentions ofÓÓNullSpace.ÓBobby TreatÓ-----Original Message-----> of Mathematica.> BobbyÓÓThe expected, and documented, behavior is that the output should be aÓÓbasis for the null space, that is, solutions of the homogeneous matrixÓÓequation A.x==0. If this were to stop working then that would be aÓÓserious bug. Is this the behavior you mean?ÓThe implementation notes of the manual mention that approximateÓÓNullSpace is based on a singular values decomposition. This in factÓÓgives resulting vectors that are orthonormal by the usualÓÓconjugate-symmetric inner product on C (though these are now notÓÓnormal to the original vector in this same inner product, unless theyÓÓare real-valued). But this basis-orthogonality is not part of theÓÓmission of NullSpace and moreover should not become part of it. HenceÓÓthat particular (and implementation dependent) aspect of NullSpaceÓÓshould not become documented.ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== Ó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}**********************************************[Capita lOAcute] 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ÓÓ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Ó ==== Ó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}**********************************************[Capita lOAcute] 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 ==== ÓDaniel,ÓWe mostly agree. I simply look at things from a slightly differentÓ(user, non-WRI) perspective. My original point was -- in line with yourÓÓown comments -- that people shouldn't depend on NullSpace to returnÓÓorthogonal vectors even when it seems to do so, because it's notÓÓdocumented behavior. (Although YOU knew about it and could point toÓÓdocumentation of it! Sort of.)ÓUnlike you, perhaps, I consider the lack of search capabilities in HelpÓÓan EGREGIOUS failing -- a mistake no other Help engine makes (so far asÓÓI know). Fix that, and 90% of my complaints about documentation wouldÓÓgo away; I could have found the implementation notes on NullSpace, forÓÓinstance, without already KNOWING where they are. That is preciselyÓÓwhat annoys me most of the time; the information is there, but I can'tÓÓfind it. (If searching for Óimplementation works, why doesn'tÓÓimplementation notes yield anything at all?)ÓNow that I've found this page, I'll add it to all the other informationÓÓlocations I'm trying to remember. (There's not much there anyway,Óthough.)ÓBobbyÓ-----Ori ginal Message-----ÓI'll try to address your specific remarks below and then return to this.> Your own comments below point out that we should expect vectorsÓ> resulting from NullSpace to be Óorthonormal by the usualÓ> conjugate-symmetric inner product on C. But that's not spelled outÓ> (documented) for dummies like myself who don't know that's a naturalÓ> result of singular values decomposition.ÓMy comments indicate that they will be orthonormal, for approximateÓÓnumericÓ[CapitalOA cute]matrix input, so long as the implementation is based on SVD. But that'sÓÓnot by any means part of what NullSpace is required to do, and it isÓÓquiteÓÓclear ly implementation dependent.> The Ómission of NullSpace (or any function) is to adhere toÓ> documentation, so reasonable persons may differ on whetherÓÓorthogonalityÓ> is a feature we should depend on.ÓWell... the name ÓNullSpace gives a pretty good idea of what it needsÓÓtoÓÓdo. When you stop to consider all the matrix Ótypes (approximateÓÓnumbers,Óexact numbers, symbolic, numeric but with non-number elements e.g. PiÓÓandÓÓSqrt[2] ) you quickly realize that different types will most likely beÓÓhandled by different methods, and these may have differentÓÓcharacteristicsÓ[Cap italOAcute]of output e.g. normalized vectors, vectors with last nonzero componentÓÓequal to one, or other quirks. But these are artifacts ofÓÓimplementation,Ónot part of the requirements of a null space.> The mission of documentation is to tell us what to expect. When itÓ> doesn't, the result is that we spend all this time discussing issuesÓ> online, trying to figure things out. A simple Ódon't depend onÓ> orthogonal results would be nice, if that's the intent.ÓPerhaps. If there is strong reason to expect that people might dependÓÓon such results in the first place. I don't think there is.> In any case, I just spent ten minutes LOOKING for implementation notesÓ> for NullSpace, and have not found any. Searching for ÓimplementationÓ> notes doesn't help and there's no link from NullSpace. What use isÓ> documentation I can't find?> In general, I don't like Mathematica's quirky Help Browser, in which IÓ> cannot search for anything that's not indexed. Every other helpÓÓengineÓ> on my computer (and there are hundreds) allows me to search for words,> and that's exactly what I need in order to find all mentions ofÓ> NullSpace.ÓI found it in the back of the book, appendix A.9, ÓSome Notes onÓÓInternalÓÓIm plementation. See A.9.4, ÓApproximate numerical linear algebra.ÓIn the Help Browser, click on ÓThe Mathematica Book and then typeÓÓimplementation in the window. The second URL it gives is ÓA.9. I'llÓÓgrant you one might reasonably desire a good search engine. I just wantÓÓto indicate that what is there now is not entirely useless in thisÓÓinstance provided you at least know about the existance of these notesÓÓin the book.> Bobby TreatÓ> [...]ÓTo respond to your question at the beginning, yes, I also like to seeÓÓimprovements in documentation. I certainly agree that a good searchÓÓengine would be useful in this case. Though note that I also may notÓÓbe using the Help Browser to its fullest capabilities (I claim noÓÓgreat familiarity with the Mathematica user interface). As for theÓÓspecific issue of what to document about NullSpace, suffice it to sayÓÓthat I do not favor making claims beyond what it is required to do.ÓDaniel LichtblauÓÓWolfram ResearchÓ ==== ÓBobby TreatÓ-----Original Message-----> Yes, I can make a page break where I want one, but I can't eliminateÓ> page-breaks that leave tons of white-space at the end of some pages.ÓInÓ> some of my notebooks, Mathematica puts the first cell on a page byÓ> itself, using less than an inch --- and NOT because the next cellÓÓtakesÓ> a whole page. If I force the first two cells to stay together, theÓ> problem just moves to the next page.> It's enough to make Mathematica useless as a word processor all byÓ> itself.> Bobby TreatÓ> > -----Original Message-----> Kenny,> Sympathy but no solution.> I too have been trying to use Mathematica (v4.2 most recently) to typeÓ> maths papers and the like but I'm not ready to ditch LaTeX yet. ThereÓ> are just too many cases where I cannot figure out how to achieve whatÓÓIÓ> want in Mathematica, things like:> - left brackets spanning multiple lines for defining hybrid functions;> - vertical alignment of equals signs in multi-line equations orÓ> derivations;> - setting typefaces in tables of material.> I figure most of this is do-able, but I don't have the time, orÓ> patience, to spend too much time on it. So, I'll be the firstÓÓcustomerÓ> when you write the guide to math publishing in Mathematica - I justÓÓhopeÓ> you won't have to use LaTeX to write it.> Mark WestwoodÓ>>I would like to use mathematica type papers for my math courses, butÓ>>I'm having trouble formatting documents. Despite searching, I've beenÓ>>unable to find a complete guide to word processing with mathematica.>>Does anyone know where such a document could be found?> ==== ÓGroup,ÓSorry for the previous posting. The following solves (to some extent my problem)<10.02Ótimes2=First[Timing[fLPartition[3,20];]]/. Second->10.18Ótimes3=First[Timing[fLPartition[3,30];]]/. Second->10.701Ótimes4=First[Timing[fLPartition[3,40];]]/. Second->11.913Ótimes5=First[Timing[fLPartition[3,50];]]/. Second->14.236Ótimes6=First[Timing[fLPartition[3,60];]]/. Second->18.222Ótimes7=First[Timing[fLPartition[3,70];]]/. Second->114.39Ótimes8=First[Timing[fLPartition[3,80];]]/. Second->123.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Ó___________________________________[CapitalOA cute]Emilio Martin-SerranoÓÓSchlumbergerÓ[ CapitalOAcute]Oil & Gas Business Consulting PrincipalÓ1325 South Dairy Ashford RoadÓÓHouston, TX 77077 ==== Ó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 ßush 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.-- 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 ==== Ó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[CapitalOAcut e]Ó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 ßush 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. ==== ÓIt seems there is an error in the BinCounts function of Mathematica'sÓÓstandard <Left, FontSize->18],ÓCell[<ÓSept. 9, 2002ÓMark D. NormandÓÓUMass Dept. of Food ScienceÓÓmnormand@foodsci.umass.edu>, ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[<[CapitalOAcu te]Load the Data Manipulation functions from the Statistics Standard ÓPackage.>, ÓText, TextAlignment->Left],ÓCell[BoxData[ (<< Statistics`DataManipulation`)], ÓInput]}, Open ]],ÓCell[CellGroupData[{Cell[ÓAssign data to the vector (1D list) dat., ÓText, TextAlignment->Left],ÓCell[BoxData[ ((dat = {63, 184, 23, 14, 17, 32, 26, 666, 27, 11, 28, 53, 37, 29,4, 60, 7, 23, 94, 18, 43, 15, 74, 42, 81, 8, 7, 19, 0, 27, 87,35, 3, 24, 94, 42, 4, 7, 18, 7, 38, 1, 0, 61, 3, 40, 22, 8, 3, 2, 0,2, 5, 5, 7, 0, 9, 2, 11, 13, 105, 51, 36, 149, 147, 12, 1, 1, 7, 8,10, 1, 7, 25, 38, 142, 15, 8, 9, 16, 0, 1, 4, 3, 31, 30, 10};))], ÓInput]}, Open ]],ÓCell[CellGroupData[{Cell[ÓCount the number of dat data rows., ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[ (datRows = Length[dat])], ÓInput],ÓCell[BoxData[ (87)], ÓOutput]}, Open ]]}, Open ]],ÓCell[CellGroupData[{Cell[ÓFind the minimum value in the dat data rows., ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[ (datMin = Min[dat])], ÓInput],ÓCell[BoxData[ (0)], ÓOutput]}, Open ]]}, Open ]],ÓCell[CellGroupData[{Cell[ÓFind the maximum value in the dat data rows., ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[ (datMax = Max[dat])], ÓInput],ÓCell[BoxData[ (666)], ÓOutput]}, Open ]]}, Open ]],ÓCell[CellGroupData[{Cell[ÓCalculate the number of histogram bins to use., ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[ (datBins = Ceiling[Log[2, datRows]])], ÓInput],ÓCell[BoxData[ (7)], ÓOutput]}, Open ]]}, Open ]],ÓCell[CellGroupData[{Cell[ÓSet the width of a histogram bin., ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[ (datBinWidth = N[((datMax - datMin))/datBins])], ÓInput],ÓCell[BoxData[ (95.14285714285714`)], ÓOutput]}, Open ]]}, Open ]],ÓCell[CellGroupData[{ TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[Cell [BoxData[ ({76, 5, 0, 0, 0, 0, 0, 1})], ÓOutput]}, Open ]]}, Open ]],ÓCell[CellGroupData[{Cell[<ÓFor the above dat list, if datBins equals, for example, 5,7,10,14 Óof Óhistogram bins generated) is one more than the assigned datBins value. Yet 13 Óor 16. Why!? (Is this a bug?)>, ÓText, TextAlignment->Left],ÓCell[CellGroupData[{Cell[BoxData[Cell [BoxData[ (8)], ÓOutput]}, Open ]]}, Open ]]},ÓScreenRectangle->{{0, 1024}, {0, 748}},ÓCellGrouping->Manual,ÓWindowSize->{520, 626},ÓWindowMargins->{{-1, Automatic}, {Automatic, -1}},ÓMacintoshSystemPageSetup-><0080001804P000000_82@? okonh34`9B;@<5:0?l00;m009H0UP0000068dB`0B`02d5X5k/02H80@ 4101P00BL?00400@ 00000000000000P0010000020D000000000000000000000000000004T40000 2004>] ==== ÓOn my machine, replacing Null with made Husain's code 8 times fasterÓÓon the same test: 0.592 seconds versus 4.688.ÓI suppose making the same change in my code makes no difference becauseÓÓthere are no Nulls in the tree (except one, very brießy), or perhapsÓÓbecause I have fewer patterns that involve Nulls.ÓBy rearranging the order of my rules, and deleting a couple that wereÓÓnever used, I made my algorithm about 15% faster, getting the time downÓÓto 0.906. Mihajlo's amazing discovery beats that, of course -- it's 50%Ófaster.ÓI suppose what we've found is that (1) my algorith makes the code fourÓÓto five times faster by reducing expression complexity, tree depth, andÓÓmemory use, but it's a slower algorithm otherwise (too many rules?); andÓ(2) Mathematica pattern matching and code execution has a real problemÓÓwith Null used as if it means something.ÓBobbyÓ-----Original Message-----Óadd[node[x_Real, lower_, higher_], y_Real] := node[x, lower, add[higher,Óy]];Ónums = ÓNULL;ÓSeedRandom[5];ÓDo[nums = add[nums, Random[]], {5000}] // TimingÓÓOutÓ{5.11 Second, Null}ÓClear[add];Óadd[Null, x_Real] := node[x, Null, Null];Óadd[node[x_Real, lower_, higher_], y_Real] /; x > y := node[x, add[lower, y], higher];Óadd[node[x_Real, lower_, higher_], y_Real] := node[x, lower, add[higher,Óy]];Ónums = Null;ÓSeedRandom[5];ÓDo[nums = add[nums, Random[]], {5000}] // TimingÓÓOutÓ{41.03 Second, Null}ÓAlso:ÓSimplify[1==Null]1==Null[CapitalO Acute]Ódoesn't evaluate to false!!ÓBtw. changing Null to ÓNULL in your code doesn't infulence the speed... Mihajlo VanevicÓ mvane@EUnet.yuÓ 2002-09-09*************************************************** ************ At 2002-09-09, 00:29:00 ************************************************************* *>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Ó********************************************** **************** ==== Ó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Ó ==== Ó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Ó ==== ÓI am having some trouble with numerical integration.!(((Timing[ ansOUT = {}; [IndentingNewLine]For[EbNo = 0, EbNo <= 2, EbNo += 10/10, [IndentingNewLine]linEbNo = 10^(EbNo/10); [IndentingNewLine]M = 64; [IndentingNewLine]K = Log[2, M]; [IndentingNewLine]p = (M/2)/(M - 1) Sum[ Binomial[M - 1, n] (((-1)))^(n + 1)/(1 + n) Exp[(- linEbNo) K n/(1 + n)], {n, 1, M - 1}]; [IndentingNewLine]Pm = (1/@(2 [Pi])) NIntegrate[ 1 - ((((1/@(2 [Pi])) NIntegrate[ Exp[(-x^2)/2], {x, (-[Infinity]), y}, WorkingPrecision -> 32 ]))^(M - 1)) Exp[((-1)/2) ((y - @(2 K linEbNo)))^2], {y,(-[Infinity]), [Infinity]}, WorkingPrecision -> 32]; [IndentingNewLine]Pb = ((M/2)/(M - 1)) Pm; [IndentingNewLine]AppendTo[ ansOUT, {N[a, 4], N[p, 8], N[Pb, 8]}];[IndentingNewLine]];])([IndentingNewLine])) )ÓTableForm[ansOUT]ÓThe code can also be downloaded fromÓÓhttp://www.itee.uq.edu.au/~dsalman/_down loads/ Proakis.nbÓÓCol. 2(symblic formula) and 3 (result of numerical integration) of theÓÓvariable ansOUT should be identical.ÓHowever the numerical integration is giving a 0 answer.ÓCan anyone please suggest how a solution to this problem.ÓSalmanÓ ==== ÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== ÓNeeds[ÓGraphics` Graphics`]ÓLogPlot[Exp[-x],{x,0,10}]?? JensÓ> ==== <>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 3193053 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[CapitalO Acute]Ó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 ßoor symbols! Use esc l f escÓÓfor the left ßoor and esc r f esc for the right ßoor. 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`]ÓLog LinearPlot[Sqrt[x], {x, 1., 1000}, ImageSize -> 500];ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/ Approved: Steven M. Christensen , ModeratorÓ ==== > 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 ßush 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[ CapitalOAcute]Ó 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. ==== Ó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];[Capital OAcute]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[CapitalOA cute]Ó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ÓÓcla ss satisfies the condition it is possible to avoid generating theÓÓwholeÓÓstruc ture 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->10.02Ótimes2=First[Timing[fLPartition[3,20];]]/. Second->10.18Ótimes3=First[Timing[fLPartition[3,30];]]/. Second->10.701Ótimes4=First[Timing[fLPartition[3,40];]]/. Second->11.913Ótimes5=First[Timing[fLPartition[3,50];]]/. Second->14.236Ótimes6=First[Timing[fLPartition[3,60];]]/. Second->18.222Ótimes7=First[Timing[fLPartition[3,70];]]/. Second->114.39Ótimes8=First[Timing[fLPartition[3,80];]]/. Second->123.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Ó___________________________________[CapitalOA cute]Emilio Martin-SerranoÓÓSchlumbergerÓ[ CapitalOAcute]Oil & Gas Business Consulting PrincipalÓ1325 South Dairy Ashford RoadÓÓHouston, TX 77077 ==== Ó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 3193053 RegensburgÓ ==== Ó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-----> ==== > 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Ó> ==== >-----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]:=[CapitalOAcut e]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]:=[C apitalOAcute]Plot3D[Sin[x]^2 Sin[y]^2, {x, 0, Pi}, {y, 0, Pi}]ÓOut[3]=[SkeletonIndicator]SurfaceGraphics[ SkeletonIndicator]...ÓIn[5]:=ÓShow[%%, ColorOutput -> GrayLevel]--ÓHartmutÓ ==== Ó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Ó ==== Ó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Ó[Capi talOAcute]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`];[CapitalOA cute]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Ó[CapitalOAcute ]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Ó**********************************************[CapitalOA cute]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][CapitalOAcute ]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[<[Capita lOAcute] 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Ó[Capi talOAcute]http://home.earthlink.net/~djmp/Ó Sender: steve@smc.vnet.netÓÓApproved: Steven M. Christensen , ModeratorÓ ==== ÓAdding my two cents to:> There are many cases in graphics, and otherwise, where it is useful toÓ> obtain two orthogonal unit vectors to a given vector. I know a number ofÓ> ways to do it, but they all seem to be slightly inelegant. I thought I wouldÓ> pose the problem to MathGroup. Who has the most elegant MathematicaÓ> routine...ÓTo this I would like to add a criterion of smoothness. Armed with a secondÓÓvector b not parallel to the given vector a, it's a trivial matter toÓÓorthogonalize b WRT a by Gram-Schmidt and then form the third vector c = a xÓÓb. (Normalize as needed.)ÓI don't need more elegance that this, but I would like a scheme to selectÓÓthe vector b that results in a triad {a,b,c} that various smoothly as ÓaÓvaries over all possible directions. Each of my attempts to date involve aÓÓbranched algorithm and jumps in the resulting triad for certain smallÓÓchanges in Óa.ÓTo David's call for elegance I add a call for smoothness.ÓTom BurtonÓ ==== ÓDoes anybody have Benchmarks for Mathematica 4.2 to share?ÓIf possible the same or similar machine and different OSes.Óto the Windows version.ÓI tried http://www2.staff.fh-vorarlberg.ac.at/~ku/karl/timings40. htmlÓÓvalue of 6.4.---more details--ÓTimes = [InvisibleSpace]{1.18, 1.14, 1.08, 0.55, 1.18, 2.48, 0.74, 0.79, 0.41, 0.11, 0.38, 0.96, 0.97, 1.26, 1.11}ÓTime = [InvisibleSpace]17.ÓBenchmark = [InvisibleSpace]6.40784----------------------------------- -------------ÓI would like to see how Mathematica 4.2 improved in speedÓÓcompared to Mathematica 4 or 3. ArminÓ ==== ÓUse Text statements. Click of a coordinate point on the plot, copy it andÓÓpaste it into the Text statement. Here is an example.ÓShow[Graphics[ {Circle[{1, 1}, 2], Text[ÓA, {1.75659, 2.03292}], Circle[{0, 0}, 2], Text[ÓB, {-1.38818, -0.0197372}], Circle[{1, -1}, 2], Text[ÓC, {1.57238, -1.99344}]}], AspectRatio -> Automatic, ImageSize -> 400];ÓTo click off a coordinate:1) Select the plot by putting the cursor in it and clicking.2) Press and hold Ctrl. When you move the cursor you will obtain crossÓÓhairs.3) Move the cursor to where you want to put the text and left click.4) Right click and use Copy. (Or use Ctrl-C or the menu).5) Paste the copied coordinate as the second argument in the Text statement.ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/=== =ÓMark,ÓJust add a PlotRange option and that each pentomino will be plotted to theÓÓsame scale.ÓShow[ GraphicsArray[ Partition[ Table[ Graphics[ Map[Rectangle[#, (# + {1, 1})] &, pentominoes[[i]]], AspectRatio -> Automatic, PlotRange -> {{0, 5}, {0, 5}} ], {i, 12}], 6] ]]ÓDavid ParkÓÓdjmp@earthlink.netÓ[Capi talOAcute]http://home.earthlink.net/~djmp/{{0 , 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}}, (*I*){{0, 0}, {1, 0}, {2, 0}, {3, 0}, {0, 1}}, (*L*){{0, 0}, {1, 0}, {2, 0}, {2, 1}, {3, 1}}, (*N*){{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}}, (*P*){{0, 0}, {1, 0}, {2, 0}, {1, 1}, {1, 2}}, (*T*){{0, 0}, {1, 0}, {2, 0}, {0, 1}, {2, 1}}, (*U*){{0, 0}, {1, 0}, {2, 0}, {0, 1}, {0, 2}}, (*V*){{0, 0}, {1, 0}, {1, 1}, {2, 1}, {2, 2}}, (*W*){{1, 0}, {0, 1}, {1, 1}, {2, 1}, {1, 2}}, (*X*){{0, 0}, {1, 0}, {2, 0}, {3, 0}, {1, 1}}, (*Y*){{0, 0}, {1, 0}, {1, 1}, {1, 2}, {2, 2}} (*Z*)}ÓWhen I display them with the code below, the aspect ratio is correct *withinÓÓeach pentomino* but they are not scaled equivalently. I would appreciate aÓÓpointer to what I have done wrong. The only solution I have been able toÓÓdevelop so far effectively places each of the 12 pentominoes at a differentÓÓlocation in the plane, and then draws the whole region in one go.ÓShow[ GraphicsArray[ Partition[ Table[ Graphics[ Map[Rectangle[#, (# + {1, 1})] &, pentominoes[[i]]], AspectRatio -> AutomaticÓ ], {i, 12}], 6] ]]--ÓMark R. DiamondÓ ==== ÓIn my previous post, I proposedÓÓOrthogonalUnitVectors[v:{_, _, _}] := With[{u = Which[ (w = {0,v[[3]],-v[[2]]}).w != 0, w, (w = {v[[3]],0,-v[[1]]}).w != 0, w, (w = {v[[2]],-v[[1]],0}).w != 0, w ] }, #/Sqrt[#.#]& /@ {u, Cross[u,v]}]ÓThe trouble with this is that w ends up being a global variable. The only way I see around that is to use Module instead of With. (May as well put in a Return[$Failed] too.)ÓOrthogonalUnitVectors[v:{_, _, _}] := Module[{u, w}, u = Which[(w = {0,v[[3]],-v[[2]]}).w != 0, w, (w = {v[[3]],0,-v[[1]]}).w != 0, w, (w = {v[[2]],-v[[1]],0}).w != 0, w, True, Return[$Failed]]; #/Sqrt[#.#]& /@ {u, Cross[u, v]} ]----ÓSelwyn HollisÓ ==== ÓI have spent an enormous amount of time (far too much) on this question.ÓIndeed, I have just completed a program that handles all sorts ofÓÓpiecewise defined functions. I am in the process of writing it up toÓÓoffer it to all of you. In my opinion the best, cleansest method is toÓÓinvoke the UnitStep function as illustrated in David Park's solutions.ÓTo make everything cleaner, define a characteristic functionÓÓChi[x_,a_,b_] := UnitStep[x-a]-UnitStep[x-b]ÓThis function is continuous on the right, vanishes outside of [a,b) and isÓÓone in the half-open interval [a,b). Now your answer isÓ x^2 Chi[x,0,6] + (x+1) Chi[x,6,Infinity]ÓThe integrator handles UnitSteps easily and smoothly.ÓMy program handles these cases easily and many more, including suchÓÓoddities as Integrate[Abs[x],x] and (for amusement sake only)ÓUnitStep[ Abs[x]-Sign[x]+3]ÓAnother virtue of this approach (also handled in my program) is theÓÓpeculiar error messages and poor answers given by NIntegrate for simpleÓÓpiecewise continuous functions at jump discontinuites. The limit functionÓÓalso fails dismally on some examples where it really shouldn'tÓÓI am rather naive about how to transmit programs to interested users, soÓÓif you would like a copy of my program and about 100 worked examples, IÓÓwill be glad to send them to you IF YOU TELL ME HOW TO DO IT!ÓJack GoldbergÓ> In a message dated 8/31/02 1:58:36 AM, berlusconi_pagliusi@fis.unical.itÓ> I'd like to use Mathematica 4.0 to write a function having differentÓ> expressions in different domain's intervals.> Let's say:> >> F[x_]= x^2 if 0 x+1 if x>=6>> I know It's a stupid syntax problem, but I really do not know how/where toÓ> search the solution on the Mathematica BookÓ> Just for grins here are several methods:>> f1[x_/;x<=0] := 0 ;>> f1[x_/;0> f1[x_/;x>=6] := x+1;> f2[x_] :=>> x^2*UnitStep[x]+(x+1-x^2)*UnitStep[x-6];> f3[x_] := Which[>> x<=0, 0,>> 0> x>=6, x+1];> f4[x_] := If[0> If[x>=6, x+1,0]];> f5[x_] := Switch[x,>> _?(#<=0&), 0,>> _?(0<#<6&), x^2,>> _?(#>=6&), x+1 ]> f6[x_?NumericQ] :=>> {0,x^2,x+1}[[Position[>> {x<=0,0=6}, True][[1,1]]]];> Needs[ÓCalculus`Integration`];>> (* needed for definition of Boole *)> f7a[x_?NumericQ] := Evaluate[>> (Boole /@ {0=6}).>> {x^2,x+1}];> Off[Part::pspec];>> f7b[x_?NumericQ] := Evaluate[>> {0,x^2,x+1}[[1+Tr[Boole /@ {x>0, x>=6}]]]];> f8[x_?NumericQ] := Cases[>> {{x<=0, 0}, {0=6, x+1}},>> {True, z_} :>z][[1]];> f9[x_?NumericQ] := DeleteCases[>> {{x<=0, 0}, {0=6, x+1}},>> {False, z_}][[1,2]];> f10[x_?NumericQ] := Select[>> {{x<=0, 0}, {0=6, x+1}},>> First[#]&][[1,2]];> f11[x_?NumericQ] := Last[Sort[>> {{x<=0, 0}, {0=6, x+1}}]][[2]];> f12[x_?NumericQ] := Module[{n=1},>> While[{x<6,x<0, False}[[n]], n++];>> {x+1,x^2,0}[[n]]];> Generating some test points:>> ts = {Random[Real,{-5,0}],0, Random[Real,{0,6}],6,Random[Real,{6,15}]};> Checking the different representationsÓ>> Equal[(# /@ pts)& /@ {f1,f2,f3,f4,f5,f6,f7a,f7b,f8,f9,f10,f11,f12}]> TrueÓ>> To pick a favorite, look at how the different definitions behave.> Of the definitions that evaluate with symbolic input, only f2 and f4> simplify with assumptionsÓ> . For example,>> FullSimplify[#[x]& /@ {f2,f4}, 1 f2 through f5 respond immediately to differentiationÓ> #'[x]& /@ {f2,f3,f4,f5} // Simplify //ColumnFormÓ> Only f2 responds immediately to integrationÓ> Integrate[f2[x],x]//SimplifyÓ>> Consequently, f2 (UnitStep) appears to be the most versatile.> Bob HanlonÓ> Chantilly, VA USAÓ>> ==== ÓCan I use Mathematica to find out the volumn of this 3 dimensional object fromÓÓthe equations :Óz=x^2 +4, y=4-x^2, y=3xÓÓShz ShzÓÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== Óthe volume is 0 because you get two pointsÓÓSolve[{y == 4 - x^2, y == 3x}, {x, y}]{{y -> -12, x -> -4}, {y -> 3, x -> 1}}ÓwithÓ{{y -> -12, x -> -4,z->20}, {y -> 3, x -> 1,z -> 5}}ÓTo get a nonzero volume you neeed a singel implicit equation likeÓ0==f[x,y,z]Óor you need 3 parametric equationsÓ{ x==f[1][u,v], y==f[2][u,v], z==f[3][u,v]}ÓIf you have an implicit equation you can compute theÓÓsurface with MathGL3d's MVContourPlot3D[] (not withÓÓthe ContourPlot3D[] from the standard addons, becauseÓÓyou need a consistent oriented surface) and than you can triangulate the surface an sum the signed voulmesÓÓof the tetrahedrons build from the triangles and a fixed point in space.ÓFor parametric surfaces you can do the same with the polygons. JensÓ> Can I use Mathematica to find out the volumn of this 3 dimensional object fromÓ> the equations :> > z=x^2 +4, y=4-x^2, y=3xÓ> Shz ShzÓ ==== Ó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Ó ==== Ó First of all, I would like to thanks to all for trying to help.ÓSorry, I must have something missing in my previous description.ÓI need to find out the volumn of a 3D object which form by the equation :Óz=x^2 +4 (as bottom surface)Óand on the xy plane which bounded by a parabola y=4-x^2 and y=3x line.ÓHow would I use Mathematica to plot out this 3D object or find out its volumnÓÓwith only the equation given?ÓShz ShzÓ ==== ===================================================== ==== =====================Óof the individual or entity to which they are addressed. Any disclosure, copying,Ódistribution and diversion contrary to the applicable export control laws andÓÓregulations including US Export Administration Regulations is strictly prohibited.Óand do not disclose it to others. Please notify the Ópostmaster@hitachi.com.myÓof the delivery error by replying to this message and then delete it from yourÓ ==== =================================================== ==== =======================ÓReply-To: kuska@informatik.uni-leipzig.deÓ ==== Óyou mean:ÓIn[]:=Needs[ÓCalculus`Integration`][Cap italOAcute]Integrate[Boole[x ^2 + 4 - z > 0 && 4 - x^2 - y > 0 && 3 - x - y < 0 && z > 0], {x, -1, 2}, {y, 1, 5}, {z, -1, 10}]]ÓOut[]=(15*Sqrt[5])/4Óand to plot the volume:ÓIn[]:=Get[ÓMathGL3d`OpenGLViewer`][Ca pitalOAcute]In[]:= MVContourPlot3D[ If[1 == Boole[x^2 + 4 - z > 0 && 4 - x^2 - y > 0 && 3 - x - y < 0 && z > 0], 1., -1.], {x, -1, 2}, {y, 1, 5}, {z, -0.1, 7}, Contours -> {0.}, PlotPoints -> 64, MVNewScene -> True] JensÓ> First of all, I would like to thanks to all for trying to help.> Sorry, I must have something missing in my previous description.> I need to find out the volumn of a 3D object which form by the equation :> z=x^2 +4 (as bottom surface)> and on the xy plane which bounded by a parabola y=4-x^2 and y=3x line.> How would I use Mathematica to plot out this 3D object or find out its volumnÓ> with only the equation given?> Shz ShzÓ> ==== ======================================================== ==== ==================> of the individual or entity to which they are addressed. Any disclosure, copying,> distribution and diversion contrary to the applicable export control laws andÓ> regulations including US Export Administration Regulations is strictly prohibited.> and do not disclose it to others. Please notify the Ópostmaster@hitachi.com.my> of the delivery error by replying to this message and then delete it from yourÓ> ==== ======================================================== ==== ======================ÓBy taking sums and differences of the counterweights 1, 3, ... 3^(k-1)Óyou can precisely express all integers up to the integer whose base 3Ónotation is composed of k ones.ÓBy doubling those counterweights, you can precisely express all the EVENÓÓintegers up to TWICE that limit, or -1 + 3^k. If you know that unknownsÓÓare limited to the integers from 1 to 3^k, this allows you to preciselyÓÓweight the even numbers and bracket the odd numbers. HenceÓÓcounterweights 2, 6, ... 2*3^(k-1) are sufficient for unknowns up toÓ3^k.ÓNotice that this is an efficient coding scheme: Each counterweight isÓÓmultiplied by -1, 0, or 1, so there can be at most 3^k distinctÓÓcounterweight sums. More than half are negative or zero, however; theÓÓpositive sums and differences number at most (3^k - 1)/2. Since we needÓÓto enumerate (and CAN enumerate with even weights) only the even numbersÓÓand because we get the maximum unknown 3^k by elimination, we Ócover upÓÓto twice as many as we can enumerate, plus one. Twice (3^k - 1)/2 plusÓÓone is 3^k, so we're getting the maximum coverage possible for a givenÓÓnumber of counterweights.ÓBobby TreatÓ-----Original Message-----ÓFor these 40 positive integers to match 1 to 40 correspondingly, theÓÓbiggestÓÓsh ould be 40 (also, the smallest should be 1). So we have:Óa+b+c+d=40 or 1+b+c+d=40 (we state that a> I have a very interesting math problem:If I have a scales,and IÓ>> have 40 things that their mass range from 1~40 which each is aÓÓnatureÓ>> number,and now I can only make 4 counterweights to measure out eachÓ>> mass of those things.Question:What mass should the counterweightsÓ>> be???>> The answer is that 1,3,9,27 and I wnat to use mathematica toÓÓsolveÓ>> this problem.>> In fact,I think that this physical problem has variousÓ>> answer,ex.2,4,10,28>> this way also work,because if I have a thing which weight 3 , and IÓ>> can measure out by comparing 2<3<4 . But,If I want to solve thisÓÓmathÓ>> problem:>> {x|x=k1*a+k2*b+k3*c+k4*d}={1,2,3,4,,,,,,40} where a,b,c,d is natureÓ> numbers.>> and {k1,k2,k3,k4}={1,0,-1}>> How to solve it ??>> mathematica solving method. appreciate any idea sharingÓ>> sincerelyÓ> >> bryanÓ> Just use brute force.>> Needs[ÓDiscreteMath`Combinatorica`];>> var = {a, b, c, d}; n = Length[var];>> s = Outer[Times, var, {-1, 0, 1} ];>> f = Flatten[Outer[Plus, Sequence@@s]];>> Since the length of f is just 3^n then the range of numbersÓ> to be covered should be {-(3^n-1)/2, (3^n-1)/2}.> Consequently, the largest of the weights can not exceedÓ> (3^n-1)/2 - (1+2+...+(n-1)) orÓ>> ((3^n-1) - n(n-1))/2>> 34>> Thread[var->#]& /@>> (First /@ Select[{var,f} /. Thread[var->#]& /@>> KSubsets[Range[((3^n-1) - n(n-1))/2], n],>> Sort[#[[2]]] == Range[-(3^n-1)/2,(3^n-1)/2]&])>> {{a -> 1, b -> 3, c -> 9, d -> 27}}> Bob HanlonÓ> Chantilly, VA USAÓ> ==== >>But my actual output reproduces the input form, i.e., it is simplyÓÓf[...listA,newEntry,...].[CapitalOAcu te]That means your arguments don't fit a pattern for which the function isÓÓdefined. That is, it has nothing to do with what's on the right side ofÓ:=. It's about making sure there are the right number and type ofÓÓarguments passed to the function. You haven't told us what the patternÓÓis or what the arguments are, so we can't help you.ÓBobbyÓ-----Original Message----- 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ÓÓplaceÓshows: 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ÓÓw ith 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Ó ==== Ó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Ó[CapitalOAcut e]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,Interpola tionOrder[ 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ÓÓlis t_?(VectorQ[#, NumericQ] &)Ómakes no sense at all. Maybe you meantÓÓlist_?And[VectorQ[#],NumericQ[#]]&[Cap italOAcute]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Ó ==== Ó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. ==== ÓI want to make a list of all symbols in the Global context, as inÓÓNames[ÓGlobal`*][CapitalOAc ute]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 ====