A106 === Subject: Re: Fourier Trasform of a Bessel Function I try to make the following > FourierTransform[BesselJ[n, x], x, w]; >> % /. n -> 0 I try >> FourierTransform[BesselJ[0, x], x, w] > I obtain another result. Why? Because the output for FourierTransform[BesselJ[n, x], x, w] is wrong (for all n). In[1]:=f[n_]:=FourierTransform[BesselJ[n,x,],x,w] In[2]:=f[2]//FullSimplify Out[2]:=0 === Subject: Re: Fourier Trasform of a Bessel Function > I try to make the following > FourierTransform[BesselJ[n, x], x, w]; >> % /. n -> 0 I try >> FourierTransform[BesselJ[0, x], x, w] > I obtain another result. Why? Vladislav, The issue is that, by default, FourierTransform[] does not generate/check any conditions on the parameters and thus returns the most general case. So, your first expression returns zero for n == 0, which is true for any w > 1 or w < -1. However, for -1 < w < 1 the true value is not zero (see below). And of course the expression is not defined for w == 1 or w == -1. You can force FourierTransform[] to generate conditions and also put GenerateConditions -> True and Assumptions, perspectively. In[1]:= expr = FourierTransform[BesselJ[0, x], x, w] Out[1]= (Sqrt[2/[Pi]] (-HeavisideTheta[-1 + w] + HeavisideTheta[1 + w]))/Sqrt[1 - w^2] In[2]:= FullSimplify[expr, Assumptions -> w > 1] Out[2]= 0 In[3]:= FullSimplify[expr, Assumptions -> w < -1] Out[3]= 0 In[4]:= FullSimplify[expr, Assumptions -> -1 < w < 1] Out[4]= Sqrt[2]/Sqrt[[Pi] - [Pi] w^2] In[5]:= Plot[(-HeavisideTheta[-1 + w] + HeavisideTheta[1 + w]), {w, -5, 5}] Plot[expr, {w, -5, 5}] In[7]:= FourierTransform[BesselJ[n, x], x, w, GenerateConditions -> True] Out[7]= If[w^2 > 1 && Re[n] > -1, ( E^((I n [Pi])/ 2) (-w + Abs[w]) (Sqrt[-1 + w^2] + Abs[w])^-n Sin[n [Pi]])/( Sqrt[2 [Pi]] w Sqrt[-1 + w^2]), FourierTransform[BesselJ[n, x], x, w, GenerateConditions -> True]] In[8]:= % /. n -> 0 Out[8]= If[w^2 > 1, ( E^((I 0 [Pi])/ 2) (-w + Abs[w]) (Sqrt[-1 + w^2] + Abs[w])^-0 Sin[0 [Pi]])/( Sqrt[2 [Pi]] w Sqrt[-1 + w^2]), FourierTransform[BesselJ[0, x], x, w, GenerateConditions -> True]] In[9]:= % // Simplify Out[9]= [Piecewise] { {((Sqrt[2/[Pi]] (-HeavisideTheta[-1 + w] + HeavisideTheta[1 + w]))/ Sqrt[1 - w^2]), -1 <= w <= 1} } -- === Subject: Abs[x] function Who can explain the behavior. THe derivative Abs[x] at x=.5 is well defined and is equal to 1. In[1]:= D[Abs[x], x] Out[1]= !(*SuperscriptBox[Abs, [Prime], MultilineFunction->None])[x] In[2]:= % /. x -> .5 Out[2]= !(*SuperscriptBox[Abs, [Prime], MultilineFunction->None])[0.5] === Subject: Re: Abs[x] function because you have forgotten to define Derivative[1][Abs][x_] := Sign[x] > Who can explain the behavior. THe derivative Abs[x] at x=.5 is well > defined and is equal to 1. In[1]:= D[Abs[x], x] Out[1]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[x] In[2]:= % /. x -> .5 Out[2]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[0.5] > === Subject: Re: Abs[x] function Hi Vlad, by default Mathematica uses complex numbers. As Abs is not an analytical function, it does not have a derivative (the differential quotient depends on direction). Therefore, the derivative of Abs is not defined. For your application, you could define the derivative you would like to have yourself by e.g.: Unprotect[Abs]; Abs'[x_]:=Which[x<0,-1,x==0,undefined,x>0,1]; hope this helps, Daniel > Who can explain the behavior. THe derivative Abs[x] at x=.5 is well > defined and is equal to 1. In[1]:= D[Abs[x], x] Out[1]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[x] In[2]:= % /. x -> .5 Out[2]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[0.5] > === Subject: Re: Abs[x] function > Who can explain the behavior. THe derivative Abs[x] at x=.5 is well > defined and is equal to 1. In[1]:= D[Abs[x], x] Out[1]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[x] In[2]:= % /. x -> .5 Out[2]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[0.5] Please use copy as plain text when pasting Mathematica expressions, so it will be easier to read them. Just use FunctionExpand on the result to get a concrete value. === Subject: Indefinite numbers of arguments in a function Hello everybody, Is it possible to define a function in Mathematica, where the numbers of arguments does not matter? I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I can call the function with five arguments (for example Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can define for ever number of arguments a function like that: MyPlus[a_,b_]:=a+b MyPlus[a_,b_,c_]:=a+b+c MyPlus[a_,b_,c_,d_]:=a+b+c+d MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e I also know that I can create a list as one argument: MyPlus[list_List] := ( m = 0; For[n = 1, n < Length[list] + 1, n++, m += list[[n]] ]; m ) But since there are functions like Plus, there has to be a way to define those kind of functions. I would be very glad, if someone could give me his advice. Patrick Klitzke email: philologos14@gmx.de === Subject: Re: Indefinite numbers of arguments in a function MyPlus[a__]:=Plus @@ {a} ?? > Hello everybody, > Is it possible to define a function in Mathematica, where the numbers of > arguments does not matter? I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I can > call the function with five arguments (for example > Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can > define for ever number of arguments a function like that: > MyPlus[a_,b_]:=a+b > MyPlus[a_,b_,c_]:=a+b+c > MyPlus[a_,b_,c_,d_]:=a+b+c+d > MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e I also know that I can create a list as one argument: MyPlus[list_List] := ( > m = 0; For[n = 1, n < Length[list] + 1, n++, m += list[[n]] ]; > m > ) > But since there are functions like Plus, there has to be a way to define > those kind of functions. I would be very glad, if someone could give me his advice. > Patrick Klitzke email: philologos14@gmx.de > === Subject: Re: Indefinite numbers of arguments in a function Hi Patrick, the magic word is: BlankSequence, written: __ (two underscores). Similar: BlankSequenceRepeated. Here is an example: myPlus[x__]:=Plus[x] hope this helps, Daniel > Hello everybody, > Is it possible to define a function in Mathematica, where the numbers of > arguments does not matter? I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I can > call the function with five arguments (for example > Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can > define for ever number of arguments a function like that: > MyPlus[a_,b_]:=a+b > MyPlus[a_,b_,c_]:=a+b+c > MyPlus[a_,b_,c_,d_]:=a+b+c+d > MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e I also know that I can create a list as one argument: MyPlus[list_List] := ( > m = 0; For[n = 1, n < Length[list] + 1, n++, m += list[[n]] ]; > m > ) > But since there are functions like Plus, there has to be a way to define > those kind of functions. I would be very glad, if someone could give me his advice. > Patrick Klitzke email: philologos14@gmx.de > === Subject: Re: Indefinite numbers of arguments in a function > Hello everybody, > Is it possible to define a function in Mathematica, where the numbers of > arguments does not matter? I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I can > call the function with five arguments (for example > Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can > define for ever number of arguments a function like that: > MyPlus[a_,b_]:=a+b > MyPlus[a_,b_,c_]:=a+b+c > MyPlus[a_,b_,c_,d_]:=a+b+c+d > MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e I also know that I can create a list as one argument: MyPlus[list_List] := ( > m = 0; For[n = 1, n < Length[list] + 1, n++, m += list[[n]] ]; > m > ) But since there are functions like Plus, there has to be a way to define > those kind of functions. Search for patterns or pattern matching in the documentation. _ is a pattern that matches a single expression. __ can match one or more expressions: myPlus[args__] := Plus[args] === Subject: Re: Indefinite numbers of arguments in a function > Hello everybody, > Is it possible to define a function in Mathematica, where the numbers of > arguments does not matter? I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I can > call the function with five arguments (for example > Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can > define for ever number of arguments a function like that: > MyPlus[a_,b_]:=a+b > MyPlus[a_,b_,c_]:=a+b+c > MyPlus[a_,b_,c_,d_]:=a+b+c+d > MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e I also know that I can create a list as one argument: MyPlus[list_List] := ( > m = 0; For[n = 1, n < Length[list] + 1, n++, m += list[[n]] ]; > m > ) > But since there are functions like Plus, there has to be a way to define > those kind of functions. I would be very glad, if someone could give me his advice. > Patrick Klitzke email: philologos14@gmx.de Any symbol can have attributes which control how it behaves. The attribute you are looking for is Orderless: In[3]:= SetAttributes[fff,Orderless] In[6]:= fff[1,2,3,4]==fff[2,4,3,1] Out[6]= True How would you know? Check the attributes of Plus and see which fits, if in doubt, look them up in the documentation: In[2]:= Attributes[Plus] Out[2]= {Flat,Listable,NumericFunction,OneIdentity,Orderless,Protected} hth, albert === Subject: Quantile and InverseCDF (* Version 6.0.2 for Mac PPC *) I thick I am missing something obvious: The documentation for InverseCDF says: For a discrete Distribution dist the inverse CDF at q ist the largest integer x such CDF[dist,x]<=q. But I get binom=BinomialDistribution[20,0.3] InverseCDF[binom,0.5] ---> 6 Quantile[binom,0.6] ---> 6 CDF[binom,7] ---> 0.772... CDF[binom,6] ---> 0.608... CDF[binom,5] ---> 0.416... so the quantile ist the smallest integer such CDF[dist,x]>=q ?? Gruss Peter -- ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-== Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de === Subject: Re: Any One have an idea? It's nicer to replace that ShowGraph expression by the following expression, which shows the tour evolving in time: AnimateGraph[g, path, HighlightedEdgeColors -> Red] (By the way, Mathematica will seem to complain about the option HighlightedEdgeColors -> Red there by highlighting it in red, as if it were a syntax error. But of course it's not. Evidently it's a SyntaxInformation oversight.) >> Does anyone have any idea how to do or come up with the knight's tour > problem. (* Ver 6.01 *) > Needs[Combinatorica`] g = KnightsTourGraph[8, 8]; > path = Partition[HamiltonianCycle[g], 2, 1]; ShowGraph[Highlight[g, {path}, HighlightedEdgeColors -> Red]] ----- Original Message ----- > === > Subject: Any One have an idea? >> Does anyone have any idea how to do or come up with the knight's tour > problem. Please give me some idea how to do it! >> The program is used a random number to select a starting position for the > knight, and select the next position by selecting one of the available > positions at random. When the knight reaches a position from which the > number of the last possible available positions, the tour is finished. -- 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 fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: If Integrate returns no result, can we conclude that no On Apr 17, 9:01 pm, David W. Cantrell terms of elementary functions such as exponentials, logarithms and > trigonometric functions. In fact, if you give an integrand that > involves only such elementary functions, then one of the important > capabilities of Integrate is that if the corresponding integral > can be expressed in terms of elementary functions, then Integrate > will essentially always succeed in finding it. >http://reference.wolfram.com/mathematica/tutorial/IntegralsThatCanAnd..= . How precise is this? Can one rely on this information? > I suppose that depends on the definition of essentially. ;-) Is it really > true that if Mathematica cannot integrate an expression made up of > elementary functions, then no closed-form result exists? > No. Consider, for example, > In[9]:= Integrate[D[x Sin[x^ArcSin[x]], x], x] > Out[9]= Integrate[x^(1 + ArcSin[x])*Cos[x^ArcSin[x]]*(ArcSin[x]/x + >> Log[x]/Sqrt[1 - x^2]) + Sin[x^ArcSin[x]], x] > which was done in Versionn 6.0.2 under Windows XP. > This is not an elementary function (as far as the Risch algorithm > is concerned). The class of elementary functions consists of rational functions, > exponentials, logarithms, trigonometric, inverse trigonometric, > hyperbolic, and inverse hyperbolic functions, the solutions of a > polynomial equation whose coefficients are elementary functions) and > any finite nesting (composition) of elementary functions. It does > not include the power of an elementary function to another > elementary function so your example actually shows the opposite of > what you seem to claim, namely that Mathematica has correctly > concluded (by using the Risch algorithm) that the integral cannot be > expressed in terms of elementary functions. Are you claiming that, for the purpose of the Risch algorithm, > Exp[Log[x] ArcSin[x]] is not considered to be an elementary function? I find that hard to believe! David As far as the Risch algorithm is concerned Exp[Log[x] ArcSin[x]] is certainly an elementary function. It's just a mixed algebraic/ transcendental function where the final extension is transcendental. IFAIK no CAS implements every branch of the Risch algorithm. I believe this is a result of not completely implementing the mixed transcendental/algebraic case where the final extension is algebraic, in this case one must solve a Risch differential equation over an algebraic curve. Bronstein developed an algorithm which computes the denominator of the solution, but one must compute Puiseux expansions about infinity to find the numerator. To quote Bronstein That step is now the last computational bottleneck to a complete effective integration algorithm for elementary functions. [Bronstein, M. The Risch Differential Equation on an Algebraic Curve, 1991] Others may comment that the Risch algorithm requires determining if an expression is equal to zero and thus we could never have a complete algorithm, this never seems to be a problem is practice... I was writing a Risch algorithm last year, it's no easy task ;-) Another important fact often overlooked is that the Risch algorithm often returns rather ugly solutions. I was playing around with this integral earlier: Consider the following integrand: Cos[x]/(1+Sin[x]) Using the usual old Risch algorithm we get: In[6]:= Risch[Cos[x]/(1+Sin[x]),x] Out[6]= -I x+2 Log[I+1/2 (-E^(-I x)+E^(I x))+1/2 (E^(-I x)+E^(I x))] Using the Tan[x/2] substitution then Risch on the resulting rational function: In[8]:= Risch[Cos[x]/(1+Sin[x]),x] Out[8]= 2 Log[1+Tan[x/2]]-Log[1+Tan[x/2]^2] Just for fun we see the parallel Risch algorithm succeeds here(in general it's far too slow): In[9]:= ParallelRisch[Cos[x]/(1+Sin[x]),x] Out[9]= -Log[Sec[x/2]^2]+2 Log[1+Tan[x/2]] IMHO the nicest solution comes from the substitution u = Sin[x] and the answer is Log[1 + Sin[x]]. Bhuvanesh, I'll try that integral tomorrow.... It looks like it was created by taking y = Sqrt[-1 + x + x^5], a rational function of x and y, say Y(x,y) and an integer A. Then computing Cancel[ D[Y,x] / (A Y) ]. If this is the case then it's really not trivial using Trager's algorithm, OTOH using Groebner basis and Czichowski's algorithm may have more success.... Sam === Subject: Re: A kernel, multiple notebooks, and Global? AES, I would like to put in a pitch for using the standard Mathematica package method and maybe even go further and learn something about documentation. I think one of the unstated assumptions here is that no one else is going to see your Mathematica work because all of the pertinent results will be Exported or copied out into non-Mathematica documents before being transmitted to a larger public. In that case why not organize the internal work in the way that seems most convenient to you? But another assumption that we can make for certain is that you have expert knowledge and a lot of experience in optical fibers. You also have done, and will do a lot of work in organizing the theory and calculation methods for the field. This is valuable stuff! So why not make it available to others in the Mathematica format with all of its advantages of dynamics and interactivity. In addition to the final results, if you have worked out various algorithms, calculation and display routines these are valuable. Why not make them available to other people as Mathematica packages? If you follow the multiple notebook paradigm, you also have to devise some kind of organization for the notebooks. You have to remember that for WorkingNotebookA you need ModuleNotebooks a, c and f. But for WorkingNotebookB you need ModuleNotebooks a, b, and c. Pretty soon you are designing your own system, which is not the standard Mathematica system. People who might use your notebooks not only have to learn the standard system (because they might be doing other things as well) but they also have to learn your special system. Rule Number 1: WRI has put a lot of thought into designing a user interface. It work's fairly well. Be very wary of interposing your own interface. In the time it took you to devise your own system, you could have learned the standard package system. It is really not that difficult. A Mathematica package is just a simple particular form of notebook with Initialization cells. You just save it as an Auto Generated Package and that is all there is to it. If you organize your notebooks using Sections (and I wonder if using multiple notebooks is a substitute for using Sectional organization within a notebook?), then you can initially put your routines in a Routines Section. The notebook does not have to be 'visually large' because the Routines Section can usually be closed up. Other things should also be in Sections. (When I'm working on a particular derivation of development I put it in its own Section. If I don't especially like it or get stuck I usually mark it as Try 1, close it up, copy and paste it and work on a Try 2. When I finally get something I like I throw all the false steps away.) When you develop a routine in a working notebook, move it to the Routines Section and write a usage message for it and make it an Initialization cell. If you start a new working notebook, copy the Routines Section over. At some point, you will be convinced that some of the routines are in good shape for general use. Then move them to your OpticalFiber package. Then you will have one simple working structure. A single package and working notebooks that load the package. You or your readers don't have to look at any of the package code anymore. You may still have some things in your Routines Sections that haven't yet made it to the package. Documentation is another question, but again, if you have worked out good routines and methods they are really worth something to other people and deserve to be documented. (And in any case, I find that I am always forgetting how some of my own routines work and have to refer to my own documentation!) With a little cleverness the documentation can also serve as a set of test cases if you make changes to your routine. Working on documentation also helps to perfect a routine. Sometimes if it is difficult to explain and illustrate a routine one might wonder about it basic design. It's true that this takes time, but it's a focused and productive use of one's time. David Reiss has put up a good introduction to creating Version 6 documentation. http://www.scientificarts.com/worklife/notebooks/ and the Workbench application for documentation is coming along. Rule Number 2: Most users of Mathematica are pretty capable people. Turn your hard work into permanently useful and active knowledge for yourself and other people. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > I just wanted to mention this for the case that the OP asked this >> question because he is trying to track down a problem related to this. to say that, unless you do something to deliberately manipulate > contexts, a group of several simultaneously open notebooks can generally > be used as if they were all parts of one big notebook with one overall > global context. I didn't raise this question because of any problems I've encountered, > but rather to flush out any problems that might arise in the packages > without Packages approach that I'd like to start implementing for my > particular Mathematica style of use (and it looks like there needn't be > any such problems). This approach says, in essence, that I'm often working on 3 or 4 > different physical problems, with the currently active projects changing > from time to time (and old projects reviving from time to time). So, I'd like to keep all the materials associated with any given > project -- notes, references, other memos, graphics and artwork, > materials for publications resulting from the project == and, > especially, all the Mathematica notebooks for that project -- in a > separate > master folder for that project. Moreover, I'd like to have all the Mathematica accessories -- like any > packages or modules that do some major computational or display tasks > for that project -- be right there, in that same subfolder with the > primary notebooks for the project. A typical project -- a study of optical fiber propagation, let's say -- > generally has a limited and consistent set or glossary of primary > parameters and variables, set by the physics of the problem and the > conventional notation in the field, and thus easy to remember. So, > those quantities might as well all be global variables, used with the > same meaning in all the project notebooks. Suppose then that we might at different times want to do calculations > and display results on the modes of these optical fibers, or on their > propagation characteristics, or their thermal behavior, or on a > perturbation aspect of their behavior, or whatever. Rather than have one large, unwieldy notebook to do all these tasks, we > might better have a number of separate much smaller task notebooks that > are appropriately named (OpticalFiberModes.nb, etc) and that each do > one limited part of the overall project -- and then one modules > notebook (OpticalFiberModules.nb) that contains various common basic > function and equation definitions for the project, plus individual > display modules that create certain graphics or tabular displays of > results, plus computational modules that do some complicated iterative > numerical calculations -- in other words, any stuff that's lengthy or > that might go into a Package in other circumstances. At a given time, one might have only one or two task notebooks open, > plus the modules notebook (no real problem on a modern computer > screen). If you're polishing up a certain graphic display routine, you > edit this routine (probably as a Module[]) in the modules notebook; > execute the modules notebook to refresh it (which is very fast, since > this notebook does nothing but definitions); then jump to and run the > task notebook that calls it, and back again if further editing is needed. What are the virtues of this approach? * Each task notebook can be comparatively short and free of long module > definitions -- and thus can be navigated through quickly. * The modules notebook may be longer -- but if too long can be split > into setup modules, display modules, computational modules. * **You never have to learn how to create/edit/modify/store away > Packages! -- a great virtue, from what the questions I've seen > repeatedly posed in this group. * Maybe more important, you don't have to **remember** any of this > knowledge on how to work with Packages, nor do you have to remember how > you defined a Package, or how to use it, over possibly long interim > periods between active periods of a given project. All that knowledge > is right there at hand, in the modules notebook, if you go back later to > that project. * If you need one part of a project's modules notebook in another > project, you just copy it over into that project's modules notebook. I'm not attacking Packages here. It's just that they're necessarily > pretty sophisticated constructs (and have to be, if they're going to > function in the full Mathematica environment). Hence they have a > significant > learning curve (and a significant 'evaporation rate' if one moves away > from them for any period of time). The above approach seems like it may > work for me, and give me one fewer messy construct in Mathematica to > worry about. I don't see any serious downsides to this approach, although if any are > pointed out by readers -- if any -- of this lengthy screed, I'll > certainly have to learn from them. > === Subject: Why isn't Expand[] grouping terms by order? Consider this: In[19]:= Expand[ (1+a*x)*(1+b*x), x] 2 Out[19]= 1 + a x + b x + a b x How can I coax Mathematica to give me this, instead: 2 Want[19]= 1 + (a + b) x + a b x Why isn't Mathematica reporting the answer in terms of powers of x? === Subject: Re: Why isn't Expand[] grouping terms by order? because it doen not know that you look for orders of x and not of a or b .. and Collect[Expand[(1 + a*x)*(1 + b*x), x], x] will do what you want. > Consider this: In[19]:= Expand[ (1+a*x)*(1+b*x), x] 2 > Out[19]= 1 + a x + b x + a b x > How can I coax Mathematica to give me this, instead: 2 > Want[19]= 1 + (a + b) x + a b x Why isn't Mathematica reporting the answer in terms of powers of x? === Subject: Re: Why isn't Expand[] grouping terms by order? > Consider this: In[19]:= Expand[ (1+a*x)*(1+b*x), x] 2 > Out[19]= 1 + a x + b x + a b x > How can I coax Mathematica to give me this, instead: 2 > Want[19]= 1 + (a + b) x + a b x Collect[(1+a*x)*(1+b*x), x] > Why isn't Mathematica reporting the answer in terms of powers of x? When you ask mathematica to expand it expands, if you want it to collect, you need to tell it. It can't read your mind. hth, albert === Subject: Re: PolarPlot Hi Helen, >> just saw your reply. A coordinate system as you propose would assign >> more than one coordinate tuple to any point. Although I can see >> aplications in graphics (cycloids...), I do not think that this makes >> life easier for calculations. There are enough problems with unique >> maps, no need to make artificial ones. > I am not proposing anything. If you consult any calculus textbook, you will see that defining r as a directed distance (which may be negative) is *standard*. And as for non-unique coordinates, this would be the case for polar coordinates even if we only allowed non-negative r, since you can always add or subtract any multiple of 2Pi from the angle. -- Helen Read University of Vermont === Subject: Re: Numerical integration and list of points Nobody can help me ? Should I use Evaluate[] somewhere... TIA === Subject: Re: Numerical integration and list of points Sometimes using Integrate can be faster than using NIntegrate. With your example this is not true, if version 6.0 and higher is used: In[1]:= $Version Out[1]= 6.0 for Mac OS X x86 (32-bit) (June 19, 2007) In[2]:= f[x_] := Interpolation@Table[{x, Sin[x^2]}, {x, 0., 20, 20/20000}]; In[5]:= Integrate[f[x], {x, 0, 20}] ; // Timing Out[5]= {0.081263, Null} In[6]:= NIntegrate[Sin[x^2], {x, 0, 20}] ; // Timing Out[6]= {0.022355, Null} Anton Antonov Wolfram Research, Inc. > Try using Integrate instead ofNIntegrate. Integrate[] supports > InterpolatingFunction objects directly, so this will be much faster than > usingNIntegrate[]. (I found out that Integrate can do this only because your message Example: In[1]:= f = > Interpolation@Table[{x, Sin[x^2]}, {x, 0., 20, 20/20000}]; In[2]:= Integrate[f[x], {x, 0, 20}] // Timing > Out[2]= {0.25, 0.639816} Check result: In[3]:=NIntegrate[Sin[x^2], {x, 0, 20}] > Out[3]= 0.639816 (Indeed, NIntegrating this takes a very long time. I haven't had the > patience to wait for it to finish.) Szabolcs === I am not sure if this is a question or comment. I thought I should note the package, DaysBetween and DaysPlus. Timings are from an original iMac G5. Do[ DaysBetween[{2000, 3, 3}, {2002, 2, 2}];, {1000}]; // Timing Out[49]= {1.08407, Null} Do[ Out[50]= {5.39334, Null} In[56]:= Table[DaysPlus[{2000, 1, 1}, i], {i, 1000}]; // Timing Out[56]= {1.88357, Null} Out[57]= {2.75215, Null} I got a 100% speed-up by switching to the functions from the package. This is a puzzle, because the commands from the Calendar package would seem more general. If anyone has any insights on why this might be, that would be interesting. Otherwise I'm just putting the information out there, in case it is helpful to someone. Luci === Subject: Scaling Plot inside Row I am trying to control size of a Plot inside a Row that contains also some TableForm with selectable text. This Row is an output from my complicated program so I use Print[] to print it as output. I have tried the following (this is an example): plot=Plot[Sin[x],{x,0,6 Pi}]; matrix=TableForm[Table[10 i+j,{i,4},{j,3}]]; Print[Row[{plot,matrix},t]] All is fine but the plot is scaled down. I have tried to use Graphics[plot,ImageSize->1] but it does not work. How can I control size of the plot in the output? === Subject: Re: Scaling Plot inside Row ImageSize->1 an image a single pixel wide ? will be hard to see try plot = Plot[Sin[x], {x, 0, 6 Pi}, ImageSize -> 2000000]; matrix = TableForm[Table[10 i + j, {i, 4}, {j, 3}]]; Print[Row[{plot, matrix}, t]] > I am trying to control size of a Plot inside a Row that contains also > some TableForm with selectable text. This Row is an output from my > complicated program so I use Print[] to print it as output. I have > tried the following (this is an example): plot=Plot[Sin[x],{x,0,6 Pi}]; > matrix=TableForm[Table[10 i+j,{i,4},{j,3}]]; > Print[Row[{plot,matrix},t]] All is fine but the plot is scaled down. I have tried to use > Graphics[plot,ImageSize->1] but it does not work. > How can I control size of the plot in the output? > === Subject: Re: Scaling Plot inside Row > I am trying to control size of a Plot inside a Row that contains also > some TableForm with selectable text. This Row is an output from my > complicated program so I use Print[] to print it as output. I have > tried the following (this is an example): plot=Plot[Sin[x],{x,0,6 Pi}]; > matrix=TableForm[Table[10 i+j,{i,4},{j,3}]]; > Print[Row[{plot,matrix},t]] All is fine but the plot is scaled down. I have tried to use > Graphics[plot,ImageSize->1] but it does not work. > How can I control size of the plot in the output? ImageSize expects the size in pixels as value, setting it to 1 usually gives rather small pictures :-). The following works as expected for me: plot = Plot[Sin[x], {x, 0, 6 Pi}, ImageSize -> 300]; matrix = TableForm[Table[10 i + j, {i, 4}, {j, 3}]]; Print[Row[{plot, matrix}, t]] hth, albert === Subject: Re: If Integrate returns no result, can we conclude that no closed-form > .. >> A completely implemented Risch algorithm will either return an >> explicit answer for an integral that can be evaluated in terms of >> elementary functions or determine that no such answer can be >> given. ... >> Andrzej Kozlowski Is this a theorem? > Matthias Bode. > Yes. Actually quite many. The Risch's theorem, that I know, gives conditions for an integral of a purely algebraic function to be elementary and an algorithm for finding it or deciding that it does not exist. There is also such an algorithm for a function which is an element of the field K[t1,t2,...tn], where each tk is either an exponential or a logarithm of a function in K[t1,t2,...,t(k-1)]. Again, there is a theorem and an effective procedure. (However, even if fully implemented these procedures may actually by impossible to carry out in a reasonable time). But one can show, using them that things like Integral[Log[Log[x]],x] cannot be expressed in terms of elementary functions. Then, there is the mixed case, where you need both algebraic and exponential or logarithmic extensions. For example, the function ArcSin[x] belongs to a mixed extension, since TrigToExp[ArcSin[x]] (-I)*Log[I*x + Sqrt[1 - x^2]] If I understand it correctly, there is also an effective procedure due to Manuel Bronstein for dealing with general mixed cases (and it is also a theorem) but it is much later work then Risch's (c.f. my comments in a reply to a post by David Cantrell) and does not seem to be implemented. In fact I am not sure about this since I have never been interested in integrating non-algebraic functions so perhaps someone else can confirm if I have got this right. Andrzej Kozlowski === Subject: Re: If Integrate returns no >> .. > A completely implemented Risch algorithm will either return an > explicit answer for an integral that can be evaluated in terms of > elementary functions or determine that no such answer can be given. > ... > Andrzej Kozlowski >> Is this a theorem? >> Matthias Bode. Yes. Actually quite many. The Risch's theorem, that I know, gives > conditions for an integral of a purely algebraic function to be > elementary and an algorithm for finding it or deciding that it does not > exist. There is also such an algorithm for a function which is an > element of the field K[t1,t2,...tn], where each tk is either an > exponential or a logarithm of a function in K[t1,t2,...,t(k-1)]. Again, > there is a theorem and an effective procedure. (However, even if fully > implemented these procedures may actually by impossible to carry out in > a reasonable time). But one can show, using them that things like > Integral[Log[Log[x]],x] cannot be expressed in terms of elementary > functions. Then, there is the mixed case, where you need both algebraic > and exponential or logarithmic extensions. For example, the function > ArcSin[x] belongs to a mixed extension, since TrigToExp[ArcSin[x]] > (-I)*Log[I*x + Sqrt[1 - x^2]] If I understand it correctly, there is also an effective procedure due > to Manuel Bronstein for dealing with general mixed cases (and it is > also a theorem) but it is much later work then Risch's (c.f. my > comments in a reply to a post by David Cantrell) and does not seem to > be implemented. In fact I am not sure about this since I have never > been interested in integrating non-algebraic functions so perhaps > someone else can confirm if I have got this right. Andrzej Kozlowski It might be implemented in AXIOM. I gather that much of Bronstein's work, as well as related indefinite integration algorithmics due to Barry Trager and James-not-John Davenport, is in AXIOM. Very likely implemented by those people themselves. As for Risch, what counts as elementary exp-log-powers is a bit tricky. Exp[x] and Log[x+1] count. Exp[1/2*Log[x+1]] does not count (it's algebraic). As best I understand, it is this last sort of thing for which work of Davenport, Trager, and Bronstein is required. Daniel === Subject: Re: If Integrate returns no result, can we conclude that no closed-form March 2008, Volume 50, Number 1, pages 155-157 on Manuel Bronstein's book: Symbolic Integration. I. Transcendental Functions. Second Edition, Springer-Verlag, Berlin, 2005 by Sam Blake. It discusses Risch integration and other approaches to symbolic integration. Paul Peterson === Subject: Comments on the .m file editor As essentially a new user of Mathematica since v6, I'd like to share a couple of comments about using Mathematica itself to write .m packages directly. I'm only using v6.0.1 because I can't afford the bug-fix update right now, so a couple of these comments may no longer be relevant. Firstly, the positives: It's great to be able to write code in an editor that explicitly understands the syntax. Brace matching and selection are good, and syntax colouring is excellent. Being able to write comments in outline mode is also great; especially with input cells that aren't part of the package but allow you to execute code; this makes testing and code exposition very convenient because it can be done inline with the code itself. Now, the negatives. The first complaint is more ignorance than anything: I've got no idea how to use the debugger. It's great that it's there, but I don't understand how it's supposed to be used. Are there any tutorials on this feature? Next: the editor *really* needs to make up its mind whether it's going to support nice Mathematica symbols or not. It's ridiculous that typing -> gives you a nice arrow, but then closing and re-opening the file gives you the literal ascii. Worse, typing a complex expression involving Greek letters and subscripts and accents looks fine to start with but then turns into an unreadable mess when re-opening the package. Since Mathematica can understand the FullForm in package files, I can't see the harm in displaying it nicely in the .m file editor. Similarly, the lack of nice spacing in the typesetting of the code is a shame and makes packages look uglier -- usually requiring extra whitespace (and effort) to be readable. Finally, the editor doesn't like code that has comments inserted mid-way through. For example, paste this into a file test.m: (* ::Package:: *) code[hello, (* ::Text:: *) (*some explanation*) there] Open it in Mathematica, then select all, cut, and paste (this procedure emulates you typing in those lines manually). Close and reopen the file and you'll see that Mathematica has inserted two blank lines in the code. Yuck. Furthermore, this sort of construction kills syntax colouring, which is a big shame. It also breaks the Run Package button, which tries to evaluate the package cell by cell (instead, it should simply execute `< I want to define a matrix valued function such as the following (in > LaTeX lingo): $$ > X(0)=Id, > X(n)=prod_{i=0}^{n-1} (Id + f[i] A) > $$ where A and f have already been defined and Id is the identity matrix > of appropriate size. I tried the following: Id=IdentityMatrix[2]; > Phi[0]:=Id; > Phi[n_]:= Product[Id + f[i] A,{i,0,n-1}] However, Phi[3] and (Id+f[2]A).(Id+f[1]A).(Id+f[0]A) do not agree. Any help around this would be appreciated. > === Subject: Re: EdgeRenderingFunction to produce edge I believe this method fails to preserve vertex coordinates from an original Combinatorica Graph[...] object in case one changes the vertex labels to, say, letters. For example: g = SetEdgeLabels[SetVertexLabels[Wheel[4], Characters[1234]], Characters[defabc]]; GraphPlot[torules[g], EdgeLabeling -> True, VertexLabeling -> True, VertexCoordinateRules -> getcoords[g]] ... If you want to use my first method and maintain the vertex locations, > then you need to include that information in the call to GraphPlot. Here is a function that creates the usual rule structure that GraphPlot > expects from a Combinatorica graph (with vertex and edge labels): torules[Graph[edges_, vertices_, ___]] := Module[ > {vrules}, > > vrules = DeleteCases[ > Thread[Range[Length[vertices]] -> (VertexLabel /. > vertices[[All,2 ;;]])], > _ -> VertexLabel > ]; > Replace[ > Transpose[{Rule @@@ (edges[[All,1]] /. vrules), EdgeLabel /. > edges[[All,2 ;;]]}], > {a_, EdgeLabel} -> a, > {1} > ] > ] Here is a function that extracts coordinates from a Combinatorica graph: getcoords[Graph[edges_, vertices_, ___]] := > Thread[Rule[Range[Length[vertices]], vertices[[All, 1]]]] So, let's create a graph with edge and vertex labels: g = SetEdgeLabels[SetVertexLabels[Cycle[3], {a, b, c}], {x, y, z}]; Now, we'll use GraphPlot to view the graph: GraphPlot[torules[g], EdgeLabeling->True, VertexLabeling->True, > VertexCoordinateRules->getcoords[g]] -- 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 fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: Possible bug in WAV export The sound in Mathematica and the sound from the exported WAV file > (using some unknown player) seem the same to me. I'm using > V6.02 on a XP box. I experimented some more and it turns out that the problem is not > limited to WAV (it is present with FLAC and AIFF too). However, the > problem only appears randomly, and not in each evaluation. The > following command does not always give the same result: ImportString[ > ExportString[ > Play[Sum[Sin[2 Pi 440 k t], {k, 1, 4}], {t, 0, 1}, > SampleRate -> 44100, SampleDepth -> 16], WAV], WAV] In about 20 or so evaluations I always get a few incorrect results. > It is not even necessary to play the sound---it is possible to see the > difference by looking at the spectra: Table[ImportString[ > ExportString[ > Play[Sum[Sin[2 Pi 440 k t], {k, 1, 4}], {t, 0, 1}, > SampleRate -> 44100, SampleDepth -> 16], WAV], WAV], > {20}] Can anyone else reproduce this problem? It is very strange that the > result is not deterministic. Any ideas why this might happen? To demonstrate that this unbelievable thing really happens, here's an > another example, together with the result. Note that the very same > command returns different results in subsequent evaluations: In[1]:= > Table[ > Total[#[[1, 1, 1]]] &@ > ImportString[ > ExportString[ > Play[Sum[Sin[2 Pi 440 k t], {k, 1, 4}], {t, 0, 1}, > SampleRate -> 44100, SampleDepth -> 16], WAV], WAV], > {20}] Out[1]= {0., 268.745, -0.752563, -0.756226, -0.756226, -2.99866, 0., > 0., -2.98279, 0., 0.756226, 341.993, 0., -0.752563, 0., 268.017, > -0.752563, 0., -2.2522, 0.} The small fluctuations could be explained by dithering, but any > reasonably precise result cannot have a sum of 342! The sound > function was constructed in such a way that the sum should be 0. A workaround is to use PlayRange -> All. Maxim Rytin m.r@inbox.ru === Subject: Debugger Sorry for the newbie post but I wanted to get started with the debugger in Mathematica 6.0 and I can't seem to find any documentation other than the simple description of the buttons. On a Mac (OSX dual core machine) I can't seem to get the interactive debugger to work. Can anyone point me toward some documentation examples or HOWTO simple examples to get me started. Paul B. === Subject: SparseArray memory usage An obvious advantage of SparseArray is that less memory is needed for sparse arrays. Unfortunately, this doesn't always seem to be the case, as I outline below sometimes almost as much memory is used as for an ordinary array. Can someone explain this, and hopefully tell me how to get around it? First, a situation which is fine: Starting with a clean kernel, I get the following memory usage for a 2 x 100million sparse array: In[1]:= MaxMemoryUsed[] MemoryInUse[] a=SparseArray[{{1,1}->1},{2,100000000}]; MaxMemoryUsed[] MemoryInUse[] Out[1]= 5826800 Out[2]= 6652184 Out[4]= 6927152 Out[5]= 6654624 Second, a situation which is not fine: I use the transposed array and memory usage explodes: In[1]:= MaxMemoryUsed[] MemoryInUse[] a=SparseArray[{{1,1}->1},{100000000,2}]; MaxMemoryUsed[] MemoryInUse[] Out[1]= 5826816 Out[2]= 6652184 Out[4]= 806653720 Out[5]= 406655144 === Subject: Re: Extending Integrate[] Integrate[] is, AFAIK a kernel function, written in C++, you can't access it. >> Hi Szabolcs, >> it looks like mathematica does not automatically distribute your rule= over >> Plus. This comes a bit as a surprise. But you can teach it. If you >> additionally give the following rule: >> Integrate[a_+b_,x_]:=Integrate[a,x]+Integrate[b,x] >> then your example works. Of course you also need linearity. Hi Daniel, > The problem with this approach is that it will prevent Integrate from > working correctly in certain cases. Here's an example: In[1]:= expr = D[x*f[x], x] > Out[1]= f[x] + x*f'[x] In[2]:= Integrate[expr, x] > Out[2]= x*f[x] In[3]:= Unprotect[Integrate] > Out[3]= {Integrate} In[4]:= Integrate[a_ + b_, x_] := Integrate[a, x] + Integrate[b, x] In[5]:= Integrate[expr, x] > Out[5]= Integrate[f[x], x] + Integrate[x*f'[x], x] 's suggestion, i.e. Integrate[d_. + c_.*Sin[Sin[a_. + b_. x_]], x_] := > c*Jones[a, x]/b + Integrate[d, x] /; FreeQ[c, x] appears to be reliable, but everything it does is still fully > implemented with plain old pattern matching. So my original > suspicion, that the internal algorithms of Integrate[] cannot use > these new definitions in any way, seems to be true. Szabolcs > === Subject: Re: List concatenation - two more methods, one truly fast > It would be nice if someone from Wolfram could comment on these timing > results. > I agree, but I fear that our wish lists will exceed the personnel resources at Wolfram. In the meantime, it would be nice to form a wiki with a timing stub with plots like: p1 = ListLinePlot[ Table[{2^n, Timing[poly = {}; Do[AppendTo[poly, p[i]], {i, 1, 2^n}]][[1]]}, {n, 1, 12}]] and p2 = ListLinePlot[ Table[{2^n, Timing[poly = {}; Timing[Do[poly[[i]] = p[i], {i, 1, 2^n}]][[1]]][[1]]}, {n, 1, 12}]] Show[p1, p2] Any volunteers? -- W. Craig Carter === Subject: Re: List concatenation - two more methods, one truly fast This result is fascinating - it is reasonable that all the solutions > based on appending lists work O(n^2), but the nested list approach > should not behave this way. If you repeat the timing, but without > defining p: n = 5000; poly = Table[0, {n}]; > Print[Timing[Do[poly = {poly, p[i]}, {i, 1, n}]; > poly = Flatten[poly]][[1]]]; I get 0.02 seconds rather than 11 seconds (I obviously have a slightly > slower machine. This means that the time depends crucially on what you > are accumulating. Consider the semantics of the operation: poly = {poly, p[i]} This will only be efficient if Mathematica 'knows' that the old value of > poly is already fully evaluated. As I understand it, Mathematica does > this using a hashing method, and my guess is that in this case the hash > table overflows and the ever growing expression gets repeatedly > evaluated - hence O(n^2). It would be nice if someone from Wolfram could comment on these timing > results. Incidentally, the following method works efficiently without requiring > the array size to be known in advance: n = 5000; poly = Table[0, {n}]; > Print[Timing[poly = Reap[Do[Sow[p[i]], {i, 1, n}]][[2, 1]]][[1]]]; David Baileyhttp://www.dbaileyconsultancy.co.uk Note that O(n^2) dependence is a killer for building long object lists. For example suppose I increase n to 200000 polygons. In FEM work that is a medium size plot. Building the Show[] list by one of the O(n^2) methods extrapolates to about 50000 seconds (14 hours) on my desktop G5. And I know that on that machine elapsed time is about 3 times that reported by Timing[]. Waiting 40+ hours for one plot is not exactly interactive speed. On the other hand a O(n) scheme would build it in less than a second. === Subject: NDSolve and vector functions Hello all, does anybody know a way to compute a vector valued function using NDSolve without explicitely specifying all vector components. Here is a simple example: Although NDSolve[{p'[t]==p[t],p[0]=={1,0}},p,{t,0,1}] works, NDSolve[{p'[t]==p[t]+{1,1},p[0]=={1,0}},p,{t,0,1}] does not work because p[t] in p[t]+{1,1} is treated as a scalar and the expression is evaluated to {1+p[t],1+p[t]} what is clearly not intended. Even in IdentityMatrix[2].p[t]+{1,1} IdentityMatrix[2].p[t] is treated like a scalar and added to the components of {1,1}. do I miss something??? Daniel === Subject: Re: function > Who can explain the behavior. THe derivative Abs[x] at x=.5 is well > defined and is equal to 1. In[1]:= D[Abs[x], x] Out[1]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[x] In[2]:= % /. x -> .5 Out[2]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[0.5] > First of all your statement is simply not true. Mathematica's symbolic D works in the complex plane and in the complex plane the derivative of Abs at 1 is not defined: Limit[(Abs[1 + t*I] - Abs[1])/t, t -> 0] 0 while I Limit[(Abs[1 + t ] - Abs[1])/t, t -> 0] 1 The symbolic derivative D automatically applies the chain rule, which explains why it gives you the answer you got (it returns Abs'[1] because it does not know what it should be). If you want to differentiate in the real sense, a non-analytic function at a point where it has a derivative you have several choices. One is to use numerical differentiation: f[x_?NumericQ] := Abs[x] f'[0.5] 1. Another is to use Refine before you differentiate: D[Refine[Abs[x], x > 0], x] /. x -> 0.5 1 another way is the above approach using limits. There are still other ways but this should be enough. Andrzej Kozlowski === Subject: Re: heat equation through different media/problem with constant flux > 2008/4/16 Luigi B : I am trying to solve the heat conduction problem in a sequence of > three media with different properties. For that I am using NDSolve > However, i still do not get a satisfactory result. Probably because I= > am not including the condition that at the interface between two medi= a > the heat flux is constant. How can I do this? I suspect your hypothesis is correct. I've never tried including a a > constant flux condition (kleft D[u[x],x]/.x->a == kright > D[u[x],x]/.x->a) into NDSolve. I'll be interested > to see if someone has a method. But, why not solve the equations in each of the three domains using > DSolve, and then enforce continuity of u and continuity of flux with > Solve to determine the solution symboilicaly. If the thermal > conductivity is uniform in each sublayer, this should be fairly > straightforward---I think you'll end up matching Fourier coefficients > at the interfaces. Yes, but how to do this? Do you have an example? Luigi > -- > W. Craig Carter === Subject: Re: heat equation through different media/problem with constant flux Èé Ìõéçé¬ õîæïòôõîá ôåìyour code is not readable and you do not specify what your [Eth]òïâìåis. Not knowig more I have to guess and my bet, considering the åòòïmessage, is, that the media properties change abruptly. If so, try ôï íïäåa softer change.Here is an example with hard change: ëÛøß[CapitalYAcute].bd[CapitalEth][ EAcute]åãå÷éóå[CapitalU Hat]ûû±¬ø.bc±[YAcute]¬ û.b2¬ø.bc.b2[YAcute]¬û.b2¬ø2 74.b3[YAcute]£¿ øåîä.bd.b3 æ.bdÔ¯®Î[CapitalADou bleDot]Óïìöå[CapitalUH at]ûÄÛÔÛ[OSl ash]¬ô[CapitalYAcute]¬ô[CapitalYAcute].bd.bd[EDoub leDot]Ûø ÄÛÔÛø[Not ]ô[CapitalYAcute]¬ûø¬.b2[YAcute][CapitalYAc ute]¬ÔÛø¬°[CapitalYAcute ].bd.bd±¬ÔÛ°¬ô [CapitalYAcute].bd.bd±«Óé îÛô[CapitalYAcute]¬Ô[CapitalUHat ]øåîä¬ô[CapitalYAcute].bd.bd[ PlusMinus][YAcute]¬Ô¬ûô¬°[N ot]·[YAcute]¬ûø¬°¬ø åî䣿Û[Capital UHat]±[CapitalYAcute][CapitalYAcute]» [CapitalEth]ìïô.b3Ä[CapitalU Hat]æÛø¬ô[CapitalYAcute]¬û[O Hat]¬°¬·£¿û[OSlas h]¬°¬øåîä[YAcute] áîthe same with soft change: ëÛøß[CapitalYAcute].bd[CapitalEth][ EAcute]åãå÷éóå[CapitalU Hat]ûû±¬ø.bc±[YAcute]¬ û±«¨ø[Hyphen]±[Copyri ght]¬ø.bc.b2[YAcute]¬û.b2¬ø.bc.b3 [YAcute]£¿ øåîä.bd.b3 æ.bdÔ¯®Î[CapitalADou bleDot]Óïìöå[CapitalUH at]ûÄÛÔÛ[OSl ash]¬ô[CapitalYAcute]¬ô[CapitalYAcute].bd.bd[EDoub leDot]Ûø ÄÛÔÛø[Not ]ô[CapitalYAcute]¬ûø¬.b2[YAcute][CapitalYAc ute]¬ÔÛø¬°[CapitalYAcute ].bd.bd±¬ÔÛ°¬ô [CapitalYAcute].bd.bd±«Óé îÛô[CapitalYAcute]¬Ô[CapitalUHat ]øåîä¬ô[CapitalYAcute].bd.bd[ PlusMinus][YAcute]¬Ô¬ûô¬°[N ot]·[YAcute]¬ûø¬°¬ø åî䣿Û[Capital UHat]±[CapitalYAcute][CapitalYAcute]» [CapitalEth]ìïô.b3Ä[CapitalU Hat]æÛø¬ô[CapitalYAcute]¬û[O Hat]¬°¬·£¿û[OSlas h]¬°¬øåîä[YAcute] èï[Eth]å ôèéó èåì[Eth]ó¬ Äáîéåì I am trying to solve the heat conduction problem in a sequence of three media with different properties. For that I am using NDSolve with my own grid. The code (without the 'tedious' definition of the time dependent boundary conditions) is: !(NDSolve[{$B_(B_t u[x, t] == alfa[x]*$B_(B_{x, 2}u[x, t], u[ x, 0] == TavSInt[0] + (TavRInt[0] - TavSInt[0])/L* x, u[0, t] == TavSInt[ t], ([L, t]) == TavRInt[ t]}, u, {x, 0, L}, {t, 0, tmax}, MaxSteps -> 50000, Method - .be.be {, -> { , -> {mygrid}}}]) However, i still do not get a satisfactory result. Probably because I am not including the condition that at the interface between two media the heat flux is constant. How can I do this? Luigi === Subject: Re: Reduce and Indeterminate > What a delightful sense of humor! > Yes, a statement can be true, it can be false, or it might not make >> any sense. If it does not make sense, then considering it false is >> just as bad as considering it true. So, if I don't understand this sentence, it is of no use. If I do > understand it, then it is superfluous. Very good indeed! > Actually, all Mathematica's predicate functions (those whose name's end with Q) will return False whenever they cannot decide that it is True. So you can get: TrueQ[2+2 = 4] False Andrzej Kozlowski (I notice also that Hungarian names are as hard to remember as Polish ones ;-) ). === Subject: Re: Reduce and Indeterminate What a delightful sense of humor! > Yes, a statement can be true, it can be false, or it might not make > any sense. If it does not make sense, then considering it false is > just as bad as considering it true. > So, if I don't understand this sentence, it is of no use. If I do understand it, then it is superfluous. Very good indeed! === Subject: Defining derivatives Hello All, does anybody know how to define symbolic derivatives. E.g.: f[x_]:=f1[x]; f'[x_]:=f2[x]; this does not work because f on the lefthand side is evaluated. To prevent this (do not forget to remove f before redefining it): f[x_]:=f1[x]; HoldPattern[f'[x_]]:=f2[x]; this gives no message, but f'[x] returns f1[x] instead of f2[x]. The same thinhg happens when you change the sequence of definitions: f'[x_]:=f2[x]; f[x_]:=f1[x]; Further, where is the information about derivatives stored? thank's a lot, Daniel === Subject: Re: Indefinite numbers of arguments in a function f[x__] := {x}.{x}; f[1, 2] 5 f[1, 2, 3, 4] 30 Bob Hanlon > Hello everybody, > Is it possible to define a function in Mathematica, where the numbers of > arguments does not matter? I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I can > call the function with five arguments (for example > Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can > define for ever number of arguments a function like that: > MyPlus[a_,b_]:=a+b > MyPlus[a_,b_,c_]:=a+b+c > MyPlus[a_,b_,c_,d_]:=a+b+c+d > MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e I also know that I can create a list as one argument: MyPlus[list_List] := ( > m = 0; For[n = 1, n < Length[list] + 1, n++, m += list[[n]] ]; > m > ) > But since there are functions like Plus, there has to be a way to define > those kind of functions. I would be very glad, if someone could give me his advice. > Patrick Klitzke email: philologos14@gmx.de > === Subject: Re: A Problem with Simplify > Daniel Lichtblau: >> Sorry, I should have stated the situation more clearly. >> Yes, the antiderivatives you see have singularities at the parameter >> value in question (in all cases, when a is 1). Hence the results you >> show above. What I should have said is that one can get these >> obtain definite integrals a la Newton-Leibniz. Here is a standard >> simple >> example (modified slightly so as to have a->1 as the bad value). >> In[22]:= InputForm[i1 = Integrate[x^(-a),x]] >> Out[22]//InputForm= x^(1 - a)/(1 - a) >> Certainly it blows up as a->1. >> In[23]:= Limit[i1, a->1] >> Out[23]= -Infinity >> In[24]:= Limit[i1, a->1, Direction->1] >> Out[24]= Infinity >> But if we take a pair of values for x, say 2 and 3, to evaluate the >> definite integral, we in fact get the expected/desired logarithm >> result >> in the limit as a->1 (and independent of direction). >> In[27]:= InputForm[Limit[(i1/.x->3)-(i1/.x->2), a->1]] >> Out[27]//InputForm= Log[3/2] >> In[28]:= InputForm[Limit[(i1/.x->3)-(i1/.x->2), a->1, Direction->1]] >> Out[28]//InputForm= Log[3/2] >> To see that this really is reproducing the Fundamental Theorem of >> Calculus result (or at least doing a heckuva job to fool me), I'll >> show >> this instead as a definite integral from x0 to x. >> In[29]:= InputForm[Limit[i1 - (i1/.x->x0), a->1]] >> Out[29]//InputForm= Log[x] - Log[x0] >> I believe most of your examples will also behave fine when >> processed in >> this way. The Cos[a*z]/Sin[z] integrand might be an exception, but >> that >> indicates a limitation of Limit rather than a bug in Integrate. >> Depending on whether you give symbolic (z,z0) or exact numeric (3,2) >> input to Limit it either returns a complicated, but seemingly correct >> result, or else unevaluated. >> Daniel Lichtblau >> Wolfram Research same way as there is an alternative to Solve (the function Reduce) > that carefully keeps track for all conditions for the all partial > answers, there should be also an alternative to Integrate that also > keeps track for conditions and gives the all partial answers! I am > grieved deeply that the alternative does not exists for this case! In[1]:= Reduce[1/(a*x)==1,x] > Out[1]= a!=0&&x==1/a This example is the true mathematics! > Indeed. However, there would be two problems. First, someone would have to devise suitable algorithms and implement them. This may not be totally impossible, but it would certainly take a lot of effort. But then, we would see the second problem. This ideal integrate would run for ever on almost any non-trivial problem. You would get nice mathematical answers to trivial ones, which would make you feel good, and no answers to non-trivial ones, which would probably make you a annoyed enough to complain (to the MathGroup?). Would that be a good way to use the time and effort of programmers and your own money? As for Reduce - you should try it a little more on harder problems than the one you have just presented. It uses some very beautiful and powerful algorithms like Cylindrical Algebraic Decomposition but they have exponential or in this case double exponential complexity (in the number of variables) so if you it try on something with more than 3 variables involved you will see what I mean. Given the choice between a program that does everything in the spirit of true mathematics but can only sole trivial problems that can be done by hand and one that gives only generic solutions but can deal with cases that would take you a hundred years to do by hand, which one would you choose? Andrzej Kozlowski === Subject: Re: A Problem with Simplify Daniel Lichtblau: > Sorry, I should have stated the situation more clearly. Yes, the antiderivatives you see have singularities at the parameter > value in question (in all cases, when a is 1). Hence the results you > show above. What I should have said is that one can get these > obtain definite integrals a la Newton-Leibniz. Here is a standard simple > example (modified slightly so as to have a->1 as the bad value). In[22]:= InputForm[i1 = Integrate[x^(-a),x]] > Out[22]//InputForm= x^(1 - a)/(1 - a) Certainly it blows up as a->1. In[23]:= Limit[i1, a->1] > Out[23]= -Infinity In[24]:= Limit[i1, a->1, Direction->1] > Out[24]= Infinity But if we take a pair of values for x, say 2 and 3, to evaluate the > definite integral, we in fact get the expected/desired logarithm result > in the limit as a->1 (and independent of direction). In[27]:= InputForm[Limit[(i1/.x->3)-(i1/.x->2), a->1]] > Out[27]//InputForm= Log[3/2] In[28]:= InputForm[Limit[(i1/.x->3)-(i1/.x->2), a->1, Direction->1]] > Out[28]//InputForm= Log[3/2] To see that this really is reproducing the Fundamental Theorem of > Calculus result (or at least doing a heckuva job to fool me), I'll show > this instead as a definite integral from x0 to x. In[29]:= InputForm[Limit[i1 - (i1/.x->x0), a->1]] > Out[29]//InputForm= Log[x] - Log[x0] I believe most of your examples will also behave fine when processed in > this way. The Cos[a*z]/Sin[z] integrand might be an exception, but that > indicates a limitation of Limit rather than a bug in Integrate. > Depending on whether you give symbolic (z,z0) or exact numeric (3,2) > input to Limit it either returns a complicated, but seemingly correct > result, or else unevaluated. > Daniel Lichtblau > Wolfram Research same way as there is an alternative to Solve (the function Reduce) that carefully keeps track for all conditions for the all partial answers, there should be also an alternative to Integrate that also keeps track for conditions and gives the all partial answers! I am grieved deeply that the alternative does not exists for this case! In[1]:= Reduce[1/(a*x)==1,x] Out[1]= a!=0&&x==1/a This example is the true mathematics! === Subject: Re: financial chart with volumes With version 6, this is similar: Module[ {dateForm, high, highest, closing, low, lowest, volume, maxVolume, minVolume, adjustedVolume}, dateForm = {MonthShort, /, DayShort, /, Year}; highest = Max[high[[All, 2]]]; lowest = Min[low[[All, 2]]]; maxVolume = Max[volume[[All, 2]]]; minVolume = Min[volume[[All, 2]]]; adjustedVolume = {#[[1]], ((3*lowest - highest) + (highest - lowest) (#[[2]] - minVolume)/ (maxVolume - minVolume))/2} & /@ volume; Filling -> {1 -> {{3}, Red}, 4 -> {(3*lowest - highest)/2, {{Thick, Darker[Green, .6]}}}}, GridLines -> Automatic, PlotMarkers -> {, Style[-, {Bold, Black}], , }, FrameLabel -> {None, Price in Dollars ($)}, PlotLabel -> FinancialData[company, StandardName] <> ( <> FinancialData[company, Symbol] <> ) Common Stock, <> - <> ImageSize -> 500]]; Bob Hanlon > are there examples to plot such chart ? > http://www.wolfram.com/solutions/finance/images/fibonarcs.gif (the picture is from here: http://www.wolfram.com/solutions/finance/features.html > ) > === Subject: Question about OneIdentity (Scroll down for the actual question) I never really understood Flat and OneIdentity, and unfortunately documentation about them is scarce. OneIdentity is an attribute that can be assigned to a symbol f to indicate that f[x], f[f[x]], etc. are all equivalent to x for the purpose of pattern matching. OneIdentity has an effect only if f has attribute Flat. ** Some comments: There is also an example, listing the Attributes of Times and showing that Times[a] evaluates to a. However, this is misleading because this behaviour cannot be caused by Times's attributes: In[1]:= Attributes[f] = Attributes[Times] Out[1]= {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected} In[2]:= f[a] Out[2]= f[a] If we assign the same attributes to f, f[a] will not evaluate to a. Was the technical writer also confused, or is the example supposed to illustrate something different than what I understood? ** And now the actual question: According to the text in the docs (f[x] is considered equivalent to x in pattern matching) I would expect MatchQ[1, f[1]] to give True after evaluating SetAttributes[f, {Flat, OneIdentity}]. But it gives False. ** The application: This came up in the following application: fun[HoldPattern@Plus[terms__]] := doSomething[{terms}] This function should handle a single term, too. Of course, there are workarounds, but I couldn't come up with anything as simple as the pattern above (which unfortunately does not work). === Subject: Does Mathematica really need more printed, introductory documentation? In response to Andrzej Kozlowski's comment > Judging by quite many ordinary users I known, the views you have been > expressing, particularly those on the need for printed software manuals > rather make you a memeber of a minority, and moreover a rather > rapidly declining one. I for one, . . . Does Mathematica really need printed, more introductory level documentation (aka books, or manuals) to add to its excellent, but less readable, online documentation? Let's take an experimental or reality-based approach to this question (however much that approach may be out of favor with our current administration in Washington . . .) Adobe Illustrator is, in my opinion anyway, an excellent piece of technical software, comparable in quality and usefulness and at least somewhat comparable in technical complexity, to Mathematica. There's probably a sizable overlap --- or at very least, a very sizable _potential_ market overlap --- between Illustrator and Mathematica users (new graphics commands that are very Illustrator-like have in fact been added in 6.0). Both programs have something of an initial learning curve for ordinary users; both have excellent detailed online reference documentation. Mathematica is, I would judge, actually substantial more complex and requires more learning for an average individual than does Illustrator. On my Mac, Illustrator 11 is 75 MB for the app itself, plus another 75 MB of supplemental stuff. I didn't try to dig inside the Mathematica package, but it's over 1 GB in my Applications folder, plus whatever additional material is stuffed away elsewhere on my HD. Illustrator manuals tend to be 300 to 500 pages; the Mathematica Book for v5 was just under 1500. Mathematica users, especially less experienced ones, might need more forms and varieties of documentation, that Illustrator users. So, to get some idea what sort of introductory printed books and manuals might be useful for Mathematica, we might ask: what sort of introductory printed books and manuals are readily available, right now, for Illustrator? (Noting again that Illustrator also has good, well organized, readily accessible online documentation, Help files, and tutorials --- along with helpful user forums on its web site.) A quick look at amazon.com then brings up a list of at least twelve (12) such introductory books or manuals on Illustrator (list appended below). All of these books are currently available in stock on amazon (and three are on my bookshelf) --- as compared to _none_ (as yet, anyway) for Mathematica 6. At least half of these Illustrator manuals can be identified as current editions of earlier versions that were published for earlier versions of Illustrator. In other words, earlier versions apparently sold well enough that authors were willing to write and publishers were willing to bring out 2nd, 3rd, even 4th editions of these manuals, updated for the current version of Illustrator. Or in other words, for me anyway: The experimental evidence is that these books _clearly meet user needs_, sufficiently so that authors are willing to invest their energies in writing them; publishers publish them; and users buy them, including more than once; Should Wolfram maybe recognize this point? * Adobe Illustrator CS3 Classroom in a Book by Adobe Creative Team (2007) $35 * The Adobe Illustrator CS3 Wow! Book by Sharon Steuer (2007) $24 * Adobe Illustrator CS3 How-Tos: 100 Essential Techniques by Karlins and Hopkins (2007) $10 * Real World Adobe Illustrator CS3 by Mordy Golding (2007) $20 * Illustrator CS3 Bible by Ted Alspach ( 2007) $25 * Adobe Illustrator for Fashion Design by Susan Lazear (2008) $35 * Fashion Designer's Handbook for Adobe Illustrator by Centner and Vereker (2007) $50 * Illustrator CS3 for Windows and Macintosh (Visual QuickStart Guide) by Weinmann and Lourekas (2007) $20 * Adobe Illustrator CS3 Revealed by Chris Botello (Aug 31, 2007) $45 * Best Practice: The Pros On Adobe Illustrator by Toni Toland (Aug 16, 2006) $35 * Adobe Illustrator CS2 Revealed, Education Edition by Chris Botello (2005) $40 === Subject: TimeConstrained and returning a partial answer The following came up on sci.math.symbolic: Among the examples on the doc page of TimeConstrained there is one where a partial (less precise) answer is returned even if the calculation cannot be finished within the time constraint. I was wondering if there is a way to create user-defined functions with this behaviour. I found two relevant functions in the docs: AbortProtect and CheckAbort. Here's a small test program: AbortProtect@CheckAbort[ x = 0; Do[Pause[.1]; x++, {100}]; x, x] This program will return an answer even if the calculation is aborted with Alt+. (or the menu item Evaluation -> Abort evaluation). Now let us try to use it with TimeConstrained: TimeConstrained[ AbortProtect@CheckAbort[ x = 0; Do[Pause[.1]; x++, {100}]; x, x], 1 ] // AbsoluteTiming Unfortunately this always runs for 10 full seconds, and then returns $Aborted (i.e. the worst possible thing happens: the calculation is not stopped after 1 sec, but no answer is returned.) ** Question: How can this program be modified so that TimeConstrained will be able to stop it after 1 sec, and it will still return an answer? Note: I experimented a little with the example from the docs, and I cannot reproduce the result that is presented there. If the calculation cannot be finished within the time constraint, $Aborted is returned: In[1]:= Timing[NDSolve[{Derivative[2][x][t] + x[t] == 0, x[0] == 1, Derivative[1][x][0] == 0}, x, {t, 0, 50000*Pi}, MaxSteps -> Infinity]] Out[1]= {5.578, {{x -> InterpolatingFunction[]}}} In[2]:= AbsoluteTiming[TimeConstrained[ NDSolve[{Derivative[2][x][t] + x[t] == 0, x[0] == 1, Derivative[1][x][0] == 0}, x, {t, 0, 50000*Pi}, MaxSteps -> Infinity], 5]] Out[2]= {5.0625`8.155910029718697, $Aborted} In[3]:= AbsoluteTiming[TimeConstrained[ NDSolve[{Derivative[2][x][t] + x[t] == 0, x[0] == 1, Derivative[1][x][0] == 0}, x, {t, 0, 50000*Pi}, MaxSteps -> Infinity], 6]] Out[3]= {5.984375`8.228563793480708, {{x -> InterpolatingFunction[]}}} === Subject: Re: delayed function assignment > I am trying to integrate the pdf of a chi-square mixture distribution. If I define the pdf as > pdf2[0] := .25 !(pdf2[x] := .5*((1/2^(1/ 2))/Gamma[1/2]) (x^(1/2 - 1)) [ExponentialE]^((-x )/ 2) + .25*(1/(2*Gamma[1])) [ExponentialE]^((-x )/2)) > I can then obtaing the cumulative distribution function symbolically as > In[14]:=!($Bi(Bpdf2[x] [DifferentialD]x) > Out[14]=!((-0.25`) 2.718281828459045`^((-0.5`) x) + 0.5` Erf[0.7071067811865476` @x]) > I can get numerical values using for example > In[31]:=!(1 - .25 - $Bi(B_0%12 pdf2[x] [DifferentialD]x) > Out[31]=0.000885691 > However if I try to define this as a function of the statistic obtained, say > !(cum2[x] := 1 - .25 - $Bi(B_0%x pdf2[t] [DifferentialD]t) > Then > In[33]:=cum2[9] > Out[33]=cum2[9] > Doesn't evaluate. What should I do to obtain the value as output. > Leigh Ïï[Eth]óI guess it is a while since I have used Mathematica and I æïïìéóèì thought I remembered the correct syntax for a delayed ôèsuggestions. Ìåéç === Subject: Re: FEM contourplotter - conversion completed > The translation of the Fortran IV 1966 finite element > contourplot to Mathematica is complete. Those interested in > that specialized topic may download a mini test version from http://caswww.colorado.edu/courses.d/IFEM.d/IFEM.Ch27.d/IFEM.Ch27.index.html Click on ContBandPlotterMini.nb link. Download and execute. > Self contained data. Tested so far under V4.1, 4.2 & 5.2. > Untested under V6.0 as my laptop in Spain lacks it. > Test plots take ~0.5 sec on 2.4 GHz MacBook Pro under 5.2. To run under 6.0 set DisplayChannel to Print (see top comment). The original Fortran code was roughly 9000 lines. Code was > typical write only thesis spaghetti, with over 1000 GOTOs > and (believe it or not) even a PAUSE statement! Mathematica > code is about 800 lines. Imperative procedural logic reflects > source, but could simplify later conversion to C or assembly. was reduced by deleting 6 element types out of 7, and > removing an alternative divide & conquer contourplotting > method. (D&C produces higher quality plots but is slower.) Code is slow (about 10K poly/sec) but that is enough for > coursework. A C or assembly version will be needed for FEM > production work (>=1M poly/sec) at the cost of portability. > Worst flaw is the shoddy contour value labeling, done in a > hurry. To see what's wrong, try resizing top plot with > mouse. Advice on how to fix that mess welcome. > I'm out of my element for finite elements. There are some regular posters on this group with considerable knowledge and maybe they will have good suggestions. As you took the trouble to get the code size reduced by a factor of 9, and removed spaghetti, I thought I would say what little I can in case it might help with the speed issues. (1) You might be losing time to effects of evaluating Graphics[], Line[], and other objects. You could instead use List[] in many places, and convert to whatever heads are needed only at the end. (2) You might gain speed by using machine reals consistently. It looks like you may be mixing reals and integers. Among other things, this will make it difficult to use packed arrays. (3) If you can arrange the code to use List objects and machine reals, there is a good chance you could use Compile on code in your For loops. My guess is this is where the most time is spent, and Compile could give this a nice boost. Daniel Lichtblau Wolfram Research === Subject: Re: Wolfram User Interface Research? > You seem to have completely missed my point. You complained about > abstruse Mathematica symbols such as @, /@, @@ etc. You seem to be > oblivious to the fact that 1. You never need to use them yourself. Each of them can be replaced > by a much more readable form. > 2. TeX uses special forms such as {,$, &, %, and plenty of even more > abstruse instructions. A typical fragment of TeX code looks like this: > Not sure I complained about these. In fact I routinely use a number of them --- but also find others in fact mysterious or arcane, for me anyway. What I did ask for --- would still ask for --- was, first of all the proper technical name for this class of non-alphabetical symbols or commands or operators in Mathematica? -- what they're called as a group, to distinguish them from alphabetical symbol names? --- so I could ask about them properly. Second and more important, I asked where, if anywhere, I could find (in a single place) a short list (like perhaps a half-dozen page or less) summarizing _all_ of these non-alphabetical operators, with a brief statement of what each of them does, or what it's good for --- so that I could identify ones I'd missed and decide which of these I might want to learn more about. I'd still be happy to have an answer to this query. And thirdly, I frankly think it would be an interesting exercise in interface research --- and a _useful_ one for Wolfram's interface designers --- to have some systematic data on which of these non-alphabetical operators are heavily used and which are seldom used, by different categories of Mathematica users. I'd at least have an interest in that, out of pure curiosity. === Subject: Re: Coordinate readout from Graphics3D? > I thought I saw somewhere that one could read out coordinates from a > Graphics plot, according to the mouse position. I can't find it now, > and I don't see how it would work with Graphics3D. But anything would Steve Gray So I have a simpler question. I know I can see the options that are set for a particular 3D object typing Options[ ] around the object. This is particularly useful when I have rotated the object with the mouse. But when I right click on the object and then use the object inspector (ctrl-shift-o) and then choose Formatting, Expression Formatting, Graphics3D Box Options, a change viewpoint (which has lots of decimal places) is not completely visible.. Typing Options when can use the mouse seems clunky, but not if you cannot view the entire set of options. Any ideas? === Subject: Notebook[] Hi Everyone, I have a notebook related question. I have about 50 notebooks open on the screen with different titles. I want to select the notebooks with certain titles. I do have this working: Select[Notebooks[], StringMatchQ[(WindowTitle /. NotebookInformation[#]), temp] &] However, I want to take this a step further, and retrieve only those notebooks that are on the left side of my screen and close them. In other words, I somehow need to divide my monitor in half and select all the windows on the left side and close them by NotebookClose. I know of WindowMargins but I am not sure how to retrieve information: Options /@ Select[Notebooks[], StringMatchQ[(WindowTitle /. NotebookInformation[#]), temp] &] _____ _ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ === Subject: Re: financial chart with volumes (CORRECTION) My first response cut off the bottom of the volume lines rather than compressing the lines. Only change is calculation of adjustedVolume. ClearAll[financialChart]; Module[ {dateForm, high, highest, closing, low, lowest, volume, maxVolume, minVolume, adjustedVolume}, dateForm = {MonthShort, /, DayShort, /, Year}; highest = Max[high[[All, 2]]]; lowest = Min[low[[All, 2]]]; maxVolume = Max[volume[[All, 2]]]; minVolume = Min[volume[[All, 2]]]; adjustedVolume = {#[[1]], ((3*lowest - highest) + (highest - lowest) #[[2]]/ maxVolume)/2} & /@ volume; Filling -> {1 -> {{3}, Red}, 4 -> {(3*lowest - highest)/2, {{Thick, Darker[Green, .6]}}}}, GridLines -> Automatic, PlotMarkers -> {, Style[-, {Bold, Black}], , }, FrameLabel -> {None, Price in Dollars ($)}, PlotLabel -> FinancialData[company, StandardName] <> ( <> FinancialData[company, Symbol] <> ) Common Stock, <> - <> ImageSize -> 500]]; Bob Hanlon > With version 6, this is similar: > Module[ > {dateForm, high, highest, closing, low, lowest, > volume, maxVolume, minVolume, adjustedVolume}, > dateForm = {MonthShort, /, DayShort, /, Year}; highest = Max[high[[All, 2]]]; > lowest = Min[low[[All, 2]]]; > maxVolume = Max[volume[[All, 2]]]; > minVolume = Min[volume[[All, 2]]]; > adjustedVolume = {#[[1]], ((3*lowest - highest) + > (highest - lowest) (#[[2]] - minVolume)/ > (maxVolume - minVolume))/2} & /@ volume; Filling -> {1 -> {{3}, Red}, > 4 -> {(3*lowest - highest)/2, {{Thick, Darker[Green, .6]}}}}, > GridLines -> Automatic, > PlotMarkers -> {, Style[-, {Bold, Black}], , }, > FrameLabel -> {None, Price in Dollars ($)}, > PlotLabel - FinancialData[company, StandardName] <> ( < > FinancialData[company, Symbol] < ) Common Stock, < - < ImageSize -> 500]]; Bob Hanlon are there examples to plot such chart ? > http://www.wolfram.com/solutions/finance/images/fibonarcs.gif (the picture is from here: http://www.wolfram.com/solutions/finance/features.html > ) > === Subject: Transforming a polynomial into a trigonometric format tia sal2 Transforming a polynomial into a trigonometric format tia sal2 I'm using mathematica 6 and I have a polynomial and would like to convert it into a Trigonometric format. Is this possible? Example: I have a polynomial 0.00154991- 4.01371 x + 1.81197 x^2 + 8.00183 x^3 - 9.3462 x^4 How can I transform this into a trigonometric format Example: 0.00596679 Cos[6.98132 x] + 0.00358397 Cos[7.21403 x] + 2.25013 Sin[0.232711 x] - 4.51511 Sin[0.465421 x] Note: these aren't correct answers I just wanted to include and example tia sal2 === Subject: Common Multiple Value Question I am trying to solve this Common Multiple Value Question based on 2 sequences of values... This is both a Math question & also a question on how to apply this problem to Mathematica. However, please note I am trying to find BOTH Common Multiple Value, of each element in both lists AND maintaining the same proportion in the first list of elements. I will pose this problem in 2 ways. (i) Fractional sequence of values. (ii) Numerical sequence of values. Actually they are the same question, but I would like to be able to solve this in both the fractional & numerical form. (... And also solving this without using LCM - Lowest Common Multiple function .... as this is part of a bigger calculation & I will be using algebra.) (i) Fractional sequence of values - 1 pair. 3 elements in each. list1={2/3,2/3+1,2/3+2} list2={3/4,3/4+1,3/4+2} {2/3,5/3,8/3} {3/4,7/4,11/4} (ii) Numerical sequence of values - 1 pair. 3 elements in each. list3={2,5,8} list4={3,7,11} {2,5,8} {3,7,11} ( Apologies if this question is so simple... I have been trying to figure this out for a number of days ...) === Subject: Re: ? (*now Do and Table*) It occurs to me the proof that (n + 2)/6 is integer could be far simpler. That is, n is even, so n+2 is even. n is also a power of 10, so summing the digits of n+2 gives 3, hence n+2 is divisible by 3. (That's just the threes version of casting out nines.) Bobby > Your curious result was Clear[n, result] > result = Sum[i (i + 1)/2, {i, 1, 10^7}] 166666716666670000000 In general, the sum is Clear[k, result, n] > result = Sum[i (i + 1)/2, {i, 1, n}] 1/6 n (1 + n) (2 + n) If n is the kth power of 10, the factor n causes result to have k > trailing zeroes, and the factor (n+1) causes the repetition you noticed, > but it also requires (n+2)/6 to be an integer, which occurs when > Mod[10^k+2,6]==0. But, modulo 6, we see that 10 is congruent to 4, and 4 is idempotent: Mod[10, 6] 4 Mod[4^2, 6] 4 Union@Table[Mod[10^k, 6], {k, 100}] {4} As a consequence, the pattern you noticed will always appear when n is a > power of 10. Table[Mod[10^k, 6], {k, 100}] {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, > 4, > 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 , > 4, 4, > 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 , > 4, 4, > 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4} Oops! I almost forgot the final requirement, that (n+2)/6 < n. But > that's pretty obvious. Bobby >> Craig, >> Just a (tongue in cheek) reminder that Mathematica is a wonderful all >> purpose environment in which to do Mathematics. >> 221 years ago the 10 year old Gauss would have solved the problem by >> coding:- >> n = 10000000; >> Timing[total = n (n + 1)/2] >> {0.000035, 50000005000000} >> Which is a whole lot faster! >> I realize that this is not very helpful in deciding usage of Table vs >> Do. >> But the precocious Gauss also might have tried >> Timing[total = Table[i (i + 1)/2, {i, 10000000}]] >> {20.46425400000001, {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, >> 91, <<9999974>>, >> 49999885000066, 49999895000055, 49999905000045, 49999915000036, >> 49999925000028, 49999935000021, 49999945000015, 49999955000010, >> 49999965000006, 49999975000003, 49999985000001, 49999995000000, >> 50000005000000}} >> or better yet >> Timing[Total[Table[i (i + 1)/2, {i, 10000000}]]] >> {31.7433, 166666716666670000000} >> Just to show off ... :) >> PS Where would we be now if Stephen Wolfram had provided Gauss with a= >> free Mathematica License back then? >> BTW What a surprising result (1666667)(1666667)(0000000) >> I wonder if anyone has computed this result before and explained its >> repetition of the first 7 digits? >> Syd Geraghty B.Sc, M.Sc. >> sydgeraghty@mac.com >> My System >> Mathematica 6.0.2.1 for Mac OS X x86 (64 - bit) (March 13, 2008) >> MacOS X V 10.5.2 > This is problem with a known simple result, but it will serve: let's= > find the sum of the first 10000000 integers. (*let's use a do loop*) > Timing[ > icount = 0; > Do[icount = icount + i, {i, 1, 10000000, 1}]; > icount > ] (*this returns {10.2826, 50000005000000} on my machine.*) > (*10.28 being a measure of how long the computation took to run*) (*lets try a table*) > Timing[ > Total[Table[i, {i, 1, 10000000, 1}]] > ] (*This returns {3.25516, 50000005000000} on my machine*) > -- = DrMajorBob@longhorns.com === Subject: how to use ones(A)? v=[1 2 3];a=ones(v) the result is: a(:,:,1) = 1 1 a(:,:,2) = 1 1 a(:,:,3) = 1 1 why do it has the above three vectors?What do they mean? === Subject: AnyOne Knows how to??? Hello Group, This Program is the knight's tour, however if someone could help me knightJumps = {{2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}}; successors[s_, n_, position_] := Block[{moves, onBoard}, moves = Map[position + # &, knightJumps];(*moves over the edge of the chessboard are*)(*invalid*) onBoard = Select[moves, And @@ Thread[{0, 0} < # <= {n, n}] &]; Select[onBoard, s[[Sequence @@ #]] == 0 &]] numberOfSuccessors[s_, n_, position_] := Length[successors[s, n, position]] mina[s_, n_, position_] := (*successor(s) with least number of successors*) Block[{localSuccessors, localNumbersOfSuccessors, minimum}, localSuccessors = successors[s, n, position]; localNumbersOfSuccessors = Map[numberOfSuccessors[s, n, #] &, localSuccessors]; minimum = Min[localNumbersOfSuccessors]; localSuccessors[[ Flatten[Position[localNumbersOfSuccessors, minimum]]]]] mabst[destination_, successorlist_] := (*successor(s) with greatest distance from*)(*destination*) Block[{vectors, distances, maximum}, vectors = Map[destination - # &, successorlist]; distances = Map[#.# &, vectors]; maximum = Max[distances]; successorlist[[Flatten[Position[distances, maximum]]]]] improvedWarnsdorff[n_] :=(*main program*) Block[{s, destination, position, localMina},(*initialize chessboard s*)(*s[[x,y]]==0==>square (x, y) is*)(*untouched.*)(*in the end, s contains the step numbers*)(*at which every square was visited*) s = Table[0, {n}, {n}];(*path should end near the following*) destination = {Round[n/2] - 1/2, Round[n/2] - 1/2};(*starting point in the corner of the board*) position = {1, 1}; s[[1, 1]] = 1; Do[localMina = mina[s, n, position]; If[Length[localMina] == 0, Print[Blind alley];(*algorithm failed*) Break[]]; position = If[Length[localMina] == 1, First[localMina], First[mabst[destination, localMina]]]; s[[First[position], Last[position]]] = stepNumber, {stepNumber, 2, n n}]; s] knight = improvedWarnsdorff[6]; MatrixForm[knight] This Program is the knight's tour, however if someone could help me to use a doubly subscripted array, accessibility, with numbers indicating from how many squares each particular square is accessible. On a blank chessboard, each center square is rated as 8, each corner square is rated as 2, and the other squares have accessibility numbers of 3, 4, or 6 as follows: 2 3 4 4 3 2 3 4 6 6 4 3 4 6 8 8 6 4 4 6 8 8 6 4 3 4 6 6 4 3 2 3 4 4 3 2 Is some one could help me to use the Knight's Tour program by using this heuristic. At any time, the knight SHOULD MOVE TO THE SQUARE WITH THE LOWEST ACCESSIBILITY NUMBER. If the square have the same value (6,6) (tie), the knight may move to any of the same square, so the tour may begin in any of the four corners. As the knight moves around the chessboard, THE program should reduce the accessibility numbers as more and more squares become occupied. In this way, at any given time during the tour, each available square's accessibility number will remain equal to precisely the number of squares from which that square may be reached. Anna SJ === Subject: Re: Problems with NSolve Hi Sorry for the fuzziness :) chpoly was found by using Det[A - x*IdentityMatrix[dim]] (where A is a matrix function of u with alpha etc. being some random parameters). Alpha etc are random real numbers between -1 and 1 with working precision 30. Also please find attached a notebook of a working sample. [contact the sender to get this attachment - moderator] So I think the problem seems here, that instead of getting polynomials, I am getting rational functions. The thread Carl sent mentions some alternatives - I will try them out. Kij > Hi all >> I am trying to find the number of eigenvalue crossings for a matrix as >> a function of the parameter 'u', on which the elements of the >> (symmetric) matrix depend on linearly. The matrix elements also >> involve randomly chosen constants. The plan is to find the >> distribution of the crossings of these type of matrices as I scan over >> the random numbers. >> So far I have been using the following : >> NSolve[{chpoly[u, dim, [Alpha], [Gamma], [Epsilon], x] == 0, >> D[chpoly[u, dim, [Alpha], [Gamma], [Epsilon], x], x] == 0}, {x, >> u}, WorkingPrecision -> prec] >> where chpoly is the characteristic polynomial of the matrix (with the >> eigenvalue variable being x) and alpha, gamma and epsilon are >> constant parameter arrays of random numbers. For a double (or higher) >> degeneracy of the eigenvalues both the characteristic equation and its >> derivative should be zero. This approach has worked successfully only >> upto 12*12 matrices (where one such computation takes 40 secs on my >> laptop). For 13*13 my laptop takes 4000 sec. This seems to be somewhat >> surprising, because these polynomials are of the order 'n' (where n >> is dimension of the matrix) in both u and x - and n=13 does not sound >> very computationally unreasonable. So I was wondering if there was a >> faster approach I could take. >> Also, the problem essentially entails me to know the number (not the >> values) of the real solutions to this system of polynomials. >> CountRoots seemed ideal but it does not work for more than one >> equation. So is there any alternative along this route? >> Any other alternatives are also welcome. >> Kij. > Could you post, please, a *fully working* example of what you are doing? It > is really hard to optimize fuzzy functions (fuzzy not as in fuzzy logic but > as in fuzzy definitions or concepts :-) -- === Subject: Re: Cropping a surface to a sphere (fun Manipulate example) HellO Szabolcs, I liked your surface so much, I thought I might share this fun Manipulate: sphere[ls_] := Function[{x, y, z}, x^2 + y^2 + z^2 < ls^2] Manipulate[ ContourPlot3D[-x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - x^2*z^4 + y^2*z^4 == ls, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, RegionFunction -> sphere[3]], {{ls, 0}, 0, 1/2}] > Hell Szabolcs, > In 6, there is the option: RegionFunction -> (#1^2 + #2^2 + #3^2 < 9 &) > Your surface is very pleasing. If not 6, this would be difficult. > Is there a simple way to crop a surface to a sphere? > > For example, consider the surface > > ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] W. Craig Carter > -- W. Craig Carter === Subject: Re: Enable multicore calculation ? Hello Szbolcs, I am not competent enough to answer such questions, as I have no knowledge how the various functions you mention are implemented. It is just my experience that analytic calculations using Map, Apply Inner and all that never seem to use multicores (in my particular applications). Up to now I only experienced multicore use in calculations using NDSolve, where the calculation of the right hand side of a large set of coupled ordinary differential equations requires the inversion of matrices. So I must say that I do not even know which part of the numerical calculation uses multicore, Inverse[] or NDSolve[] itselve. I just see from the Linux process monitor that CPU usage is nearly 400% on an eight processor machine, from which I conclude that my calculation uses 4 processors (hopefully correct). I guess we would need somebody from WRI to enlighten us here... Michael >> I run some larger calculations on Linux with Mathematica 6.0.2.1 and >> 8 cores essentially using NDSolve, and these calculations definitly use >> usually 4 cores without any interference from my side. Mathematica >> seems to detect the multicore environment automatically and the >> software acts then accordingly. In a sense I was (positively) surprised. >> However, not everything in Mathematica supports multicore, and it is >> my guess and partly my experience that it is mostly (maybe only) >> numerical stuff which uses multicores. > I do not have access to any multiprocessor machines which have > Mathematica. I am curious: do functions like Map or Inner use multiple > processors (in principle it is easy to parallellize these)? More > generally, can those functions that call other Mathematica functions use > more than one processor? Or is this capability restricted to built-in > operations that are implemented at a lower level than the Mathematica > language (such as numerical linear algebra)? Is it guaranteed that Map evaluates the elements of a list in order? > What about misuses such as the following: a = 123; > Map[(a = 100 + Mod[a, #]) &, {5, 6, 7, 8}]; > a (Actually this one must be pretty hard to parallellize even if there are > no guarantees about evaluation order.) Szabolcs > === Subject: Re: Enable multicore calculation ? I see... === Subject: Re: Cropping a surface to a sphere ContourPlot3D[-x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - x^2*z^4 + y^2*z^4 == 1, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, Mesh -> False, RegionFunction -> Function[{x, y, z}, x^2 + y^2 + z^2 < 9]] Bob Hanlon Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to= > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? I guess that if there really isn't a > better way, I could write a polygon cropping function, convert the > graphic to Normal[] form, and crop/remove each polygon one by one, but I= > was hoping for a simpler solution ... (built-in function or existing > package). > === Subject: Re: Change integral variables The Presentations package at my web site below ($50) has a Student's Integral section that allows students to display and manipulate integrals using basic integration techniques. It also has a BasicIntegralTable such as students might use. So it is possible to do many integrals completely bypassing the Mathematica Integrate command, or it is possible to manipulate an integral to a starting form and then hand it over to Integrate. Here is your integral done with Student's Integral. The integrate command is the inert form of Integrate that you were asking for. We first use a change of variable, then do an integration by parts, use the BasicIntegralTable, and then resubstitute the original variable. The displays would contain the normal box form for an integral but I can only show the plain text form in the posting. I usually do such calculations all in one cell, building up the steps and reevaluating. integrate[Sin[Sqrt[x]], x] % // ChangeIntegralVariable[tsub = t -> Sqrt[x], x] % // IntegrateByParts[t, t] % + C // UseIntegralTable[BasicIntegralTable] % /. tsub The successive outputs are: (You should be able to paste these into a notebook.) [Integral]Sin[Sqrt[x]][DifferentialD]x [Integral]2 t Sin[t][DifferentialD]t -2 t Cos[t]+2 [Integral]Cos[t][DifferentialD]t C-2 t Cos[t]+2 Sin[t] C-2 Sqrt[x] Cos[Sqrt[x]]+2 Sin[Sqrt[x]] And that checks with the simple use of the Integrate command. In addition, in the IntegrateByParts step, there was generated a Panel display giving the integration by parts information. It looked like the following: u = t, du = 1 dt dv = 2 Sin[t] dt, v = -2 Cos[t] Used BasicIntegralTable successfully. In the IntegrateByParts command there is a choice of using an integral table, or using the Mathematica Integrate command. In addition to these commands there are commands: OperateIntegrand to perform algebraic operations on the integrand, TrigonometricSubstitute for the standard trigonometric substitutions (which also generates a triangle plot) and BreakoutIntegral for breaking out sums and constants from integral expressions. The routines will also handle definite integrals and will display intermediate forms with a LimitsBracket. Although this is basically for students, it can also be useful in writing tutorials or research papers where one may wish to show some basic techniques in handling integrals. Sometimes a Mathematica Integrate will be very slow and return the answer in a form that has to be further manipulated to a desired form. A special integral table could be constructed to handle such cases. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > In Mathematica, how can I change integral variables? For example in > integration: Integrate[Sin[Sqrt[x]], x] if I want to use t^2=x to instead x in the > integral, how can I achieve this? PS: Does Mathematica have a inertial form of some symbolic command, > for instance, the above integration, if I only want an integration > form but not an answer, what can I do? === Subject: Re: Change integral variables > In Mathematica, how can I change integral variables? For example in > integration: Integrate[Sin[Sqrt[x]], x] if I want to use t^2=x to instead x in the > integral, how can I achieve this? PS: Does Mathematica have a inertial form of some symbolic command, > for instance, the above integration, if I only want an integration > form but not an answer, what can I do? > The following is a rough implementation of an integration by substitution routine.... In[87]:= IntegrateBySubstitution[integrand_, var_, sub_Equal] := Catch[Module[{u, substitution, du, res, x}, u = First[sub]; substitution = Last[sub]; du = D[substitution, var]; res = Simplify[(integrand /. substitution :> u)/du]; If[FreeQ[res, var], Throw[{res, u}] ]; (* use inverse function to remove var from res *) x = First@Flatten@Solve[sub, var]; res = PowerExpand@Simplify[res /. x]; {res, u} ]] Here is the integral you requested: In[88]:= IntegrateBySubstitution[Sin[Sqrt[x]], x, u == Sqrt[x]] Out[88]= {2 u Sin[u], u} And a couple of other examples ;-) In[89]:= IntegrateBySubstitution[(2 x)/(1 + x^2), x, u == 1 + x^2] Out[89]= {1/u, u} In[90]:= IntegrateBySubstitution[(2 x)/(1 + x^2), x, u == x^2] Out[90]= {1/(1 + u), u} In[91]:= IntegrateBySubstitution[Sqrt[1 - x + Sqrt[x]], x, u == Sqrt[x]] Out[91]= {2 u Sqrt[1 + u - u^2], u} In[92]:= IntegrateBySubstitution[Sqrt[1 + Tan[x]], x, u == Tan[x]] During evaluation of In[92]:= Solve::ifun: Inverse functions are being used by Solve, so some solutions may not be found; use Reduce for complete solution information. >> Out[92]= {Sqrt[1 + u]/(1 + u^2), u} Sam === Subject: Re: Change integral variables to prevent evaluation, there is Hold or HoldForm. To change variable of integration without evaluating the integral, we may use Hold or HoldForm which prints nicer. Hold[Integrate[Sin[Sqrt[x]],x]] /.Hold[Integrate[body_,var_]]:>(Hold[Integrate[body1,var]]/.{body1->2 body /.x->t^2,var->t}) note that we take care of dx=2 dt by writing body1-> 2 body. Note also that the first Rule must be delayed. hope this helps, Daniel > In Mathematica, how can I change integral variables? For example in > integration: Integrate[Sin[Sqrt[x]], x] if I want to use t^2=x to instead x in the > integral, how can I achieve this? PS: Does Mathematica have a inertial form of some symbolic command, > for instance, the above integration, if I only want an integration > form but not an answer, what can I do? === Subject: Re: Change integral variables > In Mathematica, how can I change integral variables? For example in > integration: Integrate[Sin[Sqrt[x]], x] if I want to use t^2=x to instead x in the > integral, how can I achieve this? You could write a function like the following one: In[1]:= myIntegrate[f_, chng : (z_ -> g_), t_] := Integrate[(f /. chng)*D[g, t], t] myIntegrate[Sin[Sqrt[x]], x -> t^2, t] Out[2]= 2 2 2 2 (-Sqrt[t ] Cos[Sqrt[t ]] + Sin[Sqrt[t ]]) Note that if you are looking to get rid of the square roots, you must ask Mathematica to simplify the expression, giving it the correct assumptions. (By default, Mathematica works on the complex field.) In[3]:= Simplify[%, Assumptions -> t >= 0] Out[3]= 2 (-t Cos[t] + Sin[t]) > PS: Does Mathematica have a inertial form of some symbolic command, > for instance, the above integration, if I only want an integration > form but not an answer, what can I do? You can achieve this by wrapping around the expression a *HoldForm[]* command. For instance, In[4]:= HoldForm[Integrate[Sin[Sqrt[x]], x]] == Integrate[Sin[Sqrt[x]], x] Out[4]= Integrate[Sin[Sqrt[x]], x] == -2 Sqrt[x] Cos[Sqrt[x]] + 2 Sin[Sqrt[x]] -- === Subject: Re: Cropping a surface to a sphere Just use the RegionFunction option. One should check the Function page for RegionFunction and see what arguments the function takes for various plot types. Different plot types use different arguments (and this is also true for other types of function options in plot statements) so one should check this. I usually write a Function expression with all the arguments, even though only some of them may be used. ContourPlot3D[-x^4 y^2 + x^2 y^4 + x^4 z^2 - y^4 z^2 - x^2 z^4 + y^2 z^4 == 1, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, RegionFunction -> Function[{x, y, z, f}, x^2 + y^2 + z^2 <= 9], Mesh -> False] -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? I guess that if there really isn't a > better way, I could write a polygon cropping function, convert the > graphic to Normal[] form, and crop/remove each polygon one by one, but I > was hoping for a simpler solution ... (built-in function or existing > package). > === Subject: Re: Cropping a surface to a sphere Hi Szabolcs, look up RegionFunction in the manual. Here is an example: ContourPlot3D[-x^4*y^2+x^2*y^4+x^4*z^2-y^4*z^2-x^2*z^4+y^2*z^4==1,{x,-3,3},{ y,-3,3},{z,-3,3},Mesh->False,RegionFunction->Function[{x,y,z},x^2+y^2+z^2<9]] hope this helps, Daniel > Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? I guess that if there really isn't a > better way, I could write a polygon cropping function, convert the > graphic to Normal[] form, and crop/remove each polygon one by one, but I > was hoping for a simpler solution ... (built-in function or existing > package). > === Subject: Re: Cropping a surface to a sphere > Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? I guess that if there really isn't a > better way, I could write a polygon cropping function, convert the > graphic to Normal[] form, and crop/remove each polygon one by one, but I > was hoping for a simpler solution ... (built-in function or existing > package). Have a look at RegionFunction (version 6 only). ContourPlot3D[-x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - x^2*z^4 + y^2*z^4 == 1, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, Mesh -> False, RegionFunction -> Function[{x, y, z}, x^2 + y^2 + z^2 < 9]] JM === Subject: Re: Cropping a surface to a sphere Hell Szabolcs, In 6, there is the option: RegionFunction -> (#1^2 + #2^2 + #3^2 < 9 &) Your surface is very pleasing. If not 6, this would be difficult. te: Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] > W. Craig Carter === Subject: Re: Cropping a surface to a sphere > Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to= > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? Have you tried RegionFunction? ContourPlot3D[-x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - x^2*z^4 + y^2*z^4 == 1, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, Mesh -> False, RegionFunction -> Function[{x, y, z}, x^2 + y^2 + z^2 <= 9]] -- Helen Read University of Vermont === Subject: Re: Cropping a surface to a sphere I would like to expand on my previous reply. Many beginners at Mathematica graphics, although Szabolcs is far from a beginner!, tend to overlook the use of options in plots. Options at first seem confusing and one can usually get an impressive plot without them. But they have always been important in customizing a plot and in Version 6 they are doubly important. Many essential elements are supplied only by the options. Here is a second version of the surface cropped to a sphere using a number of options. ContourPlot3D[-x^4 y^2 + x^2 y^4 + x^4 z^2 - y^4 z^2 - x^2 z^4 + y^2 z^4 == 1, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, RegionFunction -> Function[{x, y, z, f}, x^2 + y^2 + z^2 <= 9], ContourStyle -> {FaceForm[ColorData[Legacy][DarkSeaGreen], GrayLevel[.7]]}, PlotPoints -> 25, Mesh -> False, (* Use white lights instead of colored lights *) Lighting -> Neutral, Axes -> False, Boxed -> False, (* The following options provide a smooth rotation with the mouse *) SphericalRegion -> True, RotationAction -> Clip, (* The following option causes the plot to fill the viewing area *) PlotRegion -> {{-.3, 1.3}, {-.3, 1.3}}, Background -> ColorData[Legacy][LightBeige], ImageSize -> 500] It's not clear that we need the bounding box or the axes. We might just say it is the surface out to a radius of 3. The colored lights add nothing to the plot. They only introduce confusion so we use Neutral lighting. We then use the ContourStyle option to give different colors to the inside and outside of the surface. If you don't like the image jumping around when you use the mouse to rotate, you can use the SphericalRegion and RotationAction options. The PlotRegion option gives us an initial view such that the object fills the viewing area. You can also use the mouse zoom function to control this. Then we use a Background to tone down the plot and ImageSize to control the initial size. There are many other options that might be used. I hope you will agree that this is a much better presentation of the surface than my previous reply without all the options. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? I guess that if there really isn't a > better way, I could write a polygon cropping function, convert the > graphic to Normal[] form, and crop/remove each polygon one by one, but I > was hoping for a simpler solution ... (built-in function or existing > package). > === Subject: Re: Cropping a surface to a sphere you could also read the manual. ContourPlot3D[-x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - x^2*z^4 + y^2*z^4 == 1, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, Mesh -> False, RegionFunction -> Function[{x, y, z}, 9 > x^2 + y^2 + z^2]] > Is there a simple way to crop a surface to a sphere? For example, consider the surface ContourPlot3D[ > -x^4*y^2 + x^2*y^4 + x^4*z^2 - y^4*z^2 - > x^2*z^4 + y^2*z^4 == 1, > {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, > Mesh -> False] It is cropped to a cube (the bounding box) by default. I would like to= > crop it to a sphere of radius 3 (or some other region). Is there an easy way to do this? I guess that if there really isn't a > better way, I could write a polygon cropping function, convert the > graphic to Normal[] form, and crop/remove each polygon one by one, but = I > was hoping for a simpler solution ... (built-in function or existing > package). > === Subject: Re: grouping terms by order? You are looking for the command Collect Collect[(1 + a*x)*(1 + b*x), x] a*b*x^2 + (a + b)*x + 1 Bob Hanlon > Consider this: In[19]:= Expand[ (1+a*x)*(1+b*x), x] 2 > Out[19]= 1 + a x + b x + a b x > How can I coax Mathematica to give me this, instead: 2 > Want[19]= 1 + (a + b) x + a b x Why isn't Mathematica reporting the answer in terms of powers of x? === Subject: Re: Indefinite numbers of arguments in a function > Hello everybody, > Is it possible to define a function in Mathematica, where the > numbers of > arguments does not matter? Use the appropriate patterns f[x__] := .... Allows one or more values to match x f[x___] := ... Allows zero or more values for x. I know the function Plus is defined like that: I call the function with two arguments( for example Plus[5,3]) or I > can > call the function with five arguments (for example > Plus[1,6,4,6,8]). How can i define a function in Mathematica like that? I know I can > define for ever number of arguments a function like that: > MyPlus[a_,b_]:=a+b > MyPlus[a_,b_,c_]:=a+b+c > MyPlus[a_,b_,c_,d_]:=a+b+c+d > MyPlus[a_,b_,c_,d_,e_]:=a+b+c+d+e MyPlus[a__]:=Plus[a] or MyPlus[a__]:=Sum[{a}[[i]],{i,Length[{a}]}] if you don't want to use Plus. Ssezi === Subject: Re: SparseArray memory usage An obvious advantage of SparseArray is that less memory is needed for sparse arrays. Unfortunately, this doesn't always seem to be the case, as I outline below sometimes almost as much memory is used as for an ordinary array. Can someone explain this, and hopefully tell me how to get around it? > > It's because of the way SparseArrays are internally structured. It stores a cumulative count of the number of nonzero elements in each row. For a matrix with 10^8 rows, this information takes: In[1]:= ByteCount[ConstantArray[1, 10^8]] Out[1]= 400000076 This is the memory usage you are seeing. Obviously, if you can structure your problem so that it has fewer rows, your memory usage will go down. Carl Woll Wolfram Research >First, a situation which is fine: >Starting with a clean kernel, I get the following memory usage for a 2 x 100million sparse array: In[1]:= MaxMemoryUsed[] >MemoryInUse[] >a=SparseArray[{{1,1}->1},{2,100000000}]; >MaxMemoryUsed[] >MemoryInUse[] Out[1]= 5826800 >Out[2]= 6652184 >Out[4]= 6927152 >Out[5]= 6654624 Second, a situation which is not fine: I use the transposed array and memory usage explodes: In[1]:= MaxMemoryUsed[] >MemoryInUse[] >a=SparseArray[{{1,1}->1},{100000000,2}]; >MaxMemoryUsed[] >MemoryInUse[] >Out[1]= 5826816 >Out[2]= 6652184 >Out[4]= 806653720 >Out[5]= 406655144 > === Subject: Re: List concatenation - two more methods, one truly >>This result is fascinating - it is reasonable that all the solutions >>based on appending lists work O(n^2), but the nested list approach >>should not behave this way. If you repeat the timing, but without >>defining p: >>n = 5000; poly = Table[0, {n}]; >>Print[Timing[Do[poly = {poly, p[i]}, {i, 1, n}]; >> poly = Flatten[poly]][[1]]]; >>I get 0.02 seconds rather than 11 seconds (I obviously have a slightly >>slower machine. This means that the time depends crucially on what you >>are accumulating. >>Consider the semantics of the operation: >>poly = {poly, p[i]} >>This will only be efficient if Mathematica 'knows' that the old value of >>poly is already fully evaluated. As I understand it, Mathematica does >>this using a hashing method, and my guess is that in this case the hash >>table overflows and the ever growing expression gets repeatedly >>evaluated - hence O(n^2). >>It would be nice if someone from Wolfram could comment on these timing >>results. >>Incidentally, the following method works efficiently without requiring >>the array size to be known in advance: >>n = 5000; poly = Table[0, {n}]; >>Print[Timing[poly = Reap[Do[Sow[p[i]], {i, 1, n}]][[2, 1]]][[1]]]; >>David Baileyhttp://www.dbaileyconsultancy.co.uk > Note that O(n^2) dependence is a killer for building long object lists. > For example suppose I increase n to 200000 polygons. In FEM work that is a > medium size plot. Building the Show[] list by one of the O(n^2) > methods extrapolates > to about 50000 seconds (14 hours) on my desktop G5. And I know that on that > machine elapsed time is about 3 times that reported by Timing[]. Waiting 40+ > hours for one plot is not exactly interactive speed. On the other hand a O(n) scheme would build it in less than a second. The point, I guess, being that one should use an O(n) method in preference to an O(n^2) method. That, or learn relaxation techniques (and I don't mean for solving systems of equations). As for poly = {poly, p[i]} iteration being O(n^2) instead of the expected O(n), some explanation is here: http://forums.wolfram.com/mathgroup/archive/2008/Apr/msg00555.html I will also add that Sow/Reap does not suffer from this potential speed liability. Daniel Lichtblau Wolfram Research === Subject: Re: EdgeRenderingFunction to produce edge > I believe this method fails to preserve vertex coordinates from an > original Combinatorica Graph[...] object in case one changes the > vertex labels to, say, letters. For example: g = SetEdgeLabels[SetVertexLabels[Wheel[4], Characters[1234]], > Characters[defabc]]; GraphPlot[torules[g], EdgeLabeling -> True, VertexLabeling -> True, > VertexCoordinateRules -> getcoords[g]] > Yes, I made a mistake in the definition of getcoords. It should be: getcoords[Graph[edges_, vertices_, ___]] := vertices[[All, 1]] Carl Woll Wolfram Research >> ... If you want to use my first method and maintain the vertex >> locations, then you need to include that information in the call to >> GraphPlot. >> Here is a function that creates the usual rule structure that >> GraphPlot expects from a Combinatorica graph (with vertex and edge >> labels): >> torules[Graph[edges_, vertices_, ___]] := Module[ >> {vrules}, >> vrules = DeleteCases[ >> Thread[Range[Length[vertices]] -> (VertexLabel /. >> vertices[[All,2 ;;]])], >> _ -> VertexLabel >> ]; >> Replace[ >> Transpose[{Rule @@@ (edges[[All,1]] /. vrules), EdgeLabel /. >> edges[[All,2 ;;]]}], >> {a_, EdgeLabel} -> a, >> {1} >> ] >> ] >> Here is a function that extracts coordinates from a Combinatorica graph: >> getcoords[Graph[edges_, vertices_, ___]] := >> Thread[Rule[Range[Length[vertices]], vertices[[All, 1]]]] >> So, let's create a graph with edge and vertex labels: >> g = SetEdgeLabels[SetVertexLabels[Cycle[3], {a, b, c}], {x, y, z}]; >> Now, we'll use GraphPlot to view the graph: >> GraphPlot[torules[g], EdgeLabeling->True, VertexLabeling->True, >> VertexCoordinateRules->getcoords[g]] === Subject: Re: EdgeRenderingFunction to Sorry about the mistake: Using characters as vertex labels here DOES work. (I had forgotten to revert to the names that Carl Woll used for the utility functions when I tried to evaluate the second input expression shown below.) But with a catch: For this example, the edge labels of two of the edges are written to the same location, in the middle of the X inside the square, so that you see only one of them. Unfortunately, the ruse of including the Method->HighDimensionalEmbedding and then manually dragging vertices around so as to reveal the hidden vertex is not available: the VertexCoordinateRules option is not allowed here. > I believe this method fails to preserve vertex coordinates from an > original Combinatorica Graph[...] object in case one changes the vertex > labels to, say, letters. For example: g = SetEdgeLabels[SetVertexLabels[Wheel[4], Characters[1234]], > Characters[defabc]]; GraphPlot[torules[g], EdgeLabeling -> True, VertexLabeling -> True, > VertexCoordinateRules -> getcoords[g]] >> ... If you want to use my first method and maintain the vertex locations, >> then you need to include that information in the call to GraphPlot. >> Here is a function that creates the usual rule structure that GraphPlot >> expects from a Combinatorica graph (with vertex and edge labels): >> torules[Graph[edges_, vertices_, ___]] := Module[ >> {vrules}, >> >> vrules = DeleteCases[ >> Thread[Range[Length[vertices]] -> (VertexLabel /. >> vertices[[All,2 ;;]])], >> _ -> VertexLabel >> ]; >> Replace[ >> Transpose[{Rule @@@ (edges[[All,1]] /. vrules), EdgeLabel /. >> edges[[All,2 ;;]]}], >> {a_, EdgeLabel} -> a, >> {1} >> ] >> ] >> Here is a function that extracts coordinates from a Combinatorica graph: >> getcoords[Graph[edges_, vertices_, ___]] := >> Thread[Rule[Range[Length[vertices]], vertices[[All, 1]]]] >> So, let's create a graph with edge and vertex labels: >> g = SetEdgeLabels[SetVertexLabels[Cycle[3], {a, b, c}], {x, y, z}]; >> Now, we'll use GraphPlot to view the graph: >> GraphPlot[torules[g], EdgeLabeling->True, VertexLabeling->True, >> VertexCoordinateRules->getcoords[g]] > -- 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 fax 413 545-1801 Amherst, MA 01003-9305 === Subject: problem accessing notebooks dear forum, BeginPackage[Symkin`,{ GlobalKinematics`TopologicalStructure`, GlobalKinematics`GlobalChains`, SingleLoops`SolveSingleLoop`, SingleLoops`GetSubstitutions`, SingleLoops`GenerateConstraints`, SingleLoops`BuildIPM`, SingleLoops`ConstraintProjections`, SingleLoops`GenerateVelocities`, SingleLoops`GenerateAccelerations`, SingleLoops`SolveLinearEquations`, Graphs`LeafDetection`, Graphs`KinematicalNetwork`, Graphs`LoopBasis`, Graphs`SpanningTree`, Graphs`KinematicsToGraphs`, Graphs`CycleBasis`, Graphs`CycleBasis2`, Graphs`CycleBasis3`, Graphs`CycleBasis4`, Graphs`CycleBasis6`, Graphs`ShortestPath`, Jacobians`GenerateJacobians`, Jacobians`DeriveJacobians`, Jacobians`Make6x1Vector`, Transformations`Make4x4Matrix`, Transformations`SimplifyChain`, Transformations`NormalizeTransformations`, Transformations`SwapAxes`, Transformations`BasicTransformations`, Transformations`PartitionChain`, Algebra`Trigonometry`, ImplicitSolutions`ImplicitSolutions`, ImplicitSolutions`ExtractEdges`, ImplicitSolutions`JointConstraints`, ImplicitSolutions`JointConstraints`, Dynamics`KinematicDifferentials`, Help`ExtractReferenceSystems`, Help`GenerateEquationSequence`, Help`GenerateCORDICBlocks`, Help`GenerateNumericValues`}] I get the error message: Get::noopen: Cannot open GlobalKinematics`TopologicalStructure` (I added the first line of the code fragment to overcome this problem, and the package of name TopologicalStructure resides in the subdirectory GlobalKinematics). So, although the files seem to be in the right place, mathematica will not access them. Is there some other path-variable that I need to set, e.g. a variable containing the default-path for packages or something like that? Also, you might want to know that this package did run under earlier versions of mathematica, and, was designed for mathematica 4, I think. Dietmar === Subject: Re: Quantile and InverseCDF > (* Version 6.0.2 for Mac PPC *) I thick I am missing something obvious: The documentation for InverseCDF says: For a discrete Distribution dist the inverse CDF at q ist the largest > integer x such CDF[dist,x]<=q. But I get binom=BinomialDistribution[20,0.3] InverseCDF[binom,0.5] ---> 6 > Quantile[binom,0.6] ---> 6 CDF[binom,7] ---> 0.772... > CDF[binom,6] ---> 0.608... > CDF[binom,5] ---> 0.416... so the quantile ist the smallest integer such CDF[dist,x]>=q ?? > Gruss Peter > are right that the statement should be that it is the smallest integer such that CDF[dist, x]>=q. Darren Glosemeyer Wolfram Research === Subject: Problems to find the local extrema of an InterpolatingFunction does anyone know how to find all the local extrema of an InterpolatingFunction in a specified interval? The only === Subject: Mathematica syntax An error is yielded with the below segment: l4**2*m1*phidd - l3**2*m2*psidd + - l1**2*m1*thdd + l4**2*m1*thdd + l2**2*m2*thdd + - l3**2*m2*thdd + (l1**2*mb*thdd)/3. - - (l1*l2*mb*thdd)/3. + (l2**2*mb*thdd)/3. - - l1*l4*m1*(phidd + 2*thdd)*Cos(phi) + - l2*l3*m2*(psidd - 2*thdd)*Cos(psi) + - l1*l4*m1*phid**2*Sin(phi) + - 2*l1*l4*m1*phid*thd*Sin(phi) - - l2*l3*m2*psid**2*Sin(psi) + - 2*l2*l3*m2*psid*thd*Sin(psi) - - g*l3*m2*Sin(psi - th) + g*l1*m1*Sin(th) - - g*l2*m2*Sin(th) + (g*l1*mb*Sin(th))/2. - - (g*l2*mb*Sin(th))/2. - g*l4*m1*Sin(phi + th).eq.0, l4*m1*(l4*phidd + l4*thdd - l1*thdd*Cos(phi) - - l1*thd**2*Sin(phi) - g*Sin(phi + th)).eq.0, l3*m2*(l3*psidd - l3*thdd + l2*thdd*Cos(psi) - - l2*thd**2*Sin(psi) + g*Sin(psi - th)).eq.0 (This is from a old version of Mathematica, I think v3) It gives a syntax error and (psi) and (phi) are invalid. What needs to be corrected? I'll post the whole notebook aftewards. === Subject: Re: Directory of Mathematica Add-Ons >> On Apr 13, 3:32 am, David Bailey http://partnerships.wolfram.com/ > I don't think that would cover the many Mathematica packages - free and > otherwise - published independently of Wolfram. >> Correct. it includes only those that have negotiated a partnership >> agreement with Wolfram. What does that negotiation entail? > I chose to keep my Super Widget Package outside any partnership deal because I decided to offer it free of charge and make money from associated consultancy. This has worked reasonably well, and I presume that there must be many other free packages out there. I guess the only directory of all packages is called GOOGLE! David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: NDSolve and vector functions > Hello all, does anybody know a way to compute a vector valued function using NDSolve without explicitely specifying all vector components. Here is a simple example: Although NDSolve[{p'[t]==p[t],p[0]=={1,0}},p,{t,0,1}] works, NDSolve[{p'[t]==p[t]+{1,1},p[0]=={1,0}},p,{t,0,1}] does not work because p[t] in p[t]+{1,1} is treated as a scalar and the expression is evaluated to {1+p[t],1+p[t]} what is clearly not intended. Even in IdentityMatrix[2].p[t]+{1,1} IdentityMatrix[2].p[t] is treated like a scalar and added to the components of {1,1}. do I miss something??? Hi Daniel, Obviously, there are workarounds, but they might not be pretty ... I think that this is a fundamental limitation of Mathematica ... Most functions (incuding Plus) assume that symbols represent scalars ... A workaround is to define a new `plus' function that is only evaluated when its arguments are vectors: vecPlus[arg__?VectorQ] := Plus[arg] Now this works: f = p /. First@ NDSolve[{p'[t] == vecPlus[p[t], {1, 1}], p[0] == {1, 0}}, p, {t, 0, 1}] Plot[f[x], {x, 0, 1}] One disadvantage of this approach is that it prevents NDSolve from transforming the ODE symbolically. But this is really a limitation stemming from using vector functions, and not a problem introduced by vecPlus. A more serious problem is that most probably vecPlus cannot be compiled, so this might slow NDSolve down. Szabolcs === Subject: Re: NDSolve and vector functions >Hello all, does anybody know a way to compute a vector valued function using NDSolve without explicitely specifying all vector components. Here is a simple example: Although NDSolve[{p'[t]==p[t],p[0]=={1,0}},p,{t,0,1}] works, NDSolve[{p'[t]==p[t]+{1,1},p[0]=={1,0}},p,{t,0,1}] does not work because p[t] in p[t]+{1,1} is treated as a scalar and the expression is evaluated to {1+p[t],1+p[t]} what is clearly not intended. Even in IdentityMatrix[2].p[t]+{1,1} IdentityMatrix[2].p[t] is treated like a scalar and added to the components of {1,1}. do I miss something??? Daniel > > A workaround is to define a function that takes on the desired value when it's input is numeric. For example: c[_?NumericQ] = {1,1} NDSolve[{p'[t]==p[t]+c[t],p[0]=={1,0}},p,{t,0,1}] Carl Woll Wolfram Research === Subject: Re: NDSolve and vector functions I don't believe this is possible. How would Mathematica know that p[t] is 2d, 3d, 4d, ...? When I have used something like your approach it is really for ease of the human user, e.g. r[t_]={x[t],y[t]} Then in NDSolve you might *like* to do something like this: r''[t]==-k r[t] But it won't work. You need to Thread the components: Thread[r''[t]==-k r[t]] to split out each of the two diff eqs. In the end NDSolve works on a single component of the de; so, it really needs something like: NDSolve[{x''[t]==-k x[t],y''[t]==-k y[t],x[0]==1,x'[0]==2, etc.},r[t],{t,0,10}] and the above Thread-ing will do just that. Kevin > Hello all, does anybody know a way to compute a vector valued function using NDSolve without explicitely specifying all vector components. Here is a simple example: Although NDSolve[{p'[t]==p[t],p[0]=={1,0}},p,{t,0,1}] works, NDSolve[{p'[t]==p[t]+{1,1},p[0]=={1,0}},p,{t,0,1}] does not work because p[t] in p[t]+{1,1} is treated as a scalar and the expression is evaluated to {1+p[t],1+p[t]} what is clearly not intended. Even in IdentityMatrix[2].p[t]+{1,1} IdentityMatrix[2].p[t] is treated like a scalar and added to the components of {1,1}. do I miss something??? Daniel > -- Kevin J. McCann Research Associate Professor JCET/Physics Physics Building University of Maryland, Baltimore County 1000 Hilltop Circle Baltimore, MD 21250 === Subject: Re: A kernel, multiple notebooks, and Global? David, I'll not try to respond to your (appreciated) response, as appended below for completeness, by interpolating a lot of comments into your message (always find lengthy posts like that, with interpolated replies, hard to read, in fact); but will instead top-post a few more general responses as follows: NO OBJECTIONS TO DISTRIBUTING MATHEMATICA NOTEBOOKS, AS A LIMITED MEANS OF COMMUNICATION TO SMALL AND SPECIALIZED AUDIENCES -- FINE IDEA, IN FACT I have no basic objections at all to distributing notebooks I've created -- even interactive ones -- to colleagues, or pretty much any one who wants them. In fact, I've mentioned the availability of notebooks in a few journal publications, and gotten a few email requests for some of them as a result. Can be a useful means of technical communication, in a limited universe of users. BUT MATHEMATICA CAN NEVER BECOME A UNIVERSAL OR EVEN VERY WIDESPREAD MEDIUM OF COMMUNICATION, EVEN FOR THAT TYPE OF AUDIENCES -- **AND THE VERY ATTEMPT TO EXPAND MATHEMATICA I am totally unsupportive of the proposition that Mathematica can become a universal, or even very widespread, publication medium, where I use become universal to mean that Mathematica notebooks will displace and/or replace many other current publication formats like TeX, PDF, or even Word or PowerPoint (as much as I loathe Microsoft!), for many current media applications like reports, journal publications, presentations, dissertations, and so on. In fact, I think the attempt to expand Mathematica to accomplish this is not just misguided but actively damaging, to Mathematica and to its users. Reasons for this include: a) I view Mathematica as a very sophisticated *computational* tool, and secondarily as a similarly sophisticated graphical and textual *display* for outputting its computed results -- and I consider it to be of high quality and highly successful at both of these tasks. But, viewed just as a high-grade and sophisticated computational tool, Mathematica is already (and unavoidably) enormously large, enormously complex, with complex syntax, and many complex internal interactions -- which means a large learning curve, and a huge documentation, just to do the computational task. Don't try to tell me about how a novice can type in and evaluate a=2;b=3;c=a+b;Plot[c x, {x,0,5}] the first time they sit down in front of it. That's certainly true, but as soon as you get to any significant level of computational sophistication, there's a _large_ learning curve, and many ways to go wrong in using what you've learned -- and a very large remembering task, to retain all this knowledge from one time you use it to the next. [As I worked my way from v1 through v5, each time I leaned some new coding trick, or got one of the more sophisticated commands to work, I would toss a brief template and explanation into my own personal notes notebook, which was permanently accessible by being locked at the bottom of the Open Recent menu. It's now 0.5 MB in size -- and of course made more or less useless by 6.0.] b) Add to this the graphic and textual (and animation) display capabilities that we all want to have from Mathematica, not as publication quality output but just as useful output. Adding these display capabilities may not exactly double the size and complexity of Mathematica, and of the learning curve, and of the documentation, and of the remembering task associated with it -- but doing so very substantially expands all of these aspects, as well as introducing all the complexities of interactions between the output routines and the computational routines. [Plotting a result, or making a Table, can leave the _computational_ state of Mathematica different from what it was before you produced this output, right? And Plot and Table change it in _different_ ways. Not complaining about this -- just noting it.] c) So, you're proposing to add publication-quality output and presentation quality capabilities to the Mathematica core -- meaning adding all the added complexity of the program, the added syntax, the added learning curve, the added documentation, and the added remembering task associated with this function on top of the computational and display complexities already present. Forget it! ***Doing this is simply going to seriously damage the utility -- and commercial value of Mathematica for its primary computational and display functions, and for its ordinary users***. d) And, from what I know of journal publishing, commercial and by professional societies, it's not going to happen! Finally: THE MULTIPLE NOTEBOOK PARADIGM IS FINE, FOR THOSE WHO LIKE IT -- WHICH I THINK CAN INCLUDE A LOT OF ORDINARY USERS In arguing this, some interpolation can help: > If you follow the multiple notebook paradigm, you also have to devise some > kind of organization for the notebooks. All the organization that's needed is that all the notebooks that are needed for a given project are right there, visible and editable, in the folder (or a subfolder) for that project! >You have to remember that for > WorkingNotebookA you need ModuleNotebooks a, c and f. But for > WorkingNotebookB you need ModuleNotebooks a, b, and c. Pretty soon you are > designing your own system, which is not the standard Mathematica system. Nope. If I need (more accurately, want to re-use some part) of notebooks a or c from project A in project B, I just copy 'em over to the Project B folder! (Rule #N -- Disk space is cheap!). And once there, I can modify them for project B -- without screwing up the copies left back in the project A folder. And nothing I do will be modifying Mathematica itself -- don't intend to get into that (I'm after max simplicity, not complications). > People who might use your notebooks not only have to learn the standard > system (because they might be doing other things as well) but they also have > to learn your special system. The only thing they have to do to _use_ my notebooks as written (i.e., to produce further results from them) is start a standard copy of Mathematica fresh, open my notebooks, and run 'em. If they've modified their copy of Mathematica itself to be non-standard in some way, well, they've produced problems that may occur however If they want to merge my notebooks into some notebooks of theirs, well, I'm afraid this is do this at your own risk situation -- and I've not made it more difficult. > In the time it took you to devise your own system, you could have learned > the standard package system. It is really not that difficult. Sorry -- can't agree. There are not a lot of complex steps involved in defining or using packages, agreed. **But digging the exact correct steps out of the documentation, learning the vocabulary, avoiding missteps, and remembering these steps after a time lag, are all frustrating and time-consuming**. > If you organize your notebooks using Sections (and I wonder if using > multiple notebooks is a substitute for using Sectional organization within a > notebook?), then you can initially put > your routines in a Routines Section. The notebook does not have to be > 'visually large' because the Routines Section can usually be closed up. I don't like long notebooks -- navigating through them is awkward and tedious. I don't like open and closing selected cells -- tedious and awkward also. Since it makes no difference in functionality, why don't I put the Routines Section in a separate notebook, meaning a separate window -- which, on a Mac, I can instantaneously, with a single mouse click or key command, fold down into the Dock, or WindowShade (still functional), and equally quickly recover to edit if needed. --------- Enough for now -- and quite a while beyond that. Over and out, AES > AES, I would like to put in a pitch for using the standard Mathematica package > method and maybe even go further and learn something about documentation. I think one of the unstated assumptions here is that no one else is going to > see your Mathematica work because all of the pertinent results will be > Exported or copied out into non-Mathematica documents before being > transmitted to a larger public. In that case why not organize the internal > work in the way that seems most convenient to you? But another assumption that we can make for certain is that you have expert > knowledge and a lot of experience in optical fibers. You also have done, and > will do a lot of work in organizing the theory and calculation methods for > the field. This is valuable stuff! So why not make it available to others in > the Mathematica format with all of its advantages of dynamics and > interactivity. In addition to the final results, if you have worked out > various algorithms, calculation and display routines these are valuable. Why > not make them available to other people as Mathematica packages? If you follow the multiple notebook paradigm, you also have to devise some > kind of organization for the notebooks. You have to remember that for > WorkingNotebookA you need ModuleNotebooks a, c and f. But for > WorkingNotebookB you need ModuleNotebooks a, b, and c. Pretty soon you are > designing your own system, which is not the standard Mathematica system. > People who might use your notebooks not only have to learn the standard > system (because they might be doing other things as well) but they also have > to learn your special system. Rule Number 1: WRI has put a lot of thought into designing a user interface. > It work's fairly well. Be very wary of interposing your own interface. In the time it took you to devise your own system, you could have learned > the standard package system. It is really not that difficult. A Mathematica > package is just a simple particular form of notebook with Initialization > cells. You just save it as an Auto Generated Package and that is all there > is to it. If you organize your notebooks using Sections (and I wonder if using > multiple notebooks is a substitute for using Sectional organization within a > notebook?), then you can initially put > your routines in a Routines Section. The notebook does not have to be > 'visually large' because the Routines Section can usually be closed up. > Other things should also be in Sections. (When I'm working on a particular > derivation of development I put it in its own Section. If I don't especially > like it or get stuck I usually mark it as Try 1, close it up, copy and paste > it and work on a Try 2. When I finally get something I like I throw all the > false steps away.) When you develop a routine in a > working notebook, move it to the Routines Section and write a usage message > for it and make it an Initialization cell. If you start a new working > notebook, copy the Routines Section over. At some point, you will be > convinced that some of the routines are in good shape for general use. Then > move them to your OpticalFiber package. Then you will have one simple > working structure. A single package and working notebooks that load the > package. You or your readers don't have to look at any of the package code > anymore. You may still have some things in your Routines Sections that > haven't yet made it to the package. Documentation is another question, but again, if you have worked out good > routines and methods they are really worth something to other people and > deserve to be documented. (And in any case, I find that I am always > forgetting how some of my own routines work and have to refer to my own > documentation!) With a little cleverness the documentation can also serve as > a set of test cases if you make changes to your routine. Working on > documentation also helps to perfect a routine. Sometimes if it is difficult > to explain and illustrate a routine one might wonder about it basic design. > It's true that this takes time, but it's a focused and productive use of > one's time. David Reiss has put up a good introduction to creating Version 6 > documentation. http://www.scientificarts.com/worklife/notebooks/ and the Workbench application for documentation is coming along. Rule Number 2: Most users of Mathematica are pretty capable people. Turn > your hard work into permanently useful and active knowledge for yourself and > other people. -- > David Park > djmpark@comcast.net > http://home.comcast.net/~djmpark/ === Subject: FrontEnd and JLink I want to create Mathematica graphical objects (notebook with cells, palettes, plots, etc) from a Java Gui using JLink calls Apparently, this is not possible until you don't use the Mathematica.exe frontend (no way to initialize a frontend from a java gui) hereafter a Java example Any helps ? laurent ---------------------------------------------------------------------------- -------- import com.wolfram.jlink.*; class Exemple_FrontEnd { public static void main (String[] args){ try { KernelLink ml = MathLinkFactory.createKernelLink(-linkmode launch - linkname MathKernel); ml.evaluateToInputForm(Needs[ + KernelLink.PACKAGE_CONTEXT + ],0); ml.evaluateToInputForm(ConnectToFrontEnd[], 0); setVisible(True); ml.evaluate(UseFrontEnd[NotebookCreate[]]); } catch (MathLinkException e) { e.printStackTrace(); } } } === Subject: Re: Scaling Plot inside Row Also, you can get finer control of the spacing by using Spacer[15] rather than t. And you don't have to use both Print and Row. plot = Plot[Sin[x], {x, 0, 6 Pi}, ImageSize -> 300]; matrix = TableForm[Table[10 i + j, {i, 4}, {j, 3}]]; Row[{plot, matrix}, Spacer[15]] plot = Plot[Sin[x], {x, 0, 6 Pi}, ImageSize -> 300]; matrix = TableForm[Table[10 i + j, {i, 4}, {j, 3}]]; Print[plot, Spacer[15], matrix] -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > I am trying to control size of a Plot inside a Row that contains also > some TableForm with selectable text. This Row is an output from my > complicated program so I use Print[] to print it as output. I have > tried the following (this is an example): plot=Plot[Sin[x],{x,0,6 Pi}]; > matrix=TableForm[Table[10 i+j,{i,4},{j,3}]]; > Print[Row[{plot,matrix},t]] All is fine but the plot is scaled down. I have tried to use > Graphics[plot,ImageSize->1] but it does not work. > How can I control size of the plot in the output? > === Subject: axis alignment of 3D plots with ListContourPlot3D Can anyone tell me how I can manually the view angle of a ListContourPlot3D? Mathematica seems to automatically set the view angle according to the data distribution. I need to do this because I am generating a series of 3D graphics with ListContourPlot3D, which I then animate into a AVI movie using the export command. As the distribution changes shape significantly in each image, Mathematica automaitcally shifts the view angle substantially, which unfortunately makes the resulting animation appear to shake as the view angle changes. Jess === Subject: NDSolve with Piecewise function into some trouble. Basically what I want to do is this: NDSolve[ {Piecewise[{{FunctionsA, -.001 < x < .001}}, FunctionsB]} , {x, y, z}, {t,10^-5}] So I have x,y,z as functions of t that I want to solve for and in a certain region of x I want to use a different set of equations. I am not really sure if I can go about it this way or not though. Any help on how to tackle such an equation would be greatly appreciated. === Subject: Re: Product command with matrices On Apr 18, 6:14 am, -Peer Kuska Times[] is not Dot[] and Product[] and no equivalent to use > Dot[] instedad of Times[] and there is no (easy) way to > tell Mathematica that f[1] is a matrix and what may be A > a scalar ? a vector or a matrix too ? Even I can't find it out > and Mathematica can't know it. You mean DotProduct[mtx_, {i_, i1_, in_}] := Dot @@ Table[mtx, {i, i1, in}] Phi[0] := Id; > Phi[n_] := DotProduct[Id + f[i] ** A, {i, 0, n - 1}] and Phi[3] gives (Id + f[0] ** A).(Id + f[1] ** A).(Id + f[2] ** A) I want to define a matrix valued function such as the following (in > LaTeX lingo): $$ > X(0)=Id, > X(n)=prod_{i=0}^{n-1} (Id + f[i] A) > $$ where A and f have already been defined and Id is the identity matrix > of appropriate size. I tried the following: Id=IdentityMatrix[2]; > Phi[0]:=Id; > Phi[n_]:= Product[Id + f[i] A,{i,0,n-1}] However, Phi[3] and (Id+f[2]A).(Id+f[1]A).(Id+f[0]A) do not agree. Any help around this would be appreciated. email. I thought I would share the following very efficient solution: Phi[n_]:=Apply[Dot,Table[Id + f[k]A,{k,0,n-1}]] === Subject: Re: Product command with matrices Hello J, You should use Dot. Perhaps this will help: f[i_ ] := f[i] = RandomReal[{0, 1}, {2, 2}] (* random 2x2 matrices, that remember their value*) f[1].f[2].f[3] Dot[f[1], f[2], f[3]] Apply[Dot, {f[1], f[2], f[3]}] So, what you want is something like Apply[Dot,Table[matrices[k],{k,1,n}] > I want to define a matrix valued function such as the following (in > LaTeX lingo): $$ > X(0)=Id, > X(n)=prod_{i=0}^{n-1} (Id + f[i] A) > $$ where A and f have already been defined and Id is the identity matrix > of appropriate size. I tried the following: Id=IdentityMatrix[2]; > Phi[0]:=Id; > Phi[n_]:= Product[Id + f[i] A,{i,0,n-1}] However, Phi[3] and (Id+f[2]A).(Id+f[1]A).(Id+f[0]A) do not agree. Any help around this would be appreciated. -- W. Craig Carter === Subject: Re: Product command with matrices > I want to define a matrix valued function such as the following (in > LaTeX lingo): $$ > X(0)=Id, > X(n)=prod_{i=0}^{n-1} (Id + f[i] A) > $$ where A and f have already been defined and Id is the identity matrix > of appropriate size. I tried the following: Id=IdentityMatrix[2]; > Phi[0]:=Id; > Phi[n_]:= Product[Id + f[i] A,{i,0,n-1}] However, Phi[3] and (Id+f[2]A).(Id+f[1]A).(Id+f[0]A) do not agree. Any help around this would be appreciated You are confusing Dot and Product, do you want to multiply matrix elements together eg: {{a,b},{c,d}} {{e,f},{g,h}} = {{a e,b f},{c g,d h}} or do a regular matrix multiply? If the latter then Phi[n_]:=Fold[(Id+#2 A).#1&,Id+f[0] A,Table[f[i],{i,1,n-1}]] should work. Ssezi === Subject: Re: Defining derivatives You can store it with Derivative. Not that In[7]:= Attributes[Derivative] Out[7]= {NHoldAll, ReadProtected} does not include Protected. So: f[x_] := f1[x] Derivative /: Derivative[1][f] = f2 gives f'[x] f2[x] Of course this still leaves the problem that D[f[x], x] Derivative[1][f1][x] but, on the other hand, why are you trying to do this? Why not simply define: f[x_] := f1[x] Derivative[1][f1] = f2; In which case we get also D[f[x], x] f2(x) Andrzej Kozlowski > Hello All, does anybody know how to define symbolic derivatives. E.g.: f[x_]:=f1[x]; f'[x_]:=f2[x]; this does not work because f on the lefthand side is evaluated. To prevent this (do not forget to remove f before redefining it): f[x_]:=f1[x]; HoldPattern[f'[x_]]:=f2[x]; this gives no message, but f'[x] returns f1[x] instead of f2[x]. The same thinhg happens when you change the sequence of definitions: f'[x_]:=f2[x]; f[x_]:=f1[x]; Further, where is the information about derivatives stored? thank's a lot, Daniel > === Subject: Re: Defining derivatives > Hello All, does anybody know how to define symbolic derivatives. E.g.: f[x_]:=f1[x]; f'[x_]:=f2[x]; this does not work because f on the lefthand side is evaluated. To prevent this (do not forget to remove f before redefining it): f[x_]:=f1[x]; HoldPattern[f'[x_]]:=f2[x]; this gives no message, but f'[x] returns f1[x] instead of f2[x]. The same thinhg happens when you change the sequence of definitions: f'[x_]:=f2[x]; f[x_]:=f1[x]; Further, where is the information about derivatives stored? thank's a lot, Daniel > Daniel, Surely if f[x] has a definition, it is not unreasonable that this definition is used prior to differentiation. Without the definition all works well: (f^[Prime])[x_]:=f2[x]; D[f[2x],x] 2 f2[2 x] BTW, if you only want the definition to be used for numerical cases, you could always use: f[x_?NumericQ]:=f1[x] David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: Defining derivatives > Hello All, does anybody know how to define symbolic derivatives. E.g.: f[x_]:=f1[x]; f'[x_]:=f2[x]; this does not work because f on the lefthand side is evaluated. To prevent this (do not forget to remove f before redefining it): f[x_]:=f1[x]; HoldPattern[f'[x_]]:=f2[x]; this gives no message, but f'[x] returns f1[x] instead of f2[x]. The same thinhg happens when you change the sequence of definitions: f'[x_]:=f2[x]; f[x_]:=f1[x]; Hi Daniel, It seems that Mathematica is not prepared to accept that the derivative of f[x] is f2[x] unless you also tell it that f1'[x] is f2[x]. A workaround is to use f' = f2 instead of f'[x_] := f2[x] This appears to work in simple cases. Further, where is the information about derivatives stored? > It is stored as a SubValue of Derivative. Try f'[x_] := g[2 x] SubValues[f] or just remove the ReadProtected attrbute of Derivative and use ?? Derivative (There are quite a few *Values functions, e.g. NValues. Just try Names[*Values]. Unfortunately these functions are not very well documented.) I hope this helps, Szabolcs === Subject: Re: Defining derivatives >Hello All, does anybody know how to define symbolic derivatives. E.g.: f[x_]:=f1[x]; f'[x_]:=f2[x]; > > Use Derivative[1][f] = f2 Carl Woll Wolfram Research >this does not work because f on the lefthand side is evaluated. To prevent this (do not forget to remove f before redefining it): f[x_]:=f1[x]; HoldPattern[f'[x_]]:=f2[x]; this gives no message, but f'[x] returns f1[x] instead of f2[x]. The same thinhg happens when you change the sequence of definitions: f'[x_]:=f2[x]; f[x_]:=f1[x]; Further, where is the information about derivatives stored? thank's a lot, Daniel > > === Subject: Re: How to solve this simple equation? > I have also an other question for you: As a rule of thumb, it is usually better to ask questions directly to the newsgroup MathGroup. > How to import a column from excel 2007 in data format for mathematica? > For example if I have: > column1 = a b c d e f g h how I can obtain: > data = {a,b,c,d,e,f,g,h} > in mathematica? AFAIK, Mathematica does not handle Microsoft Excel 2007 file format yet. So use an XLS or CSV file format, for instance. Assuming a file saved in XLS format that contains one sheet of 3 rows by 4 columns, you can use Inport[] as follow: In[145]:= imp = Import[Workbook1.xls] Out[145]= {{{11., 21., 31.}, {12., 22., 32.}, {13., 23., 33.}, {14., 24., 34.}}} In[155]:= data = Transpose[Sequence @@ imp][[1]] Out[155]= {11., 12., 13., 14.} -- === Subject: Re: Why isn't Expand[] grouping terms by order? > Consider this: In[19]:= Expand[ (1+a*x)*(1+b*x), x] 2 > Out[19]= 1 + a x + b x + a b x > How can I coax Mathematica to give me this, instead: 2 > Want[19]= 1 + (a + b) x + a b x Why isn't Mathematica reporting the answer in terms of powers of x? The function *Collect[]* is what you are looking for. In[1]:= Collect[(1 + a*x)*(1 + b*x), x] Out[1]= 1 + (a + b) x + a b x^2 In[2]:= Expand[(1 + a*x)*(1 + b*x), x] Out[2]= 1 + a x + b x + a b x^2 In[3]:= Collect[%, x] Out[3]= 1 + (a + b) x + a b x^2 -- === Subject: Re: Why isn't Expand[] grouping terms by order? > Consider this: In[19]:= Expand[ (1+a*x)*(1+b*x), x] 2 > Out[19]= 1 + a x + b x + a b x > How can I coax Mathematica to give me this, instead: 2 > Want[19]= 1 + (a + b) x + a b x Why isn't Mathematica reporting the answer in terms of powers of x? expr = (1 + a x) (1 + b x) Collect[expr,x] Gruss Peter -- ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-== Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de === Subject: Re: Text does not show up in vertices of GraphPlot3D I asked help from Wolfram in this case with the graph gr1. gr1 = {adacadabra -> 1, adacadabra -> 2, 1 -> 3, 1 -> 4, 1 -> 5, 2 -> 6, 2 -> 5, 3 -> 7, 3 -> 8, 5 -> 8, 4 -> 7, 4 -> 9, 5 -> 9, 6 -> 9, 6 -> 10, 7 -> 11, 8 -> 11, 9 -> 11, 10 -> 11} Chetiya Sahabandu came with the following answer: GraphPlot3D[gr1, VertexLabeling -> True, EdgeRenderingFunction -> (Cylinder[#1, .05] &), VertexRenderingFunction -> ({{Text[#2, #1]}, {ColorData[Atoms][ 100], Sphere[#1, .19]}, {Style[Text[#2, #1], Bold, 16, Green]}, {ColorData[Atoms][100], Sphere[#1, .19]}} &), PlotStyle -> Directive[Specularity[White, 20]]] I post this answer because I hope that people can use it. with friendly greetings, P_ter === Subject: Re: SparseArray memory usage Sorry but I can illustrate my problem much more concisely: In[2]:= ByteCount[SparseArray[{{1,1}->1.},{1,100000000}]] ByteCount[SparseArray[{{1,1}->1.},{100000000,1}]] Out[2]= 488 Out[3]= 400000484 wb === Subject: Re: Reduce and Indeterminate The discussions about False, True and sense can fill libraries. Also, sense has different meanings in different languages. To go from False, True to sense is quite a jump. Here the effect of that jump was not to judge in True or False. So, let then the possibility come up: nor True, nor False. That solves this issue here. with friendly greetings, P_ter === Subject: Re: function >> Who can explain the behavior. THe derivative Abs[x] at x=.5 is well >> defined and is equal to 1. >> In[1]:= D[Abs[x], x] >> Out[1]= >> !(*SuperscriptBox[Abs, [Prime], >> MultilineFunction->None])[x] >> In[2]:= % /. x -> .5 >> Out[2]= >> !(*SuperscriptBox[Abs, [Prime], >> MultilineFunction->None])[0.5] > Please use copy as plain text when pasting Mathematica expressions, > so it will be easier to read them. Just use FunctionExpand on the result to get a concrete value. > I never noticed that Function expand deos that and I am not sure that I am very happy that it does. In fact: FunctionExpand[Derivative[1][Abs][x], Element[x, Reals]] x/Abs[x] but that assumes that the derivative is taken along the real line, which is not what Mathematica normally assumes. In my opinion this makes it less clear exactly what FunctionExpand is really meant to do and what to expect of it. I don't think it ought to make additional assumptions beyond what it is told. I think it would be better to let Derivative have a direction option, just as Limit does. Andrzej Kozlowski === Subject: Re: function Who can explain the behavior. THe derivative Abs[x] at x=.5 is well > defined and is equal to 1. In[1]:= D[Abs[x], x] Out[1]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[x] In[2]:= % /. x -> .5 Out[2]= > !(*SuperscriptBox[Abs, [Prime], > MultilineFunction->None])[0.5] Please use copy as plain text when pasting Mathematica expressions, > so it will be easier to read them. Just use FunctionExpand on the result to get a concrete value. > I never noticed that Function expand deos that and I am not sure that I am > very happy that it does. In fact: FunctionExpand[Derivative[1][Abs][x], > Element[x, Reals]] > x/Abs[x] but that assumes that the derivative is taken along the real line, which is > not what Mathematica normally assumes. In my opinion this makes it less > clear exactly what FunctionExpand is really meant to do and what to expect > of it. I don't think it ought to make additional assumptions beyond what it > is told. I think it would be better to let Derivative have a direction option, just > as Limit does. Somewhat related to the topic: It turns out that Limit understands Abs'[x] (this comes as a surprise to me): In[1]:= Limit[Abs'[x], x -> 0, Direction -> 1] Out[1]= -1 In[2]:= Limit[Abs'[x], x -> 0, Direction -> -1] Out[2]= 1 But it does not work correctly with complex directions: In[3]:= Limit[Abs'[1 + x], x -> 0, Direction -> I] Out[3]= 1 The result should have been 0. Szabolcs === Subject: Re: Debugger > Sorry for the newbie post but I wanted to get started with the debugger in= > Mathematica 6.0 and I can't seem to find any documentation other than the > simple description of the buttons. On a Mac (OSX dual core machine) I c= an't > seem to get the interactive debugger to work. Can anyone point me towar= d some > documentation examples or HOWTO simple examples to get me started. Here's a brief example: thread/722199eb253b8c31/34ae8abaaa1a5a45#34ae8abaaa1a5a45 The most common gotcha to the Mathematica debugger is that it only works for code which has been evaluated *after* the debugger has been enabled. You can evaluate a function, turn on the debugger, then debug code which uses that function. You must first turn on the debugger, then evaluate all function definitions you wish to debug, then you can set working breakpoints and step through code. -Rob === Subject: Re: Comments on the .m file editor I don't see the advantages of writing package with the .m file editor. Normally I don't even look at the .m file. I would be interested in hearing comments from some of the sophisticated users about when writing .m files directly might be advantagous. Normally a routine should be written and debugged in a regular Mathematica ..nb notebook. A debugging method that works for almost all cases and is very easy to use is just to insert temporary Print statements into the routine. When a routine is debugged, and a usage message and SyntaxInformation are written it can just be moved to a package.nb notebook with Initialization cells that has been saved as an Auto Generated Package. That is by far the easiest method. You can put (* comments *) anywhere in a Mathematica expression but one very negative feature of Mathematica is that if one uses Shift-Ctrl-N or Shift-Ctrl-I to convert and reformat a cell it strips out all the comments. I think comments should be considered a permanent part of an expression and never stripped out by such reformating. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ As essentially a new user of Mathematica since v6, I'd like to share a > couple of comments about using Mathematica itself to write .m packages > directly. I'm only using v6.0.1 because I can't afford the bug-fix > update right now, so a couple of these comments may no longer be > relevant. Firstly, the positives: It's great to be able to write code in an > editor that explicitly understands the syntax. Brace matching and > selection are good, and syntax colouring is excellent. Being able to write comments in outline mode is also great; especially > with input cells that aren't part of the package but allow you to > execute code; this makes testing and code exposition very convenient > because it can be done inline with the code itself. Now, the negatives. The first complaint is more ignorance than > anything: I've got no idea how to use the debugger. It's great that > it's there, but I don't understand how it's supposed to be used. Are > there any tutorials on this feature? Next: the editor *really* needs to make up its mind whether it's going > to support nice Mathematica symbols or not. It's ridiculous that > typing -> gives you a nice arrow, but then closing and re-opening > the file gives you the literal ascii. Worse, typing a complex > expression involving Greek letters and subscripts and accents looks > fine to start with but then turns into an unreadable mess when > re-opening the package. Since Mathematica can understand the FullForm in package files, I can't > see the harm in displaying it nicely in the .m file editor. Similarly, > the lack of nice spacing in the typesetting of the code is a shame and > makes packages look uglier -- usually requiring extra whitespace (and > effort) to be readable. Finally, the editor doesn't like code that has comments inserted > mid-way through. For example, paste this into a file test.m: (* ::Package:: *) > code[hello, > (* ::Text:: *) > (*some explanation*) > there] Open it in Mathematica, then select all, cut, and paste (this procedure > emulates you typing in those lines manually). Close and reopen the file > and you'll see that Mathematica has inserted two blank lines in the > code. Yuck. Furthermore, this sort of construction kills syntax colouring, which is > a big shame. > It also breaks the Run Package button, which tries to evaluate the > package cell by cell (instead, it should simply execute `< chunks of code when large packages deserve better comments than an > essay right before the Module with inline comments like (* we're doing > stuff here *). If those sorts of comments was the only way to document > the code then we may as well not even bother with cells, to be frank. *** To sum up: the .m file editor is pretty neat but two main additions > would make it much better: explicit support for breaking cells up with > comments whereever you like (including syntax checking and colouring > across cell breaks); and typesetting as in the the notebook editor > (including the extended symbols). In the very least, it shouldn't > interpret typeset symbols unless it intends to preserve them. The > typesetting doesn't affect anyone trying to edit the thing in plain > text and makes the whole thing much nicer to use. After all, without nice typesetting we may as well go back to notebooks > with initialisation cells, which have even less ability to be commented > nicely by splitting up cells partway through. Any comments from others also using the editor? Will Robertson === Subject: Re: Comments on the .m file editor As essentially a new user of Mathematica since v6, I'd like to share a > couple of comments about using Mathematica itself to write .m packages > directly. I'm only using v6.0.1 because I can't afford the bug-fix > update right now, so a couple of these comments may no longer be > relevant. Firstly, the positives: It's great to be able to write code in an > editor that explicitly understands the syntax. Brace matching and > selection are good, and syntax colouring is excellent. Being able to write comments in outline mode is also great; especially > with input cells that aren't part of the package but allow you to > execute code; this makes testing and code exposition very convenient > because it can be done inline with the code itself. Now, the negatives. The first complaint is more ignorance than > anything: I've got no idea how to use the debugger. It's great that > it's there, but I don't understand how it's supposed to be used. Are > there any tutorials on this feature? Next: the editor *really* needs to make up its mind whether it's going > to support nice Mathematica symbols or not. It's ridiculous that > typing -> gives you a nice arrow, but then closing and re-opening > the file gives you the literal ascii. Worse, typing a complex > expression involving Greek letters and subscripts and accents looks > fine to start with but then turns into an unreadable mess when > re-opening the package. Since Mathematica can understand the FullForm in package files, I can't > see the harm in displaying it nicely in the .m file editor. Similarly, > the lack of nice spacing in the typesetting of the code is a shame and > makes packages look uglier -- usually requiring extra whitespace (and > effort) to be readable. Finally, the editor doesn't like code that has comments inserted > mid-way through. For example, paste this into a file test.m: (* ::Package:: *) > code[hello, > (* ::Text:: *) > (*some explanation*) > there] Open it in Mathematica, then select all, cut, and paste (this procedure > emulates you typing in those lines manually). Close and reopen the file > and you'll see that Mathematica has inserted two blank lines in the > code. Yuck. Furthermore, this sort of construction kills syntax colouring, which is > a big shame. > It also breaks the Run Package button, which tries to evaluate the > package cell by cell (instead, it should simply execute `< chunks of code when large packages deserve better comments than an > essay right before the Module with inline comments like (* we're doing > stuff here *). If those sorts of comments was the only way to document > the code then we may as well not even bother with cells, to be frank. *** To sum up: the .m file editor is pretty neat but two main additions > would make it much better: explicit support for breaking cells up with > comments whereever you like (including syntax checking and colouring > across cell breaks); and typesetting as in the the notebook editor > (including the extended symbols). In the very least, it shouldn't > interpret typeset symbols unless it intends to preserve them. The > typesetting doesn't affect anyone trying to edit the thing in plain > text and makes the whole thing much nicer to use. After all, without nice typesetting we may as well go back to notebooks > with initialisation cells, which have even less ability to be commented > nicely by splitting up cells partway through. Any comments from others also using the editor? Will Robertson I use the .m editor a lot - I really like it! I have just checked, and alpha and beta save and restore correctly in 6.0.2 - but I didn't think that changed from 6.0.1 (I am using the Windows version). I am tending towards using only .m files for all my code - reserving notebooks for manuals and other documents in which output cells need to be preserved. The fact that you can execute the .m file from the editor but the output cells are filtered out when you save it is also very convenient. I do wish there was a way to colour text in a .m file. David Bailey http://www.dbaileyconsultancy.co.uk