A30 Mathematica can indeed solve your equation with a simple command but the command is not Solve, because your problem is not actually algebraic but combinatorial. Therefore the right way to solve it is:In[1]:=< I have a question. Please help me. Can I solve the following > equation with> a simple Solve command in Mathematica?>> ((x1, x2, x3, x4): x1 + x2 + x3 + x4 == 4; x1, x2, x3, x4 are > nonnegative> integers}>> Munsup Seoh, PhD, Professor> Department of Mathematics and Statistics> Wright State University> 3640 Colonel Glenn Hwy> Dayton, OH 45435>> Homepage: www.wright.edu/~munsup.seoh>>Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/====WFH> I have a trouble in plotting e^x.WFH> Plot[e^x, {x, 1, 4}]WFH> It keeps telling me:WFH> e^x is not a machine-size real number at x = 1.000000125WFH> e^x is not a machine-size real number at x = 1.1217009747187472WFH> e^x is not a machine-size real number at x = 1.2544263995781209;WFH> Even I have added the modiÞer Evaluate.WFH> Plot[Evaluate[e^x], {x, 1, 4}]WFH> The output is the same.Please use E (capital) instead of e to denotethe base of natural logarithms. Alternatively,you may wish to use Exp[z] instead of E^zThus, Plot[{E^x, Exp[5x/4]}, {x, 1, 4}]works right.Best wishes,Vladimir BondarenkoMathematical and Production DirectorSymbolic Testing GroupWeb : http://www.CAS-testing.org/ (under development, 95% ready) http://maple.bug-list.org/ (under development, 20% ready)Mail : 76 Zalesskaya Str, Simferopol, Crimea, Ukraine====Dear experts,I have a trouble in plotting e^x. Plot[e^x, {x, 1, 4}]It keeps telling me:e^x is not a machine-size real number at x = 1.000000125e^x is not a machine-size real number at x = 1.1217009747187472e^x is not a machine-size real number at x = 1.2544263995781209;Even I have added the modiÞer Evaluate.Plot[Evaluate[e^x], {x, 1, 4}]The output is the same.Reply-To: kuska@informatik.uni-leipzig.de====try E instead of e if you mean thebasis of the natural logarithm. Jens> Dear experts,> I have a trouble in plotting e^x.> Plot[e^x, {x, 1, 4}]> It keeps telling me:> e^x is not a machine-size real number at x = 1.000000125> e^x is not a machine-size real number at x = 1.1217009747187472> e^x is not a machine-size real number at x = 1.2544263995781209;> Even I have added the modiÞer Evaluate.> Plot[Evaluate[e^x], {x, 1, 4}]> The output is the same.> ====Liquo.Song@vanderbilt.edu posted a message with the vague subject Is Mathematica capable of doing this?In that post the author want to know if he/she can deÞne a new object,Tensor, which will act like Complex. The he/she could implement a sort ofmultiplication of tensors.----------------Yes this can be done, except in Mathematica we don¹t have objects. BelowI deÞne TensorQ[expr] which returns True if expr is a tensor and otherwisereturns False.In[1]:= TensorQ[expr_]:=MatchQ[expr,_List?(Length[Dimensions[#]]=== Depth[#]-1&)]You don¹t explain how tensors are multiplied, and I know very little abouttensors. Hence I won¹t implement tensor multiplication, but in the nextline I deÞne a function that is only deÞned when it¹s two arguments aretensors. This function indicates if the two tensors have the samedimensions.In[2]:=SameDimensionsQ[t1_?TensorQ, t2_?TensorQ]:=(Dimensions[t1]===Dimensions[t2])------------It certainly is possible to implement super/sub-scripts to represent indicesfor a tensor. However, I won¹t try to implement it because I know verylittle about tensors.You can Þnd some stuff about tensors and Mathematica at:http://mathworld.wolfram.com/Tensor.html Also did you check the tensor package at:http://home.earthlink.net/~djmp/Mathematica.html---------- Ted ErsekDownload my latest Mathematica Tips, Tricks from http://www.verbeia.com/mathematica/tips/Tricks.html or from ====Plot[E^x,{x,1,4}]> Dear experts,>> I have a trouble in plotting e^x.> Plot[e^x, {x, 1, 4}]>> It keeps telling me:> e^x is not a machine-size real number at x = 1.000000125> e^x is not a machine-size real number at x = 1.1217009747187472> e^x is not a machine-size real number at x = 1.2544263995781209;>> Even I have added the modiÞer Evaluate.> Plot[Evaluate[e^x], {x, 1, 4}]> The output is the same.>====Wen-Feng,TryPlot[E^x, {x, 1, 4}]A small e has no special meaning or value in Mathematica, so e^x does notevaluated to a number. Capital E stands for the exponential constant. Youcan also use esc e e esc, or enter it from the BasicInput Palette.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/The output is the same.====> I have a question. Please help me. Can I solve the following equation with> a simple Solve command in Mathematica?> ((x1, x2, x3, x4): x1 + x2 + x3 + x4 == 4; x1, x2, x3, x4 are nonnegative> integers}One equation, four unknowns? I think Solve isn¹t what you want. I¹m notfamiliar with the optimization part of Mathematica (though I¹d like to be),but this certainly looks like an optimization with cost functionL = (x1 + x2 + x3 + x4) - 4 and constraints x1 > 0, x2 > 0, x3 > 0, x4 > 0.I assume this is a toy problem used to explore possible solutions of yourreal problem, as the answer x1 = x2 = x3 = x4 = 1 is pretty obvious byinspection.- Eric.-- ============================================================= ========You can lead an idiot to knowledge, but you can¹t make him think...===================================================== ================ ==== The lower-case e is not the same as the constant (approx.2.7182818 . . . .). You no doubt wish to use the constant. To enterthe constant, use either the capital E or the keystrokes:ee. Best, HarveyHarvey P. DaleUniversity Professor of Philanthropy and the LawDirector, National Center on Philanthropy and the LawNew York University School of LawRoom 206A110 West 3rd StreetNew York, N.Y. 10012-1074-----Original Message-----Plot[Evaluate[e^x], {x, 1, 4}]The output is the same.====But, before further questions, I have to explain myself. I am a newbie also. I have been using Mathematica for a couple of years, but never gave it a serious thought until recently. That¹s when I began to think about this Tensor stuff. So, I might not have all the solid background with Mathematica as other veterans on this list. :)As that cleared out, so I can ask some newbie questions now.First off, how do I deÞne the Tensor Head so that I can use Plus[x_Tensor]? The only thing that I can come close to that is to deÞne TensorQ and use Plus[x_?Tensor], which worked but not satisÞable.Second, how can I deÞne the Tensor Head so that I can associate Input of Subsuperscriptbox[A,ij,kj] to a Tensor with ij as subscript and kj as superscript? Just like Input A^i corresponds to Power[A,i].Again, thanks a lot for your input.Liguo> a further hint:> by: lst = List[x__], where x__ speciÞes the paramters e.g. of the> function Plus,> you get a list of the paramters and you can access them, easily.> Hermann Schmitt> ----- Original Message -----> To: Liguo Song > Cc: > Sent: Friday, November 01, 2002 11:02 AM>>you may use entries with Head Tensor, e.g. Tensor[xyz], where xyz>>identiÞes an speciÞc Tensor.>>Then you can deÞne functions Plus, Times, ... in the form:>>Plus[x__Tensor] := .......>>x__ Tensor means one ore more expressions with Head Tensor.>>Hermann Schmitt>>----- Original Message ----->>To: Sent: Friday, November 01, 2002 7:43 AM>>>>while. And>>>here are my answers for the questions that you brought out.>>First, about the super/sub-scripts. I can easily use a list of> True/False>>for>>>sub/super-script. I can combine this list with the List that represent> the>tensor together to for a new object, Tensor.>>Second, output formatting can be done easily with>>SubsuperscriptBox[string, sub,>>>sup], where string represents the name of the Tensor, sub/sup are> strings>>to>>>represent the scripts for the tensor. Spaces can be used to align the> sub>>and>>>super-scripts.>>So, it boils down the my Þrst question, how can I deÞne a object,>>Tensor,>>>which will behave like Complex? So, I can redeÞne Times, Plus, Minus,> and>>other>>>operators to handle Tensor.>>Also, how can I relate a symble to a Function as + relates Plus, *> relates>>to Times?>>>Again, thanks for your thoughts on this topic.>>>Liguo>>>>>Liguo,>>>>I think it is a dragon¹s egg and certainly not the best way to learn>>Mathematica. Basically you would have to Unprotect and add new>>>deÞnitions>>to Times and that would be only the start of it because how are you>>>going to>>distinguish between superscripts and powers? How are you going to>> handle>>mixed up and down indices? How are you going to get nice output>>>formatting?>>There are many nice tensor packages out there. The moderator of this>>>group>>has the original powerful tensor package. As a way of learning some>>>tensor>>calculus I have been working with Renan Cabrera on a package called>>Tensorial. It can be obtained at my web site below. It is oriented>>>toward>>learning the basic mechanics and reproducing textbook problems. You>> can>>have>>any symbols for tensor labels or indices. The index domain can be any>>>range>>of numbers or a set of symbols. For example, {0,1,2,3} or {t,x,y,z}>> for>>relativity problems. You can have colored indices to distinguish>>>different>>coordinate frames.>>>>Here is how one would do your two problems in Tensorial.>>>>Needs[TensorCalculus`Tensorial`]>>SetMetric[{x, g}, IdentityMatrix[3]]>>>>DeÞneTensorShortcuts[{T, g}, 2]>>>>guu[u, v]Tdd[v, k]>>% // MetricSimplify>>(formatted output)>>(formatted output, but Tud[u,k] in shortcut notation.)>>>>guu[u, v]Tdd[u, v]>>% // IndexEinstein>>(formatted output)>>(formatted output but Tdd[1,1] + Tdd[2,2] + Tdd[3,3] in shortcut>>>notation.)>>The DeÞneTensorShortcuts statement deÞnes T and g as labels of>> second>>order tensors. The various up and down index conÞgurations can be>>>speciÞed>>by appending u¹s or d¹s to the tensor label. So, for example,>>>gud[i,j]>>is the shortcut for g with the Þrst index i up, and the second index>> j>>down. Isn¹t that easier than maneuvering between superscripts and>>subscripts? MetricSimplify automatically carries our the raising or>>>lowering>>of indices with the metric tensor. IndexEinstein automatically carries>>>out>>summations on paired up and down indices.>>>>David Park>>djmp@earthlink.net>>http://home.earthlink.net/~djmp/>>> >>>To: mathgroup@smc.vnet.net>>>Dear MathGroup,>>>>I am in the process of learning to use Mathematica. Here are a couple>> of>>questions that I want to ask the group.>>>>1) Can I deÞne a new object, Tensor, which will act like Complex? So,>>>two>>Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Times>>>function>>to>>handle it.>>>>2) If the answer to the above question is yes, then can I use>>super/sub-scripts>>to represent the indices for the Tensor, and carry out the calculation>>>based>>on>>these indices? Such as, g^uv*T_vk will get T^u_k, which essentially>>>raises>>the>>Þrst index of T_vk. Another example would be g^uv*T_uv will get a>>>scalor T.>>I know there are couple of Tensor analysis packages, comercial and>> free,>>out>>there. But, all the free packages I looked through won¹t be able to do>>>this.>>And, Þguring out how to do stuff is the best to learn how to use>>Mathematica.>>>>Maybe, I am pursuing a dragon egg here. But, I¹d still like to hear>>>about>>how>>well Mathematica can do to imitate this behavior.>>>>>>Liguo>>>>>====Many thanks to all who replied to my query. As usual, I learned a lot from this group. My reason for asking for a solution was that I had originally tried using FindRoot, and became uncomfortable with it. Findroot seems to work well, as long as one is careful in one¹s choice of initial guesses. I have a large number of calculations to do, with a wide range in the solution choices. Hence, I chose my guess for the solution rather cavalierly as a fraction of the max time I was interested in. This led to some bad answers. At Þrst I thought the problem was my choice of .99 or .999 , where my interest lies. However, the problem exists elsewhere (the example I have chosen here was chosen because it also has an exact solution; the system I am interested in must be solved numerically). With an appropriate initial guess, FindRoot gives good answers (for this problem) over a wide range of max times and a wide range of intersection points. Even so, there are some traps (see the table below). I was surprised to see the bad behavior for w=0.3 and an initial guess of 1.1. This behavior shows up at other places, for larger values of tmax.Clear[y, t, tmax];tmax = 10;sol = NDSolve[{y¹[t] == 1 - y[t], y[0] == 0}, y, {t, 0., tmax}];fy = y /. sol[[1]];Plot[fy[t], {t, 0, tmax}, PlotRange -> All];Clear[g, xx, y, t, tmax, w];g[tmax_, w_] := Module[{y, sol, t, fy}, sol = NDSolve[{y¹[t] == 1 - y[t], y[0] == 0}, y, {t, 0., tmax}];fy = y /. sol[[1]]; FindRoot[fy[t] == w, {t, .1tmax}][[1, 2]]];Table[Table[g[n, w], {n, 7, 40}], {w, .1, .9, .1}] // MatrixFormI was unable to get Bobby¹s inverse method to work. It looks very interesting, and I will play with it some more.After reading Sergio Milo¹s suggestion, the approach of forming a table of y[t] and t and using Interpolation to form the inverse interpolating function occurred to me. This seems quite robust - at least, I haven¹t been able to get it to fail yet. Here is one example:tmax = 10;sol = NDSolve[{y¹[t] == 1 - y[t], y[0] == 0}, y, {t, 0., tmax}];fy = y /. sol[[1]];Plot[fy[t], {t, 0, tmax}, PlotRange -> All];z = Interpolation[Table[{fy[t], t}, {t, 0, tmax, .1}]];Plot[z[y], {y, 0, 1}, PlotRange -> All];z[.3]I look forward to trying Ted Ersek¹s package, as suggested by David Park.Phil>Use the inverse function computed as follows:>>sol = NDSolve[{y¹[t] == 1 - y[t], y[0] == 0}, y, {t, 0, 20}]>fy = y /. sol[[1]]>Dimensions /@ (List @@ fy)>data = Reverse /@ First@> Cases[Plot[fy[x], {x, 0, 20}, PlotRange -> All], Line[a_] -> a, 3];>inverse = Interpolation[data]>Plot[inverse[x], {x, 0, 1}, PlotRange -> All]>>DrBob>>-----Original Message----->To: mathgroup@smc.vnet.net>function>I wish to Þnd the value of the independent variable in an>interpolating function that makes the dependent variable assume some>value of interest. For example,>>sol = NDSolve[{y¹[t] == 1-y[t], y[0]==0}, y, {t, 0, 20}]>fy = y/.sol[[1]]>>produces an interpolating function. I would like to extract the>value of t that yields a value of 0.99 or 0.9999 (say) for y. Is>there a straightforward way of doing this?>>Phil>-->Philip M. Howe>Program Manager, Stockpile Surety>Los Alamos National Laboratory>>(505) 665-5332>(505) 667-9498>Mail Stop P945-- Philip M. HoweProgram Manager, Stockpile SuretyLos Alamos National Laboratory(505) 665-5332(505) 667-9498Mail Stop P945Reply-To: ====Use the inverse function computed as follows:sol = NDSolve[{y¹[t] == 1 - y[t], y[0] == 0}, y, {t, 0, 20}]fy = y /. sol[[1]]Dimensions /@ (List @@ fy)data = Reverse /@ First@ Cases[Plot[fy[x], {x, 0, 20}, PlotRange -> All], Line[a_] -> a, 3];inverse = Interpolation[data]Plot[inverse[x], {x, 0, 1}, PlotRange -> All]DrBob-----Original Message-----produces an interpolating function. I would like to extract the value of t that yields a value of 0.99 or 0.9999 (say) for y. Is there a straightforward way of doing this?Phil-- Philip M. HoweProgram Manager, Stockpile SuretyLos Alamos National Laboratory(505) 665-5332(505) 667-9498Mail Stop P945====I saw in Help (Mathematica 4.0) the Step-By-Step Differentiationtopic.I would like to know if it is possible to implement a Step-By-StepIntegration function in Mathematica.There is a site calc101.com which uses webMathematica and hasimplemented such a function.If it¹s not possible, are there any tools available which can?I¹m trying to learn integration of functions, and Integrate[...] isnot very usefull.CeZaR====I can use PowerExpand to go fromSqrt[x y] to Sqrt[x] Sqrt[y]How do I reverse this and go fromSqrt[x] Sqrt[y] to Sqrt[x y]--Dave SneadReply-To: kuska@informatik.uni-leipzig.de====Sqrt[x] Sqrt[y] /. c_.*Power[a_, n_]*Power[b_, n_] :> c*Power[a*b, n]But be carefull when x and y are complex. Jens> I can use PowerExpand to go from> Sqrt[x y] to Sqrt[x] Sqrt[y]> How do I reverse this and go from> Sqrt[x] Sqrt[y] to Sqrt[x y]> --Dave Snead====Alexey,You probably want some sort of rule based implementation, though these can be slow. John Browne mentions Grassmann algebra below but his code is not yet available. You can Þnd a rules based implementation of Grassman algebra--in the G.-C. Rota, et al version referred to as Peano algebra--in the package Peano.m that accompanies my Geometry and Computer Graphics lecture notes athttp://www.math.umd.edu/~gah/Pages/Math431Lecturesf02. htmlThis implementation is not really coordinate free since the operations are deÞned on basis vectors and extended by rules to be bilinear, but it shows how to use such rules to deÞne functions.Note: The notation is different in the Peano algera context. The exterior product is denoted by [Vee], instead of [Wedge] (which computes intersections) and the Clifford product is [CircleDot]Begin forwarded message:> To: mathgroup@smc.vnet.net> Reply-To: jbrowne@swin.edu.au>> Alexey,>> Below is a link to the draft of a book on Grassmann algebra. Although > not> the full tensor algebra, it might give you some ideas for what can be> achieved in Mathematica. I think you¹ll Þnd Mathematica is ideal for> encoding mathematical systems. The actual Grassmann algebra code is > still> being Þnalized, but should be available early next year.>> http://www.ses.swin.edu.au/homes/browne/grassmannalgebra/book /index.htm>> John>>> Dear colleagues.>> Can anyone help me with making direct tensor algebra in Mathematica?>> In direct tensor algebra tensors are not components. Tensors are >> special>> objects, that could be presented in the component form in sonme basis,>> but even then they dont appear as S_{mn}, but as>> S_{mn}r^m r^n>> where r^m and r^n - are vectors of reciprocal basis and S_{mn} ->> covariant components. NB! Basis vectors, are not columns like {1,0,0},>> but exaclty vectors i.e. directed line segment as is.>> Is it possible to make this kind of package in Mathematica, that could>> deal with such objects and also go to the component form - on the >> lower>> level of abstraction - on demand.>> In particular such system would calculate that>> a . b x a = 0 (mixed product - cross and dot) WITHOUT making the>> constructs like>> E^{mnk}b_m a_n a_k, where E^{mnk} - Levi-Chivitta symbols.>> The example is on leshakk.chat.ru - Þle tensor.pdf>> -- _________________________________> John Browne> School of Engineering and Science> Swinburne University of Technology> John Street, Hawthorn, Victoria, Australia> Quantica phone: +613 9431 4007> Quantica fax: +613 9431 0940>Garry HelzerDepartment of MathematicsUniversity of Maryland1303 Math BldgCollege Park, MD 20742-4015====----- Original Message -----> So, I might not have all the solid background with Mathematica as otherveterans> on this list. :)>> As that cleared out, so I can ask some newbie questions now.>> First off, how do I deÞne the Tensor Head so that I can usePlus[x_Tensor]? The> only thing that I can come close to that is to deÞne TensorQ and use> Plus[x_?Tensor], which worked but not satisÞable.>I should say you have to do nothing. I show you an example below. But Iforgot to mention, that you must Unprotect the symbol Plus, if you want tochange the deÞnition of Plus (in the same way the other symbols).The Þrst part below is the input, the second part is the output. I added anormal addition, in order that you can see, that this functions normally:In[81]:= Plus[x__Tensor]:= Print[Hallo TensorPlus with Parameters: ,List[x]];Unprotect[Plus];tns1 = Tensor[xyz1]tns2 = Tensor[xyz2]Plus[tns1, tns2]3 + 4Out[83]= {Flat, Listable, NumericFunction, OneIdentity, Orderless}Out[84]= Tensor[xyz1]Out[85]= Tensor[xyz2]Hallo TensorPlus with Parameters: {Tensor[xyz1], Tensor[xyz2]}Out[87]= 7In[88]:=> Second, how can I deÞne the Tensor Head so that I can associate Input of> Subsuperscriptbox[A,ij,kj] to a Tensor with ij as subscript and kj as> superscript? Just like Input A^i corresponds to Power[A,i].I cannot help you with the second question. I think, that you have to workwith indexed variables during the calculations:A[,i, j, k] ??>Hermann Schmitt> Again, thanks a lot for you input.> Liguo>> a further hint:> by: lst = List[x__], where x__ speciÞes the paramters e.g. of the> function Plus,> you get a list of the paramters and you can access them, easily.> Hermann Schmitt> ----- Original Message -----> To: Liguo Song > Cc: > Sent: Friday, November 01, 2002 11:02 AM>>>>>you may use entries with Head Tensor, e.g. Tensor[xyz], where xyz>>identiÞes an speciÞc Tensor.>>Then you can deÞne functions Plus, Times, ... in the form:>>Plus[x__Tensor] := .......>>x__ Tensor means one ore more expressions with Head Tensor.>>Hermann Schmitt>>----- Original Message ----->>To: >>Sent: Friday, November 01, 2002 7:43 AM>>while. And>here are my answers for the questions that you brought out.>>First, about the super/sub-scripts. I can easily use a list of> True/False>>>for>sub/super-script. I can combine this list with the List that represent> the>>tensor together to for a new object, Tensor.>>Second, output formatting can be done easily with>>SubsuperscriptBox[string, sub,>sup], where string represents the name of the Tensor, sub/sup are> strings>>>to>represent the scripts for the tensor. Spaces can be used to align the> sub>>>and>super-scripts.>>So, it boils down the my Þrst question, how can I deÞne a object,>>Tensor,>which will behave like Complex? So, I can redeÞne Times, Plus, Minus,> and>>>other>operators to handle Tensor.>>Also, how can I relate a symble to a Function as + relates Plus, *> relates>>>to Times?>Again, thanks for your thoughts on this topic.>>>Liguo>>>>>Liguo,>>>>I think it is a dragon¹s egg and certainly not the best way to learn>>Mathematica. Basically you would have to Unprotect and add new>>>deÞnitions>>to Times and that would be only the start of it because how are you>>>going to>>distinguish between superscripts and powers? How are you going to>> handle>>>mixed up and down indices? How are you going to get nice output>>>formatting?>>There are many nice tensor packages out there. The moderator of this>>>group>>has the original powerful tensor package. As a way of learning some>>>tensor>>calculus I have been working with Renan Cabrera on a package called>>Tensorial. It can be obtained at my web site below. It is oriented>>>toward>>learning the basic mechanics and reproducing textbook problems. You>> can>>>have>>any symbols for tensor labels or indices. The index domain can be any>>>range>>of numbers or a set of symbols. For example, {0,1,2,3} or {t,x,y,z}>> for>>>relativity problems. You can have colored indices to distinguish>>>different>>coordinate frames.>>>>Here is how one would do your two problems in Tensorial.>>>>Needs[TensorCalculus`Tensorial`]>>SetMetric[{x, g}, IdentityMatrix[3]]>>>>DeÞneTensorShortcuts[{T, g}, 2]>>>>guu[u, v]Tdd[v, k]>>% // MetricSimplify>>(formatted output)>>(formatted output, but Tud[u,k] in shortcut notation.)>>>>guu[u, v]Tdd[u, v]>>% // IndexEinstein>>(formatted output)>>(formatted output but Tdd[1,1] + Tdd[2,2] + Tdd[3,3] in shortcut>>>notation.)>>The DeÞneTensorShortcuts statement deÞnes T and g as labels of>> second>>>order tensors. The various up and down index conÞgurations can be>>>speciÞed>>by appending u¹s or d¹s to the tensor label. So, for example,>>>gud[i,j]>>is the shortcut for g with the Þrst index i up, and the second index>> j>>>down. Isn¹t that easier than maneuvering between superscripts and>>subscripts? MetricSimplify automatically carries our the raising or>>>lowering>>of indices with the metric tensor. IndexEinstein automatically carries>>>out>>summations on paired up and down indices.>>>>David Park>>djmp@earthlink.net>>http://home.earthlink.net/~djmp/>>> >>>To: mathgroup@smc.vnet.net>>>Dear MathGroup,>>>>I am in the process of learning to use Mathematica. Here are a couple>> of>>>questions that I want to ask the group.>>>>1) Can I deÞne a new object, Tensor, which will act like Complex? So,>>>two>>Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Times>>>function>>to>>handle it.>>>>2) If the answer to the above question is yes, then can I use>>super/sub-scripts>>to represent the indices for the Tensor, and carry out the calculation>>>based>>on>>these indices? Such as, g^uv*T_vk will get T^u_k, which essentially>>>raises>>the>>Þrst index of T_vk. Another example would be g^uv*T_uv will get a>>>scalor T.>>I know there are couple of Tensor analysis packages, comercial and>> free,>>>out>>there. But, all the free packages I looked through won¹t be able to do>>>this.>>And, Þguring out how to do stuff is the best to learn how to use>>Mathematica.>>>>Maybe, I am pursuing a dragon egg here. But, I¹d still like to hear>>>about>>how>>well Mathematica can do to imitate this behavior.>>>>>>>>Liguo>>>>>>>====I¹ve been looking for a while, and I can¹t Þnd a way to create any sort of structured data type in Mathematica, i.e. one with named Þelds that contain other values. Does such a beast exist?Ken McDonaldkmmcdonald@wisc.eduReply-To: ====I hope Tech Support can help with this.When I run the Figure-8 animation, I get the not enough memory todisplay a cell message and then the not enough memory to do what youasked message. I have to close and reopen Mathematica to get a usabledisplay.I have this problem with many animations (SpinShow, etc...) -- with orwithout DrawGraphics -- despite having 1024MB of RAM. I¹m using version4.2 and WinXP Home, and I had the same problem with version 4.1. Theproblem is very consistent, in that each animation either always worksor never does. If I reduce the number of frames enough, the animationworks. The Figure-8, for instance, works if I change the step size from2Pi/50 to 8Pi/50.I have had no memory problems with other applications -- including SAS8.2, Photoshop 7, Prime95, etc.Help?Bobby-----Original Message-----Hermann Weyl seem to have this kind of mechanism build into thier brains, and therefore don¹t need no stinkin¹ computer.)While I was exploring this animation I noticed something rather strangeabout the CPU¹s behavior. If I open Help Browser -> Add-Ons -> DrawGraphics-> Examples -> Figure Eight Animation, the CPU utilization is virtually 0.I evaluate the Þrst cell to load the package and the CPU jumps for asecond and then settles back down. I then select the remainder of thenotebook. The CPU utilization remains very low. Then I evaluate it. The CPU utilization jumps way up, as is to be expected. The animation framesare created, and the animation runs Þne. The CPU utilization remains veryhigh.The interesting observation comes when I stop the animation by quittingthe local kernel. If I select the cell holding the graphic, I notice theCPU utilization jups to 98%+-. The kernel isn¹t even running at this time.When I say I select the cell holding the graphic, I mean to say I select thebrace to the right which has the Œfoldable¹ indicator. Selecting theinner-most brace does not cause the CPU utilization to increase, but selecting anyof its parents does.Can someone explain this?You can Þnd the DrawGraphics package here:http://home.earthlink.net/~djmp/Mathematica.html-- STHHatton¹s Law: There is only One inviolable Law.Reply-To: ====E, not e, stands for the Napierian base.DrBob-----Original Message-----Plot[Evaluate[e^x], {x, 1, 4}]The output is the same.====strgh> Is there any guide as to when Mathematica gives incorrectstrgh> results for an integral? For example,strgh> Integrate[ 1/(1 + x^2y^2), {x, 0, InÞnity}, {y, 0, x} ]strgh> returns 0.It is safer to use the following syntax Out[1] = 4.2 for Microsoft Windows (June 5, 2002) In[2] := Integrate[Integrate[1/(1 + x^2y^2), {x, 0, InÞnity}], {y, 0, x}] Out[2] = Integrate::idiv : Integral of (Log[-I y] - Log[-I y])/y does not converge on {0, x}. Integrate::idiv : Integral of (Log[-I y] - Log[-I y])/y does not converge on {0, x}. (I/2)*Integrate[(Log[(-I)*y] - Log[I*y])/y, {y, 0, x}]As you can see, Mathematica returns the correct output.The same holds for the following versions 4.1 for Microsoft Windows (November 2, 2000) 4.0 for Microsoft Windows (April 21, 1999)The version for Microsoft Windows 3.0 (April 25, 1997) yields Integrate[If[Arg[y^2] != Pi, Pi/(2*Sqrt[y^2]), Integrate[(1 + x^2*y^2)^(-1), {x, 0, InÞnity}]], {y, 0, x}]The version for Windows 387 2.2 (April 9, 1993) returns (Pi*Integrate[(y^2)^(-1/2), {y, 0, x}])/2The version for Windows (September 27, 1989) returns...In case if you still use the version 1.2 for Microsoft Windows(September 27, 1989)... well... why do NOT consider thegolden opportunity of the upgrade? ;-)Best wishes,Vladimir BondarenkoMathematical and Production DirectorSymbolic Testing GroupWeb : http://www.CAS-testing.org/ (under development, 95% ready) http://maple.bug-list.org/ (under development, 20% ready)Mail : 76 Zalesskaya Str, Simferopol, Crimea, Ukraine====Is there any guide as to when Mathematica gives incorrectresults for an integral? For example,Integrate[ 1/(1 + x^2y^2), {x, 0, InÞnity}, {y, 0, x} ]returns 0.I¹m guessing Mathematica tries to expand the integrandas partial fractions, but has difÞculties with branch points-- is that correct?====Some of you have reported that the Mathematica newsgroup messageswere not reaching your news servers since October 24. I contactedmy ISP and they were able to track down where on the net the problemwas. It has been Þxed and all back messages have been sent outagain.Sorry for the delays.Steve ChristensenModerator====in my OO`System it is not difÞcult to program.The kind of usage is very similar to the kind Java classes and Java objectsare accessed from Mathematica in J/Link.Hermann Schmitt----- Original Message -----> oriented+programming> mentions both encapsulation and inheritance.> Furthermore, OOP does not imply a particular syntax. For example,> myinstance.mymethod(args) and mymethod(myinstance,args) are both> perfectly legitimate OOP syntaxes.> The FOLDOC deÞnition is good but I prefer to refer people to the> Object Orientation FAQ at http://www.cyberdyne-object-sys.com/oofaq/.> As has been pointed out encapsulation already exists in any modular> language, Mathematica has it through contexts, if you use header Þles> correctly C has encapsulation, so do Modula, Ada and nearly any other> language developed since 1970.>> Inheritance is a sticky subject. It derives (no pun intended) from> system design considerations but in practice it is closely tied to> attempts to increase code reuse in strongly typed, static, imperative> languages. Note that Mathematica has none of these qualities. See> section 1.7 of the OO FAQ for a cogent discussion of inheritance.> Since everything in Mathematica is of the same type: an expression and> in the most general case a function can take any expression as an> argument there is little need for inheritance in Mathematica. Instead> Mathematica programmers can force inheritance structures by restricting> function arguments to a particular pattern in which case the pattern> could be considered to deÞne a type and if the pattern is> appropriately designed as Alexander did in his examples then we could> consider a hierarchy of types to which the function applies thus> getting an inheritance tree.> The biggest gain in my opinion from OOP is neither encapsulation, which> has existed nearly as long as high level languages have been known, nor> inheritance which necessarily exists in languages with pattern matching> facilities such as Prolog and thus also has been known to programmers> since long before the current OOP craze. The main facility for code> reuse is polymorphism which in my opinion is closely related to> inheritance but obviously is not identical, see section 2 of the OO> FAQ. Again, Mathematica has always supported polymorphism through the> possibility of a function having multiple downvalues. However the> downvalue and pattern matching mechanism together are more akin to> parametric polymorphism. Here is where I show myself to be a heretic:> parametric polymorphism and encapsulation are all you need for OOP,> inheritance is unnecessary. If you deÞne an appropriate set of> polymorphic functions then your inheritance hierarchy will be> implicitly deÞned. I admit that this is an extreme view.>> One of the primary beneÞts of OOP is that you can subclass> pre-existing classes, _without modifying or recompiling_ the existing> class code, and objects designed for the superclass can use the> subclass without knowing it. This greatly facilitates the REUSE of code> and increases the þexibility of libraries.>> And ultimately that is the goal: a small þexible library. However I> will repeat my heresy, you can either design an elaborate inheritance> hierarchy and specialize methods from the base class as you descend or> equivalently you can deÞne a set of types (or patterns although the> two are not exactly equivalent) and an appropriate set of functions on> preferable, for implementation however the latter seems to me to be> more effective.>> The pervasiveness of the OOP paradigm has made it seem somewhat like> the one true way to structure a program, but I think a moments> reþection leads most people to concede that, while wonderful, it is> not a panacea (e.g. the Standard Template Library for C++ is less OOP> and more functional programming).>> Or functional programming (with patterns/guards or strong typing) is> more OOP than we realized.>> Of course, there are other ways to this, but this is just an example of> simple and natural way to provide basic data inheritance with method> specialization in your Mathematica programs.> Is it just me or does this resemble the Common Lisp Object System? Is> that a coincidence? I have always believed that Mathematica possessed> the necessary facilities for OOP the problem is the amount of> programmer effort necessary to program in an OOP style with> Mathematica. So it seems some kind of syntactic assistance is all that> is necessary: functions to allow easy deÞnition of constructors,> destructors, class relationships etc. and easy inspection of the same.> My guess is that the end result will closely resemble CLOS but given> the protest most programmers make when faced with the LISP paradigm I> think many Mathematica users would be unhappy with the end result.> SseziwaReply-To: ====haven¹t seen the hoped-for beneÞt, however. Projects and programmersstill break on the rocks of complexity. I really like Smalltalk as alanguage, and it has a very rich class library, but the latter makes fora steep learning curve. When we want to DO something, we must study ahost of objects that know how to do that, and somehow pick out one thathas all the right characteristics. Writing interesting classes fromscratch is fun, but getting good use of existing classes is difÞcult.(To all that complexity, C++ users add a bloated syntax that produces anunmatched ability to write code the C++ expert next door can¹tdecipher.)Complexity in design and programming (not a scarcity of languagefeatures) is usually the enemy, and OO is an incomplete countermeasureat best.As for OOP and Mathematica in particular, it seems that computer algebrais far more about operations than data. If we write x+y as an algebraicexpression, we care only that Plus is Orderless and Flat, no matter whatkind of things x and y are. True, Plus can be a method ofUndeÞnedSymbol and most objects can inherit from that, but we have thesame behavior already through Pattern matching. FlatOperation andOrderlessOperation classes could lead us to a whole matrix of operationand data classes interacting together -- and a class library thatboggles the mind. In effect, that¹s what we already have, but we get toconcentrate on the operations, and on objects for which optimizedoperations exist.We have to concentrate on SOMETHING, I think, so mixing OOP andfunctional programming seems a recipe for confusion.Bobby-----Original Message-----Furthermore, OOP does not imply a particular syntax. For example, myinstance.mymethod(args) and mymethod(myinstance,args) are both perfectly legitimate OOP syntaxes.One of the primary beneÞts of OOP is that you can subclass pre-existing classes, _without modifying or recompiling_ the existing class code, and objects designed for the superclass can use the subclass without knowing it. This greatly facilitates the REUSE of codeand increases the þexibility of libraries. What amuses me is that the wild popularity of OOP seems to be _partly_ due to the new OOP languages having better module systems (than C, for example) as well as a syntax which encourages the use of modularity, and _partly_ due topeople Þnding the metaphors of OOP helpful in structuring their thinking.The pervasiveness of the OOP paradigm has made it seem somewhat like the one true way to structure a program, but I think a moments reþection leads most people to concede that, while wonderful, it is not a panacea (e.g. the Standard Template Library for C++ is less OOP and more functional programming). One of the difÞculties of OOP¹s pervasiveness is that it is the only paradigm many people know, so whenthey approach a problem in a language that does not support OOP, they both do not understand the new paradigm well enough to structure their thinking appropriately for the language and they do not know the necessary idioms to effectively express chunks of computation.All that said, you can build basic data hierarchies in your Mathematicaprograms quite easily if you encode the collection of data associated with an object as a list of rules and specialize function deÞnitions (methods) using pattern matching. Here is a simple example:obj={name->instance of superclass,data->1};printname[{___,name->name_,___}]:=Print[ name]printname[obj]getdata[{___,data->data_,___}]:= datagetdata[obj]subobj={name->instance of subclass,data->2, subdata->{20,30}};printname[subobj]getdata[{___,data->data_, subdata->subdata_,___}]:={data,subdata}getdata[subobj]getdata [obj]You can formalize this is various ways, by deÞning object constructorsand so on. At the very least, you want to avoid typing these pattern matches all the time. Assigning the pattern to a variable essentially deÞnes a class type:class={___,name->name_,data->data_,___};subclass=Join[ class,{subdata->subdata_,___}];mymethod[class,a_]:=a* datamymethod[subclass,a_]:=a*data*{1,1}.subdatamymethod[obj,2 ]mymethod[subobj,2]Of course, there are other ways to this, but this is just an example ofsimple and natural way to provide basic data inheritance with method specialization in your Mathematica programs.Alex====I have a 3x3 gridbox and I would like to enclose a 2x2 block within inparenthesis to indicate to a reader that I am operating only on that part ofthe matrix (gridbox).I can only seem to get parethesis added to individual elements. Any ideas?MikeReply-To: murray@math.umass.edu====You can do this directly from Mathematica¹s Input > Create Table/Matrix/Palette menu choice: Create the larger matrix. Then select the placeholder in the spot where the smaller matrix is to go and use that menu choice again.>>I have a 3x3 gridbox and I would like to enclose a 2x2 block within in>>parenthesis to indicate to a reader that I am operating only on that part of>>the matrix (gridbox).>>I can only seem to get parethesis added to individual elements. Any ideas?>>Mike> Actually it was simple:> Cell[TextData[Cell[BoxData[> RowBox[{(, GridBox[{> {> RowBox[{(, GridBox[{> {0, 0},> {0, 0}> }], )}], GridBox[{> {0},> {0}> }]},> {GridBox[{> {0, 0}> }], 0}> }], )}]]]], Text]> Mike> -- Murray Eisenberg murray@math.umass.eduMathematics & Statistics Dept.Lederle Graduate Research Tower phone 413 549-1020 (H)University of Massachusetts 413 545-2859 (W)710 North Pleasant StreetAmherst, MA 01375Reply-To: kuska@informatik.uni-leipzig.de====something likeRowBox[{(, GridBox[{{RowBox[{(, GridBox[{{a, b}, {c, d}}], )}], GridBox[{{e}, {f}}]}, {GridBox[{{g, h}}], d}}], )}] // DisplayForm Jens> I have a 3x3 gridbox and I would like to enclose a 2x2 block within in> parenthesis to indicate to a reader that I am operating only on that part of> the matrix (gridbox).> I can only seem to get parethesis added to individual elements. Any ideas?> Mike====> I think it is probably possible to use ListCorrelate in the following way:> ListCorrelate[{(j-1)*X, Y,(j+1)*Z},{a,b,c,d,....}]> Where j changes as they move along the row. The change reþects the position> or part of the element they are operating on. For example initially j =2> then 3, 4...and the output would be> {(2-1)*X*a+Y*b+(2+1)*Z*c,(3-1)*X*b+Y*c+(3+1)*Z*d, ...}> I¹ve tried to replace Times in ListCorrelate with a function that will do> this but had no success. If I can get this simple example to work I will> take this and Map a Matrix onto it:> ListCorrelate[{(j-1)*X, Y,(j+1)*Z},#]&/@ list> This will be part of a larger function which I¹ve written alternatively> using MapThread and Map but I think it should work a lot faster if I can> incorporate ListCorrelate.> MikeOne approach might be to start with the list correlation result obtainedwith j Þxed. I will illustrate using a list of 7 elements.j = 2;ll = Array[aa,7];kernel = {(j-1)*X,Y,(j+1)*Z};l1 = ListCorrelate[kernel, ll];Now do the list correlate with kernel {1,0,1}:l2 = ListCorrelate[{X,0,Z}, ll];We want to add sequential multiples of this to l1. The multiplier isjust the list {0,1,2,...}.l3 = Range[0,Length[l2]-1];result = Expand[l1+l2*l3]Out[24]= {X aa[1] + Y aa[2] + 3 Z aa[3], 2 X aa[2] + Y aa[3] + 4 Zaa[4], 3 X aa[3] + Y aa[4] + 5 Z aa[5], 4 X aa[4] + Y aa[5] + 6 Z aa[6], 5 X aa[5] + Y aa[6] + 7 Z aa[7]}Daniel LichtblauWolfram Research====I think it is probably possible to use ListCorrelate in the following way:ListCorrelate[{(j-1)*X, Y,(j+1)*Z},{a,b,c,d,....}]Where j changes as they move along the row. The change reþects the positionor part of the element they are operating on. For example initially j =2then 3, 4...and the output would be{(2-1)*X*a+Y*b+(2+1)*Z*c,(3-1)*X*b+Y*c+(3+1)*Z*d, ...}I¹ve tried to replace Times in ListCorrelate with a function that will dothis but had no success. If I can get this simple example to work I willtake this and Map a Matrix onto it:ListCorrelate[{(j-1)*X, Y,(j+1)*Z},#]&/@ listThis will be part of a larger function which I¹ve written alternativelyusing MapThread and Map but I think it should work a lot faster if I canincorporate ListCorrelate.Mike====Mike, Daniel, Clear[`*]; j=2; ll = Array[aa,7]; With[{kernel = Unevaluated[{(j-1)*X,Y,(j+++1)*Z}]}, ListCorrelate[kernel,ll]] {X aa[1]+Y aa[2]+3 Z aa[3],2 X aa[2]+Y aa[3]+4 Z aa[4], 3 X aa[3]+Y aa[4]+5 Z aa[5],4 X aa[4]+Y aa[5]+6 Z aa[6], 5 X aa[5]+Y aa[6]+7 Z aa[7]}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198> I think it is probably possible to use ListCorrelate in the following way:>> ListCorrelate[{(j-1)*X, Y,(j+1)*Z},{a,b,c,d,....}]>> Where j changes as they move along the row. The change reþects theposition> or part of the element they are operating on. For example initially j =2> then 3, 4...and the output would be>> {(2-1)*X*a+Y*b+(2+1)*Z*c,(3-1)*X*b+Y*c+(3+1)*Z*d, ...}>> I¹ve tried to replace Times in ListCorrelate with a function that will do> this but had no success. If I can get this simple example to work I will> take this and Map a Matrix onto it:>> ListCorrelate[{(j-1)*X, Y,(j+1)*Z},#]&/@ list>> This will be part of a larger function which I¹ve written alternatively> using MapThread and Map but I think it should work a lot faster if I can> incorporate ListCorrelate.> Mike>====> Consider yer basic 3d6 stat roll: What are the possibilities?> This gives a table of all 6^3 = 216 rolls:> Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}] // MatrixForm> My question is this: How shall I set up a formula to list the count of each> total?One approach might be to mess with elements of(x[1]+x[2]+x[3]+x[4]+x[5]+x[6])^3. The code below will do this. I¹m sureit can be made more efÞcient e.g. by cutting down on use of patternmatching.ddice[sides_,n_] := Module[ {x,sum,pow,ll1,ll2,ll3,ll4,ll5}, sum = Apply[Plus, Array[x,sides]]; pow = Expand[sum^n]; ll1 = Apply[List,pow]; ll2 = ll1 /. x[j_]^k_. -> ll[k*j]; ll3 = ll2 //. {ll[j_]*ll[k_] -> ll[j+k], ll[j_]^k_->ll[k*j]}; ll4 = ll3 /. a_.*ll[b_] -> {b,a}; ll5 = Split[Sort[ll4], #1[[1]]==#2[[1]]&]; Map[{#[[1,1]],Apply[Plus,Map[#[[2]]&,#]]}&, ll5] ]Example:In[17]:= ddice[6,3]Out[17]= {{3, 1}, {4, 3}, {5, 6}, {6, 10}, {7, 15}, {8, 21}, {9, 25}, {10, 27}, {11, 27}, {12, 25}, {13, 21}, {14, 15}, {15, 10}, {16, 6}, {17, 3}, {18, 1}}The efÞciency is not terrible. It will handle 9 throws of dice with 10sides in around 11 seconds on my machine.In[18]:= InputForm[Timing[ddice[10,9]]]Out[18]//InputForm= {10.76*Second, {{9, 1}, {10, 9}, {11, 45}, {12, 165}, {13, 495}, {14,1287}, {15, 3003}, {16, 6435}, {17, 12870}, {18, 24310}, {19, 43749}, {20,75501}, {21, 125565}, {22, 202005}, {23, 315315}, {24, 478731}, {25, 708444}, {26, 1023660}, {27, 1446445}, {28, 2001285}, {29, 2714319}, {30,3612231}, {31, 4720815}, {32, 6063255}, {33, 7658190}, {34, 9517662}, {35,11645073}, {36, 14033305}, {37, 16663185}, {38, 19502505}, {39, 22505751}, {40, 25614639}, {41, 28759500}, {42, 31861500}, {43, 34835625}, {44, 37594305}, {45, 40051495}, {46, 42126975}, {47, 43750575}, {48, 44865975}, {49, 45433800}, {50, 45433800}, {51, 44865975}, {52, 43750575}, {53, 42126975}, {54, 40051495}, {55, 37594305}, {56, 34835625}, {57, 31861500}, {58, 28759500}, {59, 25614639}, {60, 22505751}, {61, 19502505}, {62, 16663185}, {63, 14033305}, {64, 11645073}, {65, 9517662}, {66, 7658190}, {67, 6063255}, {68,4720815}, {69, 3612231}, {70, 2714319}, {71, 2001285}, {72, 1446445}, {73,1023660}, {74, 708444}, {75, 478731}, {76, 315315}, {77, 202005}, {78, 125565}, {79, 75501}, {80, 43749}, {81, 24310}, {82, 12870}, {83, 6435}, {84,3003}, {85, 1287}, {86, 495}, {87, 165}, {88, 45}, {89, 9}, {90, 1}}}I wonder if there are faster direct approaches using e.g. multinomialcoefÞcients?Daniel LichtblauWolfram Research====Try this:In[1]:=Apply[Plus,Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}]]Out[1]={{33,39,45,51,57,63},{39,45,51,57,63,69},{ 45,51,57,63,69,75},{51,57,63,69,75, 81},{57,63,69,75,81,87},{63,69,75,81,87,93}}Tomas GarzaMexico City----- Original Message ----->====Consider yer basic 3d6 stat roll: What are the possibilities?This gives a table of all 6^3 = 216 rolls:Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}] // MatrixFormMy question is this: How shall I set up a formula to list the count of eachtotal?====Dave,Here is a RootsTogether routine excerpted from the ExpressionManipulationpackage at my web site. Ted Ersek helped program this routine.RootsTogether::usage = RootsTogether[expr] will put factors involving the same kind of root together under one root sign. Like PowerExpand it is not always a permissible operation. Mathematica automatically removes numeric factorsfrom root expressions.;RootsTogether[expr_] := Module[{numbertest, radicalexpand, togetherrules}, numbertest = FreeQ[#1, Complex] && !NumericQ[#1] & ; radicalexpand = (a_^p_Integer)^q_Rational :> a^(p*q); togetherrules = {(n_.)*(a_)?numbertest^q_Rational*(b_)?numbertest^ q_Rational :> n*(a*b)^q, (n_.)*(a_)?numbertest^p_Rational*(b_)?numbertest^ q_Rational /; p + q == 0 && p > q :> n*(a/b)^p, (n_.)*(a_)?numbertest^(Rational[na_, r_])*(b_)?numbertest^(Rational[nb_, r_]) :> n*(a^na*b^nb)^(Rational[1, r])}; expr //. radicalexpand //. togetherrules]Sqrt[x y]% // PowerExpand% // RootsTogethergivesSqrt[x*y]Sqrt[x]*Sqrt[y]Sqrt[x*y]The routine will also work on roots other than square and roots in thedenominator.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator====Ken,You are rather edging into OO programming, of which there has been somediscussion on this news group in the past week or so. Perhaps there is roomfor something like a StructuredData package that would be considerably lessthan OO but serve a useful purpose.In any case, you could do something like the following where I deÞne aCircleType data item and a few routines for manipulating it.CircleType = {{_, _}, _};ConstructCircle[position : {_, _}, radius_] := {position, radius}GetRadius[circle : CircleType] := Part[circle, 2]GetPosition[circle : CircleType] := Part[circle, 1]Attributes[SetRadius] = {HoldFirst};SetRadius[circle_][radius_] := (circle = ReplacePart[circle, radius, 2];)mycircle = ConstructCircle[{1, 2}, 3];GetRadius[mycircle]3GetPosition[mycircle]{1, 2}SetRadius[mycircle][3.5]GetRadius[mycircle]3.5etc. I hope you get some other good discussion of this because it is a veryuseful question.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator====below I show you, how the example of David can be programmed with my OOSystem for Mathematica. It did really run on my computer----- Original Message -----> than OO but serve a useful purpose.>> In any case, you could do something like the following where I deÞne a> CircleType data item and a few routines for manipulating it.>> CircleType = {{_, _}, _};> ConstructCircle[position : {_, _}, radius_] := {position, radius}> GetRadius[circle : CircleType] := Part[circle, 2]> GetPosition[circle : CircleType] := Part[circle, 1]> Attributes[SetRadius] = {HoldFirst};> SetRadius[circle_][radius_] := (circle = ReplacePart[circle, radius, 2];)>> mycircle = ConstructCircle[{1, 2}, 3];>> GetRadius[mycircle]> 3>> GetPosition[mycircle]> {1, 2}>> SetRadius[mycircle][3.5]> GetRadius[mycircle]> 3.5>> etc. I hope you get some other good discussion of this because it is avery> useful question.>> David ParkFirst, I tried to program as similar to the example of David as possible.But when I chose the function names getRadius and setRadius ( and anlog withPosition) I got spelling checks, therefore I changed the names of the set functions.The Class Circle:{Circle, parent[] = {},status = {{xpos, ypos}, radius};,CircleInit[xp_, yp_, rd_] := Module[{}, xpos = xp; ypos = yp; radius = rd;];getRadius[] := Return[radius];setRad[rd_] := radius = rd;getPosition[] := Return[{xpos, ypos}];setPos[xp_, yp_] := (xpos = xp; ypos = yp;);}The Program: obj1 = MathNew[Circle, 1, 2, 3]; Print[Radius: , obj1 @ getRadius[]]; Print[Position: , obj1 @ getPosition[]]; obj1 @ setRad[3.5]; Print[Radius: , obj1 @ getRadius[]]; obj1 @ setPos[4, 5]; Print[Position: , obj1 @ getPosition[]];The Result:Radius: 3Position: {1, 2}Radius: 3.5Position: {4, 5}In[44]:=I programmed a second version of the program, because I thought, that in OOPosition should be a separate class, because in can be used in many otherapplications.The program remains the same.The Class Circle:{Circle, parent[] = {Position},status = {radius};,CircleInit[xp_, yp_, rd_] := Module[{}, PositionInit[xp, yp]; radius = rd;];getRadius[] := Return[radius];setRad[rd_] := radius = rd;}The Class Position:{Posion, parent[] = {}, status = {xpos, ypos};PositionInit[xp_, yp_] := Module[{}, xpos = xp; ypos = yp;];,getPosition[] := Return[{xpos, ypos}];setPos[xp_, yp_] := (xpos = xp; ypos = yp;);}> djmp@earthlink.net> http://home.earthlink.net/~djmp/> To: mathgroup@smc.vnet.net>> I¹ve been looking for a while, and I can¹t Þnd a way to create any> sort of structured data type in Mathematica, i.e. one with named Þelds> that contain other values. Does such a beast exist?>> Ken McDonald> kmmcdonald@wisc.edu>====> CircleType = {{_, _}, _};> ConstructCircle[position : {_, _}, radius_] := {position, radius}> GetRadius[circle : CircleType] := Part[circle, 2]> GetPosition[circle : CircleType] := Part[circle, 1]> Attributes[SetRadius] = {HoldFirst};> SetRadius[circle_][radius_] := (circle = ReplacePart[circle, radius, 2];)It¹s easy to type a little stronger:circleType = circle[{_, _}, _];constructCircle[position : {_, _}, radius_] := circle[position, radius];positionGet[circle : circleType] := Part[circle, 1];radiusGet[circle:circleType] := Part[circle, 2];positionSet[circle_][ position:{_,_}] := (circle = ReplacePart[circle, position, 1])radiusSet[circle_][radius_] := (circle = ReplacePart[circle, radius, 2]);(Attributes[#] = {HoldFirst})&/@{positionSet,radiusSet};I avoid capitalizing circle to prevent shadowing (clashing names with)context System`. Tom Burton====A third option, with advantages and disadvantages, is to use a list ofRules for your structured data type, such asstructureddata[type->circle, position->{1,2}, radius->{3}]I¹ll spare you the exercise of giving creation and reading rules.Erich>> CircleType = {{_, _}, _};> ConstructCircle[position : {_, _}, radius_] := {position, radius}> GetRadius[circle : CircleType] := Part[circle, 2]> GetPosition[circle : CircleType] := Part[circle, 1]> Attributes[SetRadius] = {HoldFirst};> SetRadius[circle_][radius_] := (circle = ReplacePart[circle, radius, 2];)>> It¹s easy to type a little stronger:>> circleType = circle[{_, _}, _];> constructCircle[position : {_, _}, radius_] := circle[position, radius];> positionGet[circle : circleType] := Part[circle, 1];> radiusGet[circle:circleType] := Part[circle, 2];> positionSet[circle_][> position:{_,_}] := (circle = ReplacePart[circle, position, 1])> radiusSet[circle_][radius_] := (circle = ReplacePart[circle, radius, 2]);> (Attributes[#] = {HoldFirst})&/@{positionSet,radiusSet};>> I avoid capitalizing circle to prevent shadowing (clashing names with)> context System`.>> Tom Burton>>====>>This is a minor, but annoying, problem. I would like to have the 3>palettes that I use come up in the same screen location each time I>there any way to specify this behavior?>>I have read through the entire help section for Front End>preferences, and couldn¹t Þnd anything. Wondered if anyone knew>how to do it, or knew that it was indeed impossible.>Tim>>PS -> Some X window managers can do this automatically, without>Mathematica even knowing about it, but I am running KDE, and it does>not seem to be able to do so for a non-KDE application such as>Mathematica. A KDE hack would be welcome, too, if anyone happened>to know how.Mathematica does, in fact, attempt to remember the palette positions. It does this by re-saving the palettes (*) when you close them or quit Mathematica (the window position information is stored in the notebook Þle backing the palette). However, it will refuse to re-save (failing silently instead) if you don¹t have permissions to write to the Þle, A quick Þx to the problem would be to simply change the permissions on the palette Þles. You can Þnd the Þle in the installation directory in SystemFiles/FrontEnd/Palettes. You could restore read-only privileges to the Þles after you¹ve adjusted them, if you like.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.(*) And to answer the next obvious question, yes a per-user system would obviously be better; I¹m sure this issue will be addressed in the future, although I cannot make any promises as to when.====>I hope Tech Support can help with this.>>When I run the Figure-8 animation, I get the not enough memory to>display a cell message and then the not enough memory to do what>you asked message. I have to close and reopen Mathematica to get a>usable display.>>I have this problem with many animations (SpinShow, etc...) -- with>or without DrawGraphics -- despite having 1024MB of RAM. I¹m using>version 4.2 and WinXP Home, and I had the same problem with version>4.1. The problem is very consistent, in that each animation either>always works or never does. If I reduce the number of frames>enough, the animation works. The Figure-8, for instance, works if I>change the step size from 2Pi/50 to 8Pi/50.>>I have had no memory problems with other applications -- including>SAS 8.2, Photoshop 7, Prime95, etc.>>Help?>>Bobby>>-----Original Message----->Figure-8 && CPU Strangeness>>In a sense this problem gives me an excuse to call attention to one>of the best uses I¹ve seen a computer put to. The Þgure-8>Animation in David Park¹s DrawGraphics package is exactly the kind>of graphical expression of the mathematics of physics which reviel>more about the situation than pencile and paper lend themselves to.>(People such as John A. Wheeler, and Hermann Weyl seem to have this>kind of mechanism build into thier brains, and therefore don¹t need>no stinkin¹ computer.)>While I was exploring this animation I noticed something rather>strange about the CPU¹s behavior. If I open Help Browser -> Add-Ons>-> DrawGraphics -> Examples -> Figure Eight Animation, the CPU>utilization is virtually 0.>>I evaluate the Þrst cell to load the package and the CPU jumps for>a second and then settles back down. I then select the remainder of>the notebook. The CPU utilization remains very low. Then I evaluate>it. The CPU utilization jumps way up, as is to be expected. The>animation frames are created, and the animation runs Þne. The CPU>utilization remains very high.>>The interesting observation comes when I stop the animation by>quitting the local kernel. If I select the cell holding the>graphic, I notice the CPU utilization jups to 98%+-. The kernel>isn¹t even running at this time.>When I say I select the cell holding the graphic, I mean to say I>select the brace to the right which has the Œfoldable¹ indicator.>Selecting the inner-most brace does not cause the CPU utilization to>increase, but selecting any of its parents does.>>Can someone explain this?>>You can Þnd the DrawGraphics package here:>http://home.earthlink.net/~djmp/Mathematica.htmlThe memory issue arises from the following problem. Mathematica uses bitmaps to store the rendered images. These bitmaps last the lifetime of the image itself. Bitmaps are very fast (which makes þipping between them in animations very fast), but they can consume a lot of memory. Nonetheless, if you crunch the numbers, you¹ll Þnd that the bitmaps cannot account for your system running out of memory.Unfortunately, Microsoft placed an undocumented limitation on the kind of bitmap we chose to use in Mathematica for Windows. This limitation causes bitmap allocations to fail at a much lower memory threshold then is available to the virtual memory of modern computers. Since the limitation was undocumented, it has taken us some time to root out exactly what¹s going on and what our options are for proceeding.This limitation, incidentally, is a global limitation (it could cause other applications to claim to run out of memory, too), and the memory used shows up nowhere in any memory monitoring tool, as it¹s allocated in a special area by the system.We will be working on improving this for future versions (we have a couple of viable options). In the mean time, the only way you can work around this is to limit the memory consumed by bitmaps. You could do this by...* Reduce the number of animations per notebook and don¹t have multiple notebooks with animations open.* Reduce the frame in the animation.* Reduce the size of the graphic in the animation.* Reduce the color depth of your display.I know it¹s pretty inconvenient for doing this kind of work, but understand that we weren¹t exactly happy about it, either, especially after the extensive amount of time we consumed tracking this down.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.====> I have a 3x3 gridbox and I would like to enclose a 2x2 block within in> parenthesis to indicate to a reader that I am operating only on that part of> the matrix (gridbox).> I can only seem to get parethesis added to individual elements. Any ideas?> MikeActually it was simple:Cell[TextData[Cell[BoxData[ RowBox[{(, GridBox[{ { RowBox[{(, GridBox[{ {0, 0}, {0, 0} }], )}], GridBox[{ {0}, {0} }]}, {GridBox[{ {0, 0} }], 0} }], )}]]]], Text]MikeReply-To: Liguo Song ====Ted,First of all, sorry for the vague subject. I will try to be make thesubject more clear next time.I have been playing with this Tensor idea for a couple weeks before Isent the question to the List. So, I did have a lot of things Þguredout except those in my initial post. For example, the TensorQ youprovided, except my implementation is a really ugly newbie¹s stuff.Another solution that I learned is to use Head, which I wrongly usedobject, as from Object Oriented Programming. I can deÞne A=Tensor[x],then I can use F[T_Tensor] to check whether it is a Tensor. This ismore closer to the behavior of Complex, I think.Tensor multiplication is a more complicated issue. I got some ideas, but haven¹t straight them out. As Mr. Christensen pointed out in hissimple task to make a fully functional tensor package.Also, thanks for the links. I will check them out.At last but not the least, big thanks for the nice Tips and Tricks. Ihave gone through most part of it, and learned a lot. In fact, I gotthe idea of TensorQ thing from your Tips and Tricks. Wonderful job.With my best wishes,Liguo> Liquo.Song@vanderbilt.edu posted a message with the vague subject > Is Mathematica capable of doing this?> In that post the author want to know if he/she can deÞne a new object,> Tensor, which will act like Complex. The he/she could implement a sort of> multiplication of tensors.> ----------------> Yes this can be done, except in Mathematica we don¹t have objects. Below> I deÞne TensorQ[expr] which returns True if expr is a tensor and otherwise> returns False.> In[1]:=> TensorQ[expr_]:=MatchQ[expr,_List?(Length[Dimensions[#]]=== Depth[#]-1&)]> You don¹t explain how tensors are multiplied, and I know very little about> tensors. Hence I won¹t implement tensor multiplication, but in the next> line I deÞne a function that is only deÞned when it¹s two arguments are> tensors. This function indicates if the two tensors have the same> dimensions.> In[2]:=> SameDimensionsQ[t1_?TensorQ, t2_?TensorQ]:=> (Dimensions[t1]===Dimensions[t2])> ------------> It certainly is possible to implement super/sub-scripts to represent indices> for a tensor. However, I won¹t try to implement it because I know very> little about tensors.> You can Þnd some stuff about tensors and Mathematica at:> http://mathworld.wolfram.com/Tensor.html > Also did you check the tensor package at:> http://home.earthlink.net/~djmp/Mathematica.html> ----------> Ted Ersek> Download my latest Mathematica Tips, Tricks from > http://www.verbeia.com/mathematica/tips/Tricks.html> or from > ====Dear Mathematica users,I¹ve uploaded newer release of Java Photo Editor program as a part ofJLinkProgramming applications.Java Photo Editor is a set of Java graphics painting application andMathematica packages.Extensions for Digitial Image Processing package has been added usingJ/Link.The outline of Java Photo Editor is documented athttp://fc.kuh.kumamoto-u.ac.jp/~jsato/JPEGuide/ JPEGuide.htmThe program is available from my website:http://fc.kuh.kumamoto-u.ac.jp/~jsato/ mathematica.htmJunzo---------------------------------------- Junzo SATODepartment Of Medical Information Technology & Administration PlanningKumamoto University HospitalUniversity Of Kumamoto1-1-1 Honjo, Kumamoto City,Kumamoto, 860-8556, JAPAN====There has been much discussion in this forum about the possibility oÞmplementing OOP in Mathematica. It is simply not true that OOP is somehowincompatible with Mathematica¹s current structure. Nor is it true thatthe pre-requisites are missing, like Andrew posted. Actualy it isunnervingly simple to implement OOP in a straightforward manner thatrespects all the fundamental concepts of Mathematica programming.Allow me to elaborate:The following code snippet implement a basic yet fully functionalLevel 1 (Delegate/Prototype System) OOP system within Mathematica:Unprotect[Dot];SetAttributes[Dot,HoldRest]; Protect[Dot];Object/: Object.method_Symbol[args___]:=Block[{$self=Object},Object[ method[args]]];Object@new[instance_Symbol]:=With[{ancestor=$ self}, instance/:instance.method_Symbol[args___]:=Block[{$self= instance},instance[method[args]]]; instance[msg___]:=ancestor[msg]; instance@super[]=ancestor; instance];This is the code needed to describe the Object class, and quitefrankly one doesn¹t need much more!Let¹s see how it works:(* create an instance of Object called obj1 *)Object.new[obj1](* now deÞne a Þeld for it called myField....notice the emptybrackets; this is essentialy a function with no arguments*)obj1@myField[] = OOP!(* create a method in Object that accesses the Þeld; notice the useof $self to refer to the object that actualy calls myMethod[] *)Object@myMethod[] := Print[$self.myField[]](* let¹s call it from obj1 *)obj1.myMethod[]---> OOP!In a Delegation OOP system like this, any object can also serve as aclass. We can call obj1.new[obj2] to create a new object that inheritsmyField[] from obj1 and myMethod[] from Object.For more information on what a Level 1 OOP system is, please consultthe OOP FAQ at http://www.cyberdyne-object-sys.com/oofaq2/This is, as I said, a Proof-of-Concept implementation and can begreatly improved. It is very useful for the kind of discussion we arehaving here though, as one can program Mathematica in anObject-Oriented manner with it. Notice that it is already far morepowerful than Maeder¹s package, as one can deÞne methods withconditions, predicates, patterns, etc. !I will be happy to discuss issues like Inheritance, Encapsulation,Dynamic Binding, etc. in future posts.Orestis Vantzos====Dear MathGroupCan anyone please suggest an efÞcient way to convert a list of squarematrices (of different dimensions) into a block diagonal matrix?? Theelements of each matrix are all real numbershere is an example with a list of two square matrices --matrix1 = a b c dmatrix2 = e f g h i j k l moutput = a b 0 0 0 c d 0 0 0 0 0 e f g 0 0 h i j 0 0 k l m=-=many thanksdave+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++David E. Burmaster, Ph.D.Alceon CorporationPOBox 382069 (new Box number effective 1 Sep 2001)Harvard Square StationCambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)Voice 617-864-4300Web http://www.Alceon.com++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++====David, DiagonalMatrixSq[sms_]:= Module[{p=0}, Join@@(PadRight[#,{Length[#],Plus@@Length/@sms}, 0,{0,(p+=Length[#])-Length[#]}]&/@sms) ]Test: sms= {{{a,b},{c,d}},{{e,f,g},{h,i,j},{k,l,m}},{{z}}}; DiagonalMatrixSq[sms] {{a,b,0,0,0,0}, {c,d,0,0,0,0}, {0,0,e,f,g,0}, {0,0,h,i,j, 0}, {0,0,k,l,m,0}, {0,0,0,0,0,z}}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198> Dear MathGroup>> Can anyone please suggest an efÞcient way to convert a list of square> matrices (of different dimensions) into a block diagonal matrix?? The> elements of each matrix are all real numbers>> here is an example with a list of two square matrices -->> matrix1 = a b> c d>> matrix2 = e f g> h i j> k l m> output = a b 0 0 0> c d 0 0 0> 0 0 e f g> 0 0 h i j> 0 0 k l m>> =-=>> many thanks> dave>> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> David E. Burmaster, Ph.D.> Alceon Corporation> POBox 382069 (new Box number effective 1 Sep 2001)> Harvard Square Station> Cambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)>> Voice 617-864-4300>> Web http://www.Alceon.com> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++>====I tidy up my previous posting and make it applicable to rectangular blocks:BlockDiagonalMatrix[mats_] := Module[{pl, dms, tln}, pl = 0; tln = Plus @@ (Last[Dimensions[#]] & /@ mats); Join @@ (PadRight[#, {First[dms = Dimensions[#]], tln}, 0, {0, First[{pl, pl += dms[[2]]}]}] & /@ mats) ]Test,BlockDiagonalMatrix[{{{1, 1}, {1, 1}}, {{2, 2}}, {{3}, {3}}}] // TableForm--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198> David,>> DiagonalMatrixSq[sms_]:=> Module[{p=0},> Join@@(PadRight[#,{Length[#],Plus@@Length/@sms},> 0,{0,(p+=Length[#])-Length[#]}]&/@sms)> ]>> Test:>> sms= {{{a,b},{c,d}},{{e,f,g},{h,i,j},{k,l,m}},{{z}}};>> DiagonalMatrixSq[sms]>> {{a,b,0,0,0,0},> {c,d,0,0,0,0},> {0,0,e,f,g,0},> {0,0,h,i,j, 0},> {0,0,k,l,m,0},> {0,0,0,0,0,z}}>> --> Allan>> ---------------------> Allan Hayes> Mathematica Training and Consulting> Leicester UK> www.haystack.demon.co.uk> hay@haystack.demon.co.uk> Voice: +44 (0)116 271 4198> Dear MathGroup>> Can anyone please suggest an efÞcient way to convert a list of square> matrices (of different dimensions) into a block diagonal matrix?? The> elements of each matrix are all real numbers>> here is an example with a list of two square matrices -->> matrix1 = a b> c d>> matrix2 = e f g> h i j> k l m>>> output = a b 0 0 0> c d 0 0 0> 0 0 e f g> 0 0 h i j> 0 0 k l m>>>> =-=>> many thanks> dave>>>> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> David E. Burmaster, Ph.D.> Alceon Corporation> POBox 382069 (new Box number effective 1 Sep 2001)> Harvard Square Station> Cambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)>> Voice 617-864-4300>> Web http://www.Alceon.com> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++>>>>Reply-To: kuska@informatik.uni-leipzig.de====BlockDiagonal[m_?MatrixQ] := mBlockDiagonal[m1_?MatrixQ, m2_?MatrixQ, morems___] := Module[{n1, n2}, n1 = Length[First[m1]]; n2 = Length[First[m2]]; BlockDiagonal[Join[ PadRight[#, n1 + n2, 0] & /@ m1, PadLeft[#, n1 + n2, 0] & /@ m2], morems] ]andBlockDiagonal[ {{a, b}, {d, e}}, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{q, r}, {u, v}}]will work as expected. Jens> Dear MathGroup> Can anyone please suggest an efÞcient way to convert a list of square> matrices (of different dimensions) into a block diagonal matrix?? The> elements of each matrix are all real numbers> here is an example with a list of two square matrices --> matrix1 = a b> c d> matrix2 = e f g> h i j> k l m> output = a b 0 0 0> c d 0 0 0> 0 0 e f g> 0 0 h i j> 0 0 k l m> =-=> many thanks> dave> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> David E. Burmaster, Ph.D.> Alceon Corporation> POBox 382069 (new Box number effective 1 Sep 2001)> Harvard Square Station> Cambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)> Voice 617-864-4300> Web http://www.Alceon.com> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++====All,since I started using Mathematica 4.2 on Windows XP I can no longerprint anything out of Mathematica 4.x on the HP Laserjet 3100.The result is a fatal crash of Windows XP resulting in a blue screen and reboot of windows. It is very! reproducable. Open any notebook, select print, click OK and boom....Has anbody observed this?OliverPS.: Yes I installed the latest printer driver and every other programworks just Þne with XP and the HP LaserJet 3100.Reply-To: ====Unless I¹m mistaken, a derangement can¹t leave any card in its originalposition. If so, that code doesn¹t always do it.derangement = Compile[{{ n, _Integer}}, Module[{deck = Range[n], newj}, Do[newj = Random[Integer, {j + If[ deck[[j]] == j, 1, 0], n}]; deck[[{j, newj}]] = deck[[{newj, j}]], {j, n - 1}]; deck]];check[deck_] := Count[Transpose[{deck, Range@Length@deck}], {a_, a_}] ==0And @@ Table[check@derangement[15], {100}]False (* usually *)Here¹s code that does:derangement = Compile[{{n, _Integer}}, Module[{deck = Range[n], newj}, Do[ While[deck[[newj = Random[Integer, {1, n}]]] == j || newj == deck[[j]]]; deck[[{j, newj}]] = deck[[{newj, j}]], {j, n} ]; deck]];And @@ Table[check@derangement[15], {1000}]TrueDrBob-----Original Message-----> I am searching for an algorithm for producing a random derangementof, for> instance, the integers 1 to approx 10000.>> I thought Skiena¹s site might have such an algorithm, but I couldnot locate> one. ... Producing all derangements and choosing one at random ismarginally> beyond the capacity of my machine :-)>>> Mark R. Diamond> One thing that will work efÞciently is a modiÞcation of a basicrandom> shufþe. The basic shufþe can be found at> http://forums.wolfram.com/mathgroup/archive/2001/Apr/msg00263 .html> The modiÞcation is that at step j we insist on moving somethingbetween> position j+1 (rather than j) and the end into position j.> derangement = Compile[{{n,_Integer}}, Module[> {deck=Range[n], newj},> Do[> newj = Random[Integer, {j+1,n}];> deck[[{j,newj}]] = deck[[{newj,j}]],> {j,n-1}];> deck> ]]> In[4]:= Timing[dd = derangement[10^6];]> Out[4]= {5.25 Second, Null}> Check that this is indeed a derangement:> In[5]:= Select[Transpose[{dd,Range[10^6]}], #[[1]]==#[[2]]&]> Out[5]= {}> (Or you can use MapIndexed for this test):> In[12]:= Apply[Or, MapIndexed[#1==#2[[1]]&, dd]]> Out[12]= False> I think this will give random derangements with equal probabilities> though I don¹t have a proof of that off the top of my head.> Daniel Lichtblau> Wolfram ResearchOops...my code was itself a bit deranged insofar as it will not hit allpossible derangements. I think the version below will do better.derangement = Compile[{{n,_Integer}}, Module[ {deck=Range[n], newj}, Do[ newj = Random[Integer, {j+If[deck[[j]]==j,1,0],n}]; deck[[{j,newj}]] = deck[[{newj,j}]], {j,n-1}]; deck ]]Daniel LichtblauWolfram Research====My point is, that Mathematica is not based on functional programming.Mathematica is essentially a set of instructions, which can be structuredinto programs in several ways.One method of structuring instructions into programs is the OO-Method. Thismethod connot be used in Mathematica - for the time being - becausepre-requsites are missing.Of course, everyone is free to structure the programs in the way itconsiders best. Besides, the tasks an application has to solve may make onemethod more suitable than others.Hermann Schmitt.----- Original Message -----> that not everybody using Mathematica needs the kind of data and> program structuring that object oriented programming provides, in fact> I am pretty sure the majority of Mathematica users do not (the> majority of users do not even need the existing package mechanism).> It does not mean of course you should not develop your OOP package; in> fact I am quite keen to try it when it becomes available.>> Andrzej Kozlowski>>> There is a tendency to see a contrast between OO and Mathematica. In my> opinion this makes no sense:> OO descibes a method for structuring programs and the data related to> the> programs. Mathemtica describes the instructions with which programs> may be> built.> Hermann Schmitt>>>>>>====you must differentiate between instructions and the structuring of programs.If you write a small program the structure of the program is no issue. But Ithink, that Mathematica is one of the best programming languages, you canalso program larger programs/applications with Mathematica. Then thestructuring of the program/the applications is an issue. You ignore theproblems of structuring.Additionally, your usage of the notion functional programming is wrong. Ifyou read in the literature, you will see, that functional programming isprogramming only with functions and expressions and without variables andwithout the assignement of values to variables. I think, you can program inthis way in Mathematica, but I do not think, that you mean this.Hermann----- Original Message -----> into programs in several ways.>> yes and call the instructions functions and you have a functional> language.> But you man have problems to structure a program with out If[] and> Block[]> functions.>> Jens>Reply-To: jmt@dxdydz.net====The Optica package :http://www.wolfram.com/products/applications/optica/andshows interesting approaches in this matter.> you are right, I have never written a Mathematica program> and I don¹t know what is can be. Since there is no program> it can¹t have any structure. You can have functions but I have> never written a function with more than ca 30 statements.> There is no reason to structure a Mathematica function that> has typical 5--10 statements.> It seems that larger packages work perfectly right> without any object oriented extension -- how can this> happen ?> And yes I mean functional programming when I say> functional programming. Every > real functional/logic programming language> has an assigment. The assigment is not needed> but it save some computation time. Mathematica> has also functions like While[] only for > efÞciency. > Jens> you must differentiate between instructions and the structuring of programs.> If you write a small program the structure of the program is no issue. But I> think, that Mathematica is one of the best programming languages, you can> also program larger programs/applications with Mathematica. Then the> structuring of the program/the applications is an issue. You ignore the> problems of structuring.> Additionally, your usage of the notion functional programming is wrong. If> you read in the literature, you will see, that functional programming is> programming only with functions and expressions and without variables and> without the assignement of values to variables. I think, you can program in> this way in Mathematica, but I do not think, that you mean this.> Hermann> Reply-To: kuska@informatik.uni-leipzig.de====you are right, I have never written a Mathematica programand I don¹t know what is can be. Since there is no programit can¹t have any structure. You can have functions but I havenever written a function with more than ca 30 statements.There is no reason to structure a Mathematica function thathas typical 5--10 statements.It seems that larger packages work perfectly rightwithout any object oriented extension -- how can thishappen ?And yes I mean functional programming when I sayfunctional programming. Every real functional/logic programming languagehas an assigment. The assigment is not neededbut it save some computation time. Mathematicahas also functions like While[] only for efÞciency. Jens> you must differentiate between instructions and the structuring of programs.> If you write a small program the structure of the program is no issue. But I> think, that Mathematica is one of the best programming languages, you can> also program larger programs/applications with Mathematica. Then the> structuring of the program/the applications is an issue. You ignore the> problems of structuring.> Additionally, your usage of the notion functional programming is wrong. If> you read in the literature, you will see, that functional programming is> programming only with functions and expressions and without variables and> without the assignement of values to variables. I think, you can program in> this way in Mathematica, but I do not think, that you mean this.> HermannReply-To: kuska@informatik.uni-leipzig.de====> My point is, that Mathematica is not based on functional programming.> Mathematica is essentially a set of instructions, which can be structured> into programs in several ways.yes and call the instructions functions and you have a functionallanguage.But you man have problems to structure a program with out If[] andBlock[]functions. Jens====I often heard, that Maeder¹s OO Package is not good, I do not knowthe package myself. I intend to introduce an own OO Package, soon,probably in November. My OO Package is very general. It even has essentialfeatures, which are missing in Java.I e.g support multiple inheritance. I think, the interfaces of Java are onlya weak substitute of multiple inheritance.Additionally, I think, languages with typed data Þels are at adisadvantage. It should be possible, to call methods with the same name inobjects of different classes without needing to know of which class anobject is. This is only possbile, if objects of different classes can bestored in the same data Þeld.Based on the fact, that Mathematica is an interpreted language, classes canbe build temporarily in the program.In a later step I shall make it possible to store objects on disk (calledserialization in OO). I think, it could be advantageous in some cases tohave both programs and data available throuth the same Þle.I see no essential difference between an OO system built into Mathematicaand an OO system in a separate package. Both are based on the sameMathematica system.I shall inform the mathgroup, when the package is available. I shall make itavailable on my web site:www.schmitther.deHermann SchmittReply-To: kuska@informatik.uni-leipzig.de====FourierTransform[ DiracDelta[f - (-1 + 10^(n T/c)/b)], f, t]givesE^(I*(-1 + 10^((n*T)/c)/b)*t)/Sqrt[2*Pi]in Mathematica 4.2 Jens> Any suggestions for the evaluation of the following ?> FourierTransform[> KroneckerDelta[f-(-1 + 10^(n T/c)/b)], f, t]> or even this :> FourierTransform[> DiracDelta[f-(-1 + 10^(n T/c)/b)], f, t]> Mathematica simply spits back the same input.> thanks> Matt> --> http://mffm.darktech.org> WSOLA TimeScale Audio Mod : http://mffmtimescale.sourceforge.net/> FFTw C++ : http://mffmfftwrapper.sourceforge.net/> Vector Bass : http://mffmvectorbass.sourceforge.net/> Multimedia Time Code : http://mffmtimecode.sourceforge.net/====MF> Mathematica simply spits back the same input.That¹s not quite right, in fact, not all is so dark and dim ;-)The following versions 4.2 for Microsoft Windows (June 5, 2002) 4.1 for Microsoft Windows (November 2, 2000) 4.0 for Microsoft Windows (April 21, 1999)return the correct output. In[1] := FourierTransform[DiracDelta[f - (-1 + 10^(n T/c)/b)], f, t] Out[1] = E^(I*(-1 + 10^((n*T)/c)/b)*t)/Sqrt[2*Pi] In[2] := InverseFourierTransform[%, t, f] Out[2] = DiracDelta[-1 + 10^((n*T)/c)/b - f]which is OK as DiracDelta[-z] == DiracDelta[z] .4.2 for Microsoft Windows (February 28, 2002) returns the sine/cosine variant (Cos[t - (10^((n*T)/c)*t)/b] - I*Sin[t - (10^((n*T)/c)*t)/b])/Sqrt[2*Pi]The Microsoft Windows 3.0 (April 25, 1997) version requires an add-onto be loaded Þrst, and it uses a different normalization. In[1] := <-----Original Message----->Sent: Monday, November 04, 2002 8:44 AM>To: mathgroup@smc.vnet.net>>> I have a 3x3 gridbox and I would like to enclose a 2x2 block >within in>> parenthesis to indicate to a reader that I am operating only >on that part of>> the matrix (gridbox).>>> I can only seem to get parethesis added to individual >elements. Any ideas?>>>> Mike>>Actually it was simple:>Cell[TextData[Cell[BoxData[> RowBox[{(, GridBox[{> {> RowBox[{(, GridBox[{> {0, 0},> {0, 0}> }], )}], GridBox[{> {0},> {0}> }]},> {GridBox[{> {0, 0}> }], 0}> }], )}]]]], Text]>>Mike>>As you found out by yourself, it rests to note, that there are perhaps moreattractive ways to highlight a block of a matrix:In[85]:= m = Partition[Range[9], 3]Out[85]= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}In[86]:=s[p_, {{l1_, l2_}, {u1_, u2_}}] := And @@ Thread[{l2, l1} <= p <= {u2, u1}]In[88]:=DisplayForm[ GridBox[MapIndexed[ StyleBox[ToString[#1], Unevaluated[Sequence[]]]] &, m, {2}]]]...or if you likeIn[90]:=MatrixForm[ MapIndexed[ DisplayForm[ StyleBox[ToString[#1], FontColor -> GrayLevel[.5]], FontWeight -> Bold]] &, m, {2}]]--Hartmut Wolf====>Can anyone please suggest an efÞcient way to convert a list of square>matrices (of different dimensions) into a block diagonal matrix?? The>elements of each matrix are all real numbers>>here is an example with a list of two square matrices -->>matrix1 = a b> c d>>matrix2 = e f g> h i j> k l m>output = a b 0 0 0> c d 0 0 0> 0 0 e f g> 0 0 h i j> 0 0 k l m>matrix1 = {{a, b}, {c, d}};matrix2 = {{e, f, g}, {h, i, j}, {k, l, m}};matrix3 = {{n, o}, {p, q}};Fold[ Module[{len = Length[#1] + Length[#2]}, Join[ PadRight[#, len] & /@ #1, PadLeft[#, len] & /@ #2]] &, {}, {matrix1, matrix2, matrix3}]{{a, b, 0, 0, 0, 0, 0}, {c, d, 0, 0, 0, 0, 0}, {0, 0, e, f, g, 0, 0}, {0, 0, h, i, j, 0, 0}, {0, 0, k, l, m, 0, 0}, {0, 0, 0, 0, 0, n, o}, {0, 0, 0, 0, 0, p, q}}Bob Hanlon====Dave,One way of doing this task is by using padding.Let us start with a list of square matrices:In[1]:=matrices = Table[Array[#1+#2&, {i,i}], {i, 2, 4}]Out[1]={{{2,3},{3,4}},{{2,3,4},{3,4,5},{4,5,6}},{{2,3,4,5}, {3,4,5,6},{4,5,6,7},{5,6,7,8}}}So we know the size of the result we are looking for:In[2]:=size = Plus @@ Dimensions /@ matricesOut[2]={9,9}We construct a list of the matrices together with their position in theresult:In[3]:=aux = Transpose[{matrices, Drop[ FoldList[Plus, {0,0}, Dimensions /@ matrices], -1]}]Out[3]={{{{2,3},{3,4}},{0,0}},{{{2,3,4},{3,4,5},{4,5,6}} ,{2, 2}},{{{2,3,4,5},{3,4,5,6},{4,5,6,7},{5,6,7,8}},{5,5}}}Then the result can be found by padding in the following way:In[4]:=Fold[ PadRight[ #2[[1]], size, RotateLeft[ #1, #2[[2]]], #2[[2]]]&, Array[0&, size], aux]Out[4]={{2,3,0,0,0,0,0,0,0},{3,4,0,0,0,0,0,0,0},{ 0,0,2,3,4,0,0,0,0},{0,0,3,4,5,0,0,0,0},{0,0,4,5,6,0,0,0,0},{ 0,0,0,0,0,2,3,4,5},{0,0,0,0,0,3,4,5,6},{0,0,0,0,0,4,5,6,7},{ 0,0,0,0,0,5,6,7,8}}Fred SimonsEindhoven University of Technology> -----Original Message-----> Sent: maandag 4 november 2002 8:45> To: mathgroup@smc.vnet.net> Dear MathGroup> Can anyone please suggest an efÞcient way to convert a list of square> matrices (of different dimensions) into a block diagonal matrix?? The> elements of each matrix are all real numbers> here is an example with a list of two square matrices --> matrix1 = a b> c d> matrix2 = e f g> h i j> k l m> output = a b 0 0 0> c d 0 0 0> 0 0 e f g> 0 0 h i j> 0 0 k l m> =-=> many thanks> dave> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> David E. Burmaster, Ph.D.> Alceon Corporation> POBox 382069 (new Box number effective 1 Sep 2001)> Harvard Square Station> Cambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)> Voice 617-864-4300> Web http://www.Alceon.com> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> ====Various have people have sent interesting examples of OO programming in Mathematica, as a proof that it can be done. However, let me clarify one possible confusion: I for one have never doubted that it can be done. (In fact I have occasionally tried it myself). The more doubtful issue is is it worth doing?, or is it really the best way to program in Mathematica?. I can imagine that OOP may be useful for dealing with large structures and there may be (as I have been told) some performance advantages in introducing some OOP into Mathemaitca. But none the examples I have seen here seems to me to gain much from pseudo-OOP, which is in fact also the trouble with Maeder¹s package. I have seen a couple fairly large project written using it (one is the Object-Oriented Graph Theory in Chapter III of Grey¹s Mastering Mathematica), but all of them can be programmed with no more effort using the natural Mathematica functional-pattern based style.Andrzej Kozlowski====I think, when Mathematica was created, OO was not yet existent inprogramming languages. I am astonished about the OO-like features, which arebuilt into Mathematica despite of this. Into older languages OO must bebuilt after they were created, and this is also done.In my opinion it is not the main criterion, that a program runs fast in thatprogramming language. If this was the case you should program in assemblerlanguage. The fact, that Mathematica is an interpreted language shows, thatother considerations were prominent, when the language was designed.Compiled languages are faster.The main criterion is in my opion is, that the program can be created easilyand yet more important, that it can be easily understood and modiÞedafterwards.I think, Mathematica is well suited, to integrate an OO-System.Hermann Schmitt.----- Original Message -----> abilities and those added by users, and it shows itself in performance.> In fact being aware of this difference is the most important factor in> efÞcient Mathematica programming. This distinguishes Mathematica from> most other languages.> I don¹t really want to enter into any arguments which after all are> only a matter of opinion, but I would propose the following> objective test of good OO package in Mathematica. The test is that> a proÞcient user cannot write easily a more efÞcient and equivalent> code without the package. So far I have not seen any OOP in> Mathematica that does anything in a way that I cannot do equally or> (usually) more efÞciently myself without it. Unless an OOP package can> satisfy this requirement it will be used only by users who learned> their programming on other languages and have not adapted their style> to Mathematica.> By the way, I have a good reason to believe that Wolfram will introduce> some OOP into Mathematica, that will actually enhance rather than> reduce performance. I will then think of it as real OOP rather than> pseudo-OOP.> Andrzej Kozlowski>>> what do you mean with pseudo-OOP?> Hermann Schmitt> ----- Original Message -----> To: > Sent: Tuesday, November 05, 2002 11:00 AM>>>> Various have people have sent interesting examples of OO programming>> in>> Mathematica, as a proof that it can be done. However, let me clarify>> one possible confusion: I for one have never doubted that it can be>> done. (In fact I have occasionally tried it myself). The more>> doubtful>> issue is is it worth doing?, or is it really the best way to>> program>> in Mathematica?. I can imagine that OOP may be useful for dealing>> with large structures and there may be (as I have been told) some>> performance advantages in introducing some OOP into Mathemaitca. But>> none the examples I have seen here seems to me to gain much from>> pseudo-OOP, which is in fact also the trouble with Maeder¹s package. I>> have seen a couple fairly large project written using it (one is the>> Object-Oriented Graph Theory in Chapter III of Grey¹s Mastering>> Mathematica), but all of them can be programmed with no more effort>> using the natural Mathematica functional-pattern based style.>> Andrzej Kozlowski>>>> Andrzej Kozlowski> Yokohama, Japan> http://www.mimuw.edu.pl/~akoz/> http://platon.c.u-tokyo.ac.jp/andrzej/>Reply-To: kuska@informatik.uni-leipzig.de====> In my opinion it is not the main criterion, that a program runs fast in that> programming language. you say that speed doesn¹t matter ?The extensive usage of Compile[] and the PackedArray[]s inside Mathematica say just the opposite. The point is, that in one of your larger programs/applications you accumulatethe creepiness of your OO-functions.A slow execution destroy also your easy creationof the program. Because you have to testyour code during the development and if it takes to long to make a test run your easy creation take so long thatyou can¹t call it easy anymore.BTW it it much more compilcate tounderstand a class hierachie of an OOprogram than to overload the function deÞnitions. Jens> I think, when Mathematica was created, OO was not yet existent in> programming languages. I am astonished about the OO-like features, which are> built into Mathematica despite of this. Into older languages OO must be> built after they were created, and this is also done.> In my opinion it is not the main criterion, that a program runs fast in that> programming language. If this was the case you should program in assembler> language. The fact, that Mathematica is an interpreted language shows, that> other considerations were prominent, when the language was designed.> Compiled languages are faster.> The main criterion is in my opion is, that the program can be created easily> and yet more important, that it can be easily understood and modiÞed> afterwards.> I think, Mathematica is well suited, to integrate an OO-System.> Hermann Schmitt.====I agree in general with Adrzej¹s position.It is true that traditional uses of Mathematica, namely mathematicalcomputations of one kind or another, have little to gain frompseudo-OOP that is evidently alien to the functional/rule-based style.Nevertheless:a) People have started to apply Mathematica to a wider range ofproblems (XML for instance) and even when they attack common problems,they use it in novel ways (front-end programming is much in demand,yet the elegance of Mathematica¹s programming language turns into anightmare in this case). OOP is the well established methodology inmost of these cases.b) Maeder¹s package should never have been used as extensively as itdid, although this is a strong indication that people do use OOP inconjunction with Mathematica. In the ŒOOP in Mathematica- A concrete example¹thread I provide a deceptively simple mechanism by which OOP can beimplemented within the strict conÞnes of Mathematica¹s functional/ruleparadigm. The concept behind it appears very natural to me; it¹s allabout letting a symbol use another symbol¹s DownValues.Anyway, Adrzej does not challenge the technicalities of it. He asks,why OOP? Why not stick to functional/rule programming?I can tell you what got me begging for OOP in the Þrst place...I was working on a really large set of non-linear ODEs that had thereally bad habbit of blowing up. I had to manually set the StopingTestoption of NDSolve so that each time a variable blew, NDSolve wouldstop, return the time that had elapsed, the variable that did it andofcourse the InterpolatingFunction up to that point. Then, I wouldautomaticaly recalculate a new ODE system minus the blown variable andcall a new NDSolve to carry on, etc. Finally, all thoseInterpolatingFunction objects had to be glued together and returned ina useful format along with all sorts of performance and debugginginformation. On top of all that, all the aforementioned informationhad to be stored in a Þle.I started wroting all the appropriate functions and ...got stuck!I knew how to write the relevant functions, but it just didn¹t workout really well. You see everything had to be passed from function tofunction in a literal form. But the data structures that resulted werethe huge lists and did the job but they were both too complicated andtoo slow. The functions got really involved, with scores of argumentsand local variables. You see, each functions had to splice theexpression that was given, do its deed, and then pack it all up andpass it to the next function. It was hell...Then I decided that I would store all the intermediate informationI could get the information when and where I needed it. It didn¹tchange the core of what I was doing- no programming revelation per se.Most of the functions I had written remained the same actually. It wasjust that everything got much much tidier. The juicy part was stillfunctional; encapsulation had simply made it more clear. The rest ishistory; once you accept that Mathematica programming works even whenit operates on implicit information hidden in symbols rather onexplicit one assorted in lists, OOP is only a few functions away.Orestis Vantzos====I believe it would be better to move the Module out:Module[{len}, Fold[ (len = Length[#1] + Length[#2]; Join[ PadRight[#, len] & /@ #1, PadLeft[#, len] & /@ #2]) &, {}, {matrix1, matrix2, matrix3}]]Bob Hanlon>>Can anyone please suggest an efÞcient way to convert a list of square>>matrices (of different dimensions) into a block diagonal matrix?? The>>elements of each matrix are all real numbers>>here is an example with a list of two square matrices -->>matrix1 = a b>> c d>>matrix2 = e f g>> h i j>> k l m>>output = a b 0 0 0>> c d 0 0 0>> 0 0 e f g>> 0 0 h i j>> 0 0 k l m>>matrix1 = {{a, b}, {c, d}};>matrix2 = {{e, f, g}, {h, i, j}, {k, l, m}};>matrix3 = {{n, o}, {p, q}};>>Fold[> Module[{len = Length[#1] + Length[#2]},> Join[> PadRight[#, len] & /@ #1,> PadLeft[#, len] & /@ #2]] &, {},> {matrix1, matrix2, matrix3}]>>{{a, b, 0, 0, 0, 0, 0}, {c, d, 0, 0, 0, 0, 0}, > {0, 0, e, f, g, 0, 0}, {0, 0, h, i, j, 0, 0}, > {0, 0, k, l, m, 0, 0}, {0, 0, 0, 0, 0, n, o}, > {0, 0, 0, 0, 0, p, q}}>Bob Hanlon>Bob Hanlon====Dear Colleagues,I fail to locate the commands Rows[mat], Columns[mat] which give thenumber of rows and columns of a matrix;I believe they exist - and I do know Dimensions[].Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de====the following produces your block diagonal matrix:Needs[LinearAlgebra`MatrixManipulation`]Clear[a, b, c, d, e, f, g, h, i, j, k, l, m]m1 = {{a, b}, {c, d}} // MatrixForm;m2 = {{e, f, g}, {h, i, j}, {k, l, m}} // MatrixForm;z1 = ZeroMatrix[2, 3] // MatrixForm;z2 = ZeroMatrix[3, 2] // MatrixForm;MatrixForm[AppendColumns[AppendRows[MatrixForm[{{a , b}, {c, d}}],MatrixForm[{{0, 0, 0}, {0, 0, 0}}]], AppendRows[MatrixForm[{{0, 0}, {0, 0}, {0, 0}}], MatrixForm[{{e, f, g},{h, i, j}, {k, l, m}}]]]]Out1:MatrixForm[{{a, b, 0, 0, 0}, {c, d, 0, 0, 0}, {0, 0, e, f, g}, {0, 0, h, i,j}, {0, 0, k, l, m}}]BTW: Trying to use BlockMatrix[] directly failed; I got the last commandabove (the Appends) as output, which upon evaluation - after making it an*identical* input - yielded the Out1 shown above.Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de-----UrsprÌ.b9ngliche Nachricht-----Gesendet: Montag, 4. November 2002 08:45An: mathgroup@smc.vnet.netBetreff: making a block diagonal matrixDear MathGroupCan anyone please suggest an efÞcient way to convert a list of squarematrices (of different dimensions) into a block diagonal matrix?? Theelements of each matrix are all real numbershere is an example with a list of two square matrices --matrix1 = a b c dmatrix2 = e f g h i j k l moutput = a b 0 0 0 c d 0 0 0 0 0 e f g 0 0 h i j 0 0 k l m=-=many thanksdave+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++David E. Burmaster, Ph.D.Alceon CorporationPOBox 382069 (new Box number effective 1 Sep 2001)Harvard Square StationCambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)Voice 617-864-4300Web http://www.Alceon.com++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++Reply-To: m.marques-pita@ed.ac.uk==== i have a question regarding matrices. searched on the web and forumsbut maybe due to using wrong keywords i am not Þnding an answer... i need a way or function X to initialise matrices in mathematica suchthat each time i call X i get a matrix with a predetermined number ofelements initialised as 1 and the rest as 0examplesX(4,3){{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}}again X(4,3){{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}}etc.. (Þrst argument means that the matrix is 4x4 and second meansthat there should be 3 1¹s present in the matrixany help, pointers, etc will be appreciated!thanks a lotm--====> i have a question regarding matrices. searched on the web and forums> but maybe due to using wrong keywords i am not Þnding an answer... > i need a way or function X to initialise matrices in mathematica such> that each time i call X i get a matrix with a predetermined number of> elements initialised as 1 and the rest as 0> examples> X(4,3)> {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}}> again X(4,3)> {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}}> etc.. (Þrst argument means that the matrix is 4x4 and second means> that there should be 3 1¹s present in the matrix> any help, pointers, etc will be appreciated!> thanks a lot> m> --You can use this, where dim is the dimension of the matrix and n thenumber of ones that you want:randMatrix[dim_, n_] := Module[{A, ones = 0, i, j}, A[__] = 0; While[ones < n, {i, j} = Table[Random[Integer, {1, dim}], {2}]; If[A[i, j] == 0, A[i, j] = 1; ones++]]; Array[A, {dim, dim}]]Orestis Vantzos====ManuelThis is my Þrst go, for an m x m matrix, with n 1si) load Combinatorica, we¹ll need it in a step or two:<< DiscreteMath`Combinatorica`ii) create a list with n 1s followed by (m * m)- n 0s: list = Join[Table[1, {n}], Table[0, {m m - n}]iii) Create a random permutation of this list, using the Combinatoricafunction RandomPermutation:randomList = RandomPermutation[list]iv) now partition the list into m rows each of m elements:randomMatrix = Partition[randomList, m]v) putting it all together:x[m_, n_] := Partition[RandomPermutation[Join[Table[1, {n}], Table[0, {m m - n}]]],m]I think this answers your question.Mark Westwood > i have a question regarding matrices. searched on the web and forums> but maybe due to using wrong keywords i am not Þnding an answer...> i need a way or function X to initialise matrices in mathematica such> that each time i call X i get a matrix with a predetermined number of> elements initialised as 1 and the rest as 0> examples> X(4,3)> {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}}> again X(4,3)> {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}}> etc.. (Þrst argument means that the matrix is 4x4 and second means> that there should be 3 1¹s present in the matrix> any help, pointers, etc will be appreciated!> thanks a lot> m> --Reply-To: kuska@informatik.uni-leipzig.de====X[dim_, count1_] := Module[{m, i = 0, pos}, m = Table[0, {dim}, {dim}]; While[i < count1, pos = {Random[Integer, {1, dim}], Random[Integer, {1, dim}]}; If[m[[Sequence @@ pos]] =!= 1, m[[Sequence @@ pos]] = 1; i++] ]; m ] Jens> i have a question regarding matrices. searched on the web and forums> but maybe due to using wrong keywords i am not Þnding an answer...> i need a way or function X to initialise matrices in mathematica such> that each time i call X i get a matrix with a predetermined number of> elements initialised as 1 and the rest as 0> examples> X(4,3)> {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}}> again X(4,3)> {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}}> etc.. (Þrst argument means that the matrix is 4x4 and second means> that there should be 3 1¹s present in the matrix> any help, pointers, etc will be appreciated!> thanks a lot> m> --====Oops didn¹t see that my computer replaced the Œnot equal¹ sign with a question mark after copying.Here it is again with corrections.< r) -> 0; lst = lst /. (x_ /; x != 0) -> 1; Partition[lst, n]];Then X[4,3] generates the desired matrix.Hope this helps.Lawrence > i have a question regarding matrices. searched on the web and forums > but maybe due to using wrong keywords i am not Þnding an answer... > i need a way or function X to initialise matrices in mathematica such > that each time i call X i get a matrix with a predetermined number of > elements initialised as 1 and the rest as 0 > examples > X(4,3) > {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}} > again X(4,3) > {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}} > etc.. (Þrst argument means that the matrix is 4x4 and second means > that there should be 3 1¹s present in the matrix > any help, pointers, etc will be appreciated! > thanks a lot > m > -- >-- Lawrence A. Walker Jr.http://www.kingshonor.com====Very interesting question.The approach is as follows.First load the Combinatorica package. This package contains the function, RandomPermutation, that generates a list with the numbers randomly shufþed.< r) -> 0; lst = lst /. (x_ /; x ? 0) -> 1; Partition[lst, n]];Then X[4,3] generates the desired matrix.Hope this helps.Lawrence> > i have a question regarding matrices. searched on the web and forums> but maybe due to using wrong keywords i am not Þnding an answer... > i need a way or function X to initialise matrices in mathematica such> that each time i call X i get a matrix with a predetermined number of> elements initialised as 1 and the rest as 0> examples> X(4,3)> {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}}> again X(4,3)> {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}}> etc.. (Þrst argument means that the matrix is 4x4 and second means> that there should be 3 1¹s present in the matrix> any help, pointers, etc will be appreciated!> thanks a lot> m> --> -- Lawrence A. Walker Jr.http://www.kingshonor.com====Very interesting question.The approach is as follows.First load the Combinatorica package. This package contains the function, RandomPermutation, that generates a list with the numbers randomly shufþed.< r) -> 0; lst = lst /. (x_ /; x ? 0) -> 1; Partition[lst, n]];Then X[4,3] generates the desired matrix.Hope this helps.Lawrence> > i have a question regarding matrices. searched on the web and forums> but maybe due to using wrong keywords i am not Þnding an answer... > i need a way or function X to initialise matrices in mathematica such> that each time i call X i get a matrix with a predetermined number of> elements initialised as 1 and the rest as 0> examples> X(4,3)> {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}}> again X(4,3)> {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}}> etc.. (Þrst argument means that the matrix is 4x4 and second means> that there should be 3 1¹s present in the matrix> any help, pointers, etc will be appreciated!> thanks a lot> m> --> -- Lawrence A. Walker Jr.http://www.kingshonor.comReply-To: ====Here¹s an example.<< LinearAlgebra`MatrixManipulation`MatrixForm[blocks = #IdentityMatrix[#] - 2 & /@ {2, 3, 1}]glue1 = BlockMatrix@{{#1, Table[0, {Length@#1}, {Length@#2}]}, {Table[0,{ Length@#2}, {Length@#1}], #2}} &;MatrixForm[glueAll = Fold[glue1, First@blocks, Rest@blocks]]DrBob-----Original Message----- h i j k l moutput = a b 0 0 0 c d 0 0 0 0 0 e f g 0 0 h i j 0 0 k l m=-=many thanksdave+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++David E. Burmaster, Ph.D.Alceon CorporationPOBox 382069 (new Box number effective 1 Sep 2001)Harvard Square StationCambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)Voice 617-864-4300Web http://www.Alceon.com++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++====Does this limitation occur in all Windows OS¹s? I don¹t seem to have theproblem with my Windows98. But I tend to have only one or two animationspresent at a time and I delete them before running others. Bobby seems tohave a problem when running just a single animation of moderate size.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/>or without DrawGraphics -- despite having 1024MB of RAM. I¹m using>version 4.2 and WinXP Home, and I had the same problem with version>4.1. The problem is very consistent, in that each animation either>always works or never does. If I reduce the number of frames>enough, the animation works. The Figure-8, for instance, works if I>change the step size from 2Pi/50 to 8Pi/50.>>I have had no memory problems with other applications -- including>SAS 8.2, Photoshop 7, Prime95, etc.>>Help?>>Bobby>>-----Original Message----->Figure-8 && CPU Strangeness>>In a sense this problem gives me an excuse to call attention to one>of the best uses I¹ve seen a computer put to. The Þgure-8>Animation in David Park¹s DrawGraphics package is exactly the kind>of graphical expression of the mathematics of physics which reviel>more about the situation than pencile and paper lend themselves to.>(People such as John A. Wheeler, and Hermann Weyl seem to have this>kind of mechanism build into thier brains, and therefore don¹t need>no stinkin¹ computer.)>While I was exploring this animation I noticed something rather>strange about the CPU¹s behavior. If I open Help Browser -> Add-Ons>-> DrawGraphics -> Examples -> Figure Eight Animation, the CPU>utilization is virtually 0.>>I evaluate the Þrst cell to load the package and the CPU jumps for>a second and then settles back down. I then select the remainder of>the notebook. The CPU utilization remains very low. Then I evaluate>it. The CPU utilization jumps way up, as is to be expected. The>animation frames are created, and the animation runs Þne. The CPU>utilization remains very high.>>The interesting observation comes when I stop the animation by>quitting the local kernel. If I select the cell holding the>graphic, I notice the CPU utilization jups to 98%+-. The kernel>isn¹t even running at this time.>When I say I select the cell holding the graphic, I mean to say I>select the brace to the right which has the Œfoldable¹ indicator.>Selecting the inner-most brace does not cause the CPU utilization to>increase, but selecting any of its parents does.>>Can someone explain this?>>You can Þnd the DrawGraphics package here:>http://home.earthlink.net/~djmp/Mathematica.htmlThe memory issue arises from the following problem. Mathematica usesbitmaps to store the rendered images. These bitmaps last the lifetime ofthe image itself. Bitmaps are very fast (which makes þipping betweenthem in animations very fast), but they can consume a lot of memory.Nonetheless, if you crunch the numbers, you¹ll Þnd that the bitmapscannot account for your system running out of memory.Unfortunately, Microsoft placed an undocumented limitation on the kind ofbitmap we chose to use in Mathematica for Windows. This limitation causesbitmap allocations to fail at a much lower memory threshold then isavailable to the virtual memory of modern computers. Since the limitationwas undocumented, it has taken us some time to root out exactly what¹sgoing on and what our options are for proceeding.This limitation, incidentally, is a global limitation (it could causeother applications to claim to run out of memory, too), and the memoryused shows up nowhere in any memory monitoring tool, as it¹s allocated ina special area by the system.We will be working on improving this for future versions (we have a coupleof viable options). In the mean time, the only way you can work aroundthis is to limit the memory consumed by bitmaps. You could do this by...* Reduce the number of animations per notebook and don¹t have multiplenotebooks with animations open.* Reduce the frame in the animation.* Reduce the size of the graphic in the animation.* Reduce the color depth of your display.I know it¹s pretty inconvenient for doing this kind of work, butunderstand that we weren¹t exactly happy about it, either, especiallyafter the extensive amount of time we consumed tracking this down.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.====David,Needs[LinearAlgebra`MatrixManipulation`]mat1 = {{a, b}, {c, d}};mat2 = {{e, f, g}, {h, i, j}, {k, l, m}};BlockMatrix[{{mat1, ZeroMatrix[2, 3]}, {ZeroMatrix[3, 2], mat2}}] // MatrixFormMatrixManipulation doesn¹t have a routine to make a diagonal block matrixdirectly, but I think the following will work.diagonalBlockMatrix[blocks : {__?(MatrixQ[#] && Equal @@ Dimensions[#] &)}]:= Module[ {n = Length[blocks], sizes, rows, cols, i, j}, sizes = Dimensions /@ blocks; rows = Flatten@(First /@ sizes); cols = Flatten@(Last /@ sizes); Table[ Join[Table[ ZeroMatrix[Part[rows, i], Part[cols, j]], {j, 1, i - 1}], {Part[ blocks, i]}, Table[ZeroMatrix[Part[rows, i], Part[cols, j]], {j, i + 1, n}]],{i, 1, n}] // BlockMatrix ]diagonalBlockMatrix[{mat1, mat2}] // MatrixFormDavid Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ k l moutput = a b 0 0 0 c d 0 0 0 0 0 e f g 0 0 h i j 0 0 k l m=-=many thanksdave+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++David E. Burmaster, Ph.D.Alceon CorporationPOBox 382069 (new Box number effective 1 Sep 2001)Harvard Square StationCambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)Voice 617-864-4300Web http://www.Alceon.com++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++====Dear Math Group,How can I get the linear independent subset of a list of symbol, function, and derivative of functions?Here is a example: For {a, b, a+b, c, b-c}, one of the subsets is {a,b,c}. In fact, any one of the subsets would work for me. Another example. For {F[x], G[x], D[F,x],D[G,x,2], F[x]+D[F,x], D[G,x,2]+D[F,x]+F[x]}, the subset would be {F[x], G[x], D[F,x],D[G,x,2]}.I have went through the help of Mathematica and did Þnd anything like this. Help is really appreciated.LiguoReply-To: kuska@informatik.uni-leipzig.de====the functionLinearIndepend[expr_] := expr //. {a___, b_, c___, d_, e___} /; MemberQ[d, _.b + _.] :> {a, b,c, e}gives forIn[]:= LinearIndepend[{F[x], G[x], D[F[x], x], D[G[x], {x, 2}], F[x] +D[F[x], x], D[G[x], {x, 2}] + D[F[x], x] + F[x]}]Out[]={F[x], G[x], Derivative[1][F][x], Derivative[2][G][x]}andIn[]:=LinearIndepend[{a, b, a + b, c, b - c}]Out[]={a,b,c}*and* D[G,x,2] ins nonsense you mean D[G[x],{x,2}] Jens> Dear Math Group,> How can I get the linear independent subset of a list of symbol, function, and> derivative of functions?> Here is a example:> For {a, b, a+b, c, b-c}, one of the subsets is {a,b,c}. In fact, any one of> the subsets would work for me.> Another example. For {F[x], G[x], D[F,x],D[G,x,2], F[x]+D[F,x],> D[G,x,2]+D[F,x]+F[x]}, the subset would be {F[x], G[x], D[F,x],D[G,x,2]}.> I have went through the help of Mathematica and did Þnd anything like this.> Help is really appreciated.> Liguo====I need help using Mathematica. I¹m trying to solve a standard equation of height, and Þnd a corresponding initial velocityy[t]=-(g+Drag force)*(t^2)/2+v0*t+y0y0 is always equal to 0.Can you help?Chad====ChadThe most straightforward way to Œsolve¹ your equation is to translate itinto Mathematica syntax, along the lines of:y[t_] := ((g + dragForce)(t^2)/2)+(t v0)+y0For this to work correctly you¹ll need to deÞne values for theconstants g, dragForce, and v0. Of course, if y0 is really always 0 youcould simplify the equation by dropping the term.I¹m a little puzzled by your question, since you suggest that you wishto input a height and have returned a velocity - but you name theparameter Œt¹ which looks awfully like time to me.Hope this helps some, if there¹s more to the question do post again.Mark Westwood> I need help using Mathematica. I¹m trying to solve a standard equation of> height, and Þnd a corresponding initial velocity> y[t]=-(g+Drag force)*(t^2)/2+v0*t+y0> y0 is always equal to 0.> Can you help?> Chad====Letting y[t]->h.Solve[h==-(g+Drag force)*(t^2)/2+v0*t+y0, v0]Hope this helps.Lawrence> I need help using Mathematica. I¹m trying to solve a standard equation of > height, and Þnd a corresponding initial velocity> y[t]=-(g+Drag force)*(t^2)/2+v0*t+y0> y0 is always equal to 0.> Can you help?> Chad> -- Lawrence A. Walker Jr.http://www.kingshonor.com====Letting y[t]->h.Solve[h==-(g+Drag force)*(t^2)/2+v0*t+y0, v0]Hope this helps.Lawrence> I need help using Mathematica. I¹m trying to solve a standard equation of > height, and Þnd a corresponding initial velocity> y[t]=-(g+Drag force)*(t^2)/2+v0*t+y0> y0 is always equal to 0.> Can you help?> Chad> -- Lawrence A. Walker Jr.http://www.kingshonor.comReply-To: kuska@informatik.uni-leipzig.de====Solve[y[t] == -(g + DragForce)*(t^2)/2 + v0*t + y0, v0]?? and you DragForce is a acceleration ?? Jens> I need help using Mathematica. I¹m trying to solve a standard equation of> height, and Þnd a corresponding initial velocity> y[t]=-(g+Drag force)*(t^2)/2+v0*t+y0> y0 is always equal to 0.> Can you help?> Chad====Yes, it does occur in all Windows OS¹s (although my experience is that youcan squeeze a little more memory out of Windows 9x...my suspicions as towhy this is would require a pretty complicated and detailed explanationof the problem, so I won¹t elaborate here). The limitation is on thememory consumed by the bitmap format we¹re using, so whether or not yourun into the limitation would depend upon how large your graphics are,how many there are, and what color depth your screen is set to (thelower the color depth, the more bitmaps you can create).Most people tend to run out of memory when working with animations thathave somewhere around one to two hundred frames (exact number dependingupon the above variables). The system is not truly out of memory, butit is out of memory for creating more bitmaps (and thus for renderingmore graphics). It is possible to generate animations this large andnot run out of memory, though, since the images may not be rendered intobitmaps until you actually *view* the animation (as opposed to simplyhaving generated it)..Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.> Does this limitation occur in all Windows OS¹s? I don¹t seem to have the> problem with my Windows98. But I tend to have only one or two animations> present at a time and I delete them before running others. Bobby seems to> have a problem when running just a single animation of moderate size.> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/>I hope Tech Support can help with this.>>When I run the Figure-8 animation, I get the not enough memory to>display a cell message and then the not enough memory to do what>you asked message. I have to close and reopen Mathematica to get a>usable display.>>I have this problem with many animations (SpinShow, etc...) -- with>or without DrawGraphics -- despite having 1024MB of RAM. I¹m using>version 4.2 and WinXP Home, and I had the same problem with version>4.1. The problem is very consistent, in that each animation either>always works or never does. If I reduce the number of frames>enough, the animation works. The Figure-8, for instance, works if I>change the step size from 2Pi/50 to 8Pi/50.>>I have had no memory problems with other applications -- including>SAS 8.2, Photoshop 7, Prime95, etc.>>Help?>>Bobby>>-----Original Message-----> To: mathgroup@smc.vnet.net>Figure-8 && CPU Strangeness>>In a sense this problem gives me an excuse to call attention to one>of the best uses I¹ve seen a computer put to. The Þgure-8>Animation in David Park¹s DrawGraphics package is exactly the kind>of graphical expression of the mathematics of physics which reviel>more about the situation than pencile and paper lend themselves to.>(People such as John A. Wheeler, and Hermann Weyl seem to have this>kind of mechanism build into thier brains, and therefore don¹t need>no stinkin¹ computer.)>>>While I was exploring this animation I noticed something rather>strange about the CPU¹s behavior. If I open Help Browser -> Add-Ons>-> DrawGraphics -> Examples -> Figure Eight Animation, the CPU>utilization is virtually 0.>>I evaluate the Þrst cell to load the package and the CPU jumps for>a second and then settles back down. I then select the remainder of>the notebook. The CPU utilization remains very low. Then I evaluate>it. The CPU utilization jumps way up, as is to be expected. The>animation frames are created, and the animation runs Þne. The CPU>utilization remains very high.>>The interesting observation comes when I stop the animation by>quitting the local kernel. If I select the cell holding the>graphic, I notice the CPU utilization jups to 98%+-. The kernel>isn¹t even running at this time.>When I say I select the cell holding the graphic, I mean to say I>select the brace to the right which has the Œfoldable¹ indicator.>Selecting the inner-most brace does not cause the CPU utilization to>increase, but selecting any of its parents does.>>Can someone explain this?>>You can Þnd the DrawGraphics package here:>http://home.earthlink.net/~djmp/Mathematica.html> The memory issue arises from the following problem. Mathematica uses> bitmaps to store the rendered images. These bitmaps last the lifetime of> the image itself. Bitmaps are very fast (which makes þipping between> them in animations very fast), but they can consume a lot of memory.> Nonetheless, if you crunch the numbers, you¹ll Þnd that the bitmaps> cannot account for your system running out of memory.> Unfortunately, Microsoft placed an undocumented limitation on the kind of> bitmap we chose to use in Mathematica for Windows. This limitation causes> bitmap allocations to fail at a much lower memory threshold then is> available to the virtual memory of modern computers. Since the limitation> was undocumented, it has taken us some time to root out exactly what¹s> going on and what our options are for proceeding.> This limitation, incidentally, is a global limitation (it could cause> other applications to claim to run out of memory, too), and the memory> used shows up nowhere in any memory monitoring tool, as it¹s allocated in> a special area by the system.> We will be working on improving this for future versions (we have a couple> of viable options). In the mean time, the only way you can work around> this is to limit the memory consumed by bitmaps. You could do this by...> * Reduce the number of animations per notebook and don¹t have multiple> notebooks with animations open.> * Reduce the frame in the animation.> * Reduce the size of the graphic in the animation.> * Reduce the color depth of your display.> I know it¹s pretty inconvenient for doing this kind of work, but> understand that we weren¹t exactly happy about it, either, especially> after the extensive amount of time we consumed tracking this down.> Sincerely,> John Fultz> jfultz@wolfram.com> User Interface Group> Wolfram Research, Inc.> ====values. The problem arises when p=n=0. Such an expression is indeterminateobviously, but since it is part of a probability calculation, theprobability that something with 0 probability occuring 0 times is 1. Isthere a rule that I can specify that would allow me to replace thisindeterminate express with the answer that I want? I could go back andchange every instance where this pops up with a function or take the limit,but I wanted to check if there was a more efÞcient method.M====> values. The problem arises when p=n=0. Such an expression is> indeterminate obviously,I agree with that statement _only_ because this newsgroup concernsMathematica, in which 0^0 is indeed called Indeterminate. However, manymathematicians (including myself) take 0^0 to be 1. See, for example, the. Furthermore, some other computer algebra systems (in this newsgroup, I¹mnot supposed to name them, if I understand correctly) consider 0^0 to be 1.Note that of course the _limit form_ 0^0 is indeterminate. No questionabout that. But we are not concerned with a limit form here; rather, weare concerned with just the arithmetic expression 0^0.> but since it is part of a probability> calculation, the probability that something with 0 probability occuring 0> times is 1. Is there a rule that I can specify that would allow me to> replace this indeterminate express with the answer that I want?As to this good question of yours, I¹ll defer to those more experiencedwith Mathematica. I¹ll be interested in their answers.Ultimately however, I would like to see 0^0 = 1 by default in Mathematica.David Cantrell-- -------------------- http://NewsReader.Com/ -------------------- Usenet Newsgroup ServiceReply-To: kuska@informatik.uni-leipzig.de====Unprotect[Power]Power[0, 0] = 1Protect[Power] Jens> values. The problem arises when p=n=0. Such an expression is indeterminate> obviously, but since it is part of a probability calculation, the> probability that something with 0 probability occuring 0 times is 1. Is> there a rule that I can specify that would allow me to replace this> indeterminate express with the answer that I want? I could go back and> change every instance where this pops up with a function or take the limit,> but I wanted to check if there was a more efÞcient method.> M====> values. The problem arises when p=n=0. Such an expression is indeterminate> obviously, but since it is part of a probability calculation, the> probability that something with 0 probability occuring 0 times is 1. Is> there a rule that I can specify that would allow me to replace this> indeterminate express with the answer that I want? I could go back and> change every instance where this pops up with a function or take the limit,> but I wanted to check if there was a more efÞcient method.The rule is easy,r = HoldPattern[0^0] -> 1once you know about HoldPattern. Preventing premature evaluation may be moredifÞcult. Example:expr = Hold[2^1+3^4+0^0+1^3]ReleaseHold[expr /. r]Tom Burton====Dear MathGroup,Can anyone suggest efÞcient algorithms for calculating either or both ofthese? (i) the inverse and (ii) the determinant of a block diagonal matrix?Let blocki for i = 1, 2,..., n denote each of the square matrices along thediagonal of a large block diagonal matrix.In my situation, the blocki matrices do not have a common size; a typicalblocki has dimensions in the range 6x6 to 20x20.In my situation, n is approx 1,000.In other words, the full block diagonal matrix has large dimensions -- butit is sparse in a highly structured way.many thanks for your helpdave+++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++David E. Burmaster, Ph.D.Alceon CorporationPOBox 382069 (new Box number effective 1 Sep 2001)Harvard Square StationCambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)Voice 617-864-4300Web http://www.Alceon.com++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++Reply-To: kuska@informatik.uni-leipzig.de====no special blockdiagonal code butDeveloper`SparseLinearSolve[]may help you. Jens> Dear MathGroup,> Can anyone suggest efÞcient algorithms for calculating either or both of> these?> (i) the inverse and (ii) the determinant of a block diagonal matrix?> Let blocki for i = 1, 2,..., n denote each of the square matrices along the> diagonal of a large block diagonal matrix.> In my situation, the blocki matrices do not have a common size; a typical> blocki has dimensions in the range 6x6 to 20x20.> In my situation, n is approx 1,000.> In other words, the full block diagonal matrix has large dimensions -- but> it is sparse in a highly structured way.> many thanks for your help> dave> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> David E. Burmaster, Ph.D.> Alceon Corporation> POBox 382069 (new Box number effective 1 Sep 2001)> Harvard Square Station> Cambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)> Voice 617-864-4300> Web http://www.Alceon.com> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++====I suggest the following.1) The SparseLinearSolve package.2) Finding C code on the web at http://cm.bell-labs.com/netlib/master/readme.html, LINPack or LaPack and then using Mathlink to link these to Mathematica.Hope this helps.Lawrence> Dear MathGroup,> Can anyone suggest efÞcient algorithms for calculating either or both of> these?> (i) the inverse and (ii) the determinant of a block diagonal matrix?> Let blocki for i = 1, 2,..., n denote each of the square matrices along the> diagonal of a large block diagonal matrix.> In my situation, the blocki matrices do not have a common size; a typical> blocki has dimensions in the range 6x6 to 20x20.> In my situation, n is approx 1,000.> In other words, the full block diagonal matrix has large dimensions -- but> it is sparse in a highly structured way.> many thanks for your help> dave> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++> David E. Burmaster, Ph.D.> Alceon Corporation> POBox 382069 (new Box number effective 1 Sep 2001)> Harvard Square Station> Cambridge, MA 02238-2069 (new ZIP code effective 1 Sep 2001)> Voi