3423 === Subject: Consultant Needed Mathematica consultant needed for implementing global variables in a system consisting of several Mathematica packages. It is preferable the consultant be in the San Francisco Bay Area but not absolutely necessary. Please contact Donald at dfd01@comcast.net === Subject: Memory leak caused by JavaNew[...] (JLink package) I have a function like this: myFun[...]:=Module[{...}, ... outputDataPacketObject = JavaNew[mypackage.MyOutputClass, ...]; (* run some calculation and result result within 'outputDataPacketObject' java object *) result = MyCalcObject@runSimpleCalculation[... outputDataPacketObject ... ]; ]; The function should be called many times (>3000). It turnes out that something in the program eats the memory and after sometime the kernel says no enough memory. So, why it might happen? What might be wrong? Is there a way to clear the memory? -Andrey === Subject: Re: Map[] and multiple args function > I know this has to be FAQ, but I'm just not able to find an answer > anywhere, so - here it goes: I have a multiple-arguments function, > say something like: > Foo[x_, y_, z_] := x + 2*y + 3*z > Now, I want to call this function number of times, over different sets > of arguments, and then to sum results. I thought about storing > argument triplets into some kind of list, and then employing sequence > of Map[] and Apply[] to get the job done. After number of trials and > errors, I came up with following piece of code doing the thing: > Plus @@ Foo /@ {{1, 2, 3}, {4, 5, 6}} /. List -> Sequence > but I even don't fully understand what's going here, and also I'm > wondering is there a better way to accomplish this. So - any > suggestion? Writing your code out longhand would help with interpretation, longhand it's: ReplaceAll[Apply[Plus, Map[Foo, List[List[1, 2, 3], List[4, 5, 6]]]], Rule[List, Sequence]] (obtained doing FullForm[Hold[Plus @@ Foo /@ {{1, 2, 3}, {4, 5, 6}} /. List -> Sequence]]) So the first thing that happens is Foo is mapped onto {{1, 2, 3}, {4, 5, 6}} giving {Foo[{1, 2, 3}], Foo[{4, 5, 6}]} Plus is applied giving: Foo[{1, 2, 3}],+Foo[{4, 5, 6}] then the lists are replaced by sequences leading to the evaluation of: Foo[1, 2, 3],+Foo[4, 5, 6] You can avoid the replace by applying Foo directly to the appropriate level of the argument list, either using the shorthand Plus@@Foo@@@{{1,2,3},{4,5,6}} or Apply[Plus,Apply[Foo,{{1,2,3},{4,5,6}},{1}]] === Subject: Re: Log[x]//TraditionalForm > not being a very advanced person myself, and only being an engineer, I > have to admit to thinking that ln was the correct name for natural The notational distinction between ln and log makes sense for engineers who must use both natural logarithms and common logarithms. But in advanced mathematics there is only one logarithm. --Lou Talman Department of Mathematical & Computer Sciences Metropolitan State College of Denver === Subject: Re: Data interpolation hemanth, ListInterpolation will do what you want nicely. On Feb 9, 12:37 pm, hemanth korrapati I have some 3D point data acquired through a laser range finder. The > data is sparse. I need to construct a height field out of this data > and as a part of this i have to interpolate heights at some locations > {x,y} where the actual data is not available. > I want to use B-splines. But it seems that B-splines require uniformly > distributed control points, which is not the case with my data. > My data cannot form a uniform table which is required by the > BSplineSurface function if I sort my data. for some data i got the following error: > Interpolation::indim: The coordinates do not lie on a structured > tensor product grid. >> So I started using the ListDensityPlot function which does a linear > interpolation of the data. The interpolation is sufficiently good. But > I would like to get an output consisting of list of tuples like > {x,y,InterpolatedHeight} at the desired {x,y} locations. Right now I > can only see the plot but cannot get the interpolated heights at > desired locations({x,y}). Now I have three questions: > 1) how do i make my data usable for splines in mathematica ? > 2) how do i get the interpolated values at desired {x,y} using > ListDensityPlot function ? > 3) Is there a better way other than the above two methods to > interpolate the missing data ? > === Subject: Re: NMinimize Bug in Mathematica 7.0? poly = x^4 - 3 x^2 + x; Plot[poly, {x, -2, 2}, PlotRange -> {-3.6, .5}] NMinimize[poly, x] {-1.07023,{x->1.1309}} Use Minimize Minimize[poly, x] // N {-3.51391,{x->-1.30084}} A constraint NMinimize[{poly, x < 0}, x] {-3.51391,{x->-1.30084}} Or a starting interval NMinimize[poly, {x, -2, 1}] {-3.51391,{x->-1.30084}} Bob Hanlon Here is an example from Mathematica's user's guide: In[8]:= NMinimize[x^4 - 3 x^2 + x, x] Out[8]= {-3.513905039, {x -> -1.300839566}} however, trying to replicate it, I get the following: In[2]:= NMinimize[x^4 - 3 x^2 + x, x] Out[2]= {-1.070230182, {x -> 1.130901122}} One way to find the global min, I had to use a constraint such as x<0. Has anyone come across such a problem? In[3]:= $Version Out[3]= 7.0 for Microsoft Windows (32-bit) (November 10, 2008) === Subject: Re: FourierTransform I don't see anything in your post that I particularly disagree with but perhaps a few clarifications may be useful. I think I probably share you the view that the axiomatic method is only a method in mathematics and even not a particularly useful one. By the axiomatic method I mean the idea that all of mathematics should be deduced from some finite (preferably small) set of axioms. As I have already mentioned in another thread I think it has now been conclusively shown that such an approach is neither feasible nor does it really carry any particular advantages. However, I have a completely different view of another thing, which some people mistakenly identify with the axiomatic method and which I think correctly should be called the method of proof. In my view this method is so essential to mathematics that nothing that does not rely on it can properly be called mathematics. The difference between the method of proof and the axiomatic method is that the method of proof allows one to start with whatever one believes to be solidly grounded truth and then proceed deductively using steps that again are solidly grounded mathematical or logical truths. Of course when we do so we are guided by intuition (more about it below) but intuition itself cannot be used as justification for any mathematics. The reason why we must proceed in this way is not that it guarantees that we can never fail but because when we happen to arrive at conclusions that either contradict other established truths or contradict our intuition, we will know what assumptions we should re-examine (which could even be the logical steps themselves, again more about that below). An counter-intuitive result may but need not be wrong. A good example is the so called Banach-Tarski paradox, that played a big role in our understanding of basic measure theory. This could never have been arrived by means of intuition alone, and even if it had been, we would not have known what to do with it. In case someone thinks that this example is too pure mathematical, there are equally good ones that have very direct physical relevance. My favorite one concerns the violation of Bell's Inequality. Henry Stapp called this the most profound discovery in all of science and I completely agree. I think the implications of this discovery are so staggering that there is nothing else to compare with them (if Bernard D'Espagnat is right and Bell's Theorem implies that there is no such thing as objective reality then all scientific controversies, such as evolution vs. intelligent design etc become essentially irrelevant). But Bell's theorem could never have been discovered by any approach based on intuition. Indeed its conclusions are in stark contrast with every kind of intuition we have about the physical world. It is only be adopting a rigorously logical and deductive approach that Bell's Theorem could be proved, even though it is a truth of physics rather than of mathematics. Not surprisingly physicists seem to have given up on it in frustration and now it seems to be studied by logicians (e.g. see http://www.uni-bonn.de/~tmuelle2/philo/tmtp_lmps99.pdf ). Of course intuition plays a crucial role in mathematics. In fact, in addition to the sort of intuition that certain physicists have about certain kinds of mathematics, there is also a purely mathematical intuition. Mathematicians often refer to it as geometry even in areas such as algebra (algebraic geometry) or number theory etc, where conventional geometric imagination is not of much help. Without intuition mathematical discovery would not be possible, since the method of proof only helps one with verification of mathematical truths, not with their discovery. But the reason why we cannot base mathematics on intuition is that on the whole intuition is a very subjective thing: different people have completely different intuitions and what is intuitively obvious to one person may not be at all so to another (and quite often the second one is right). This is just as much true of purely mathematical intuition as of mathematical intuition derived from insight into physics. One of the many amazing phenomena concerning the relationship between mathematics and physics is the fact that certain mathematical physicists, most notably Edward Witten (the only physicist ever to receive a Fields medal and the only Field's medal winner who, it is said, has never proved a theorem) and Roger Penrose have an uncanny intuition about mathematical truth which seems to be based on a very deep insight derived from physics. Mathematicians have got use to the fact that when Witten tells them that a certain mathematical statements must be true they infallibly turn out to be so. This is indeed fantastic, but the problem is that this intuition is something that is possessed by Witten as an individual and not shared by other physicists. If we were to rely on this kind of intuition that would be no different from relying on the authority of one individual: Witten says so so it must be true. We don't need a proof. What is needed is something that does not rely on the insight or genius of one or several individuals. In mathematics the method of proof provides this. The collective insights of even a large number of less than genius physicists is not a substitute. Of course, and here may be the main difference between us, I am interested here only in establishing what is mathematical truth. If you are really arguing that what works in practice is good enough to establish what works i practice, then you are almost certainly right, but then our whole argument has been a complete waste of time. What I have been claiming that no amount of evidence from the practice of physicists can establish the validity of a mathematical procedure or its truth. The difference is illustrated by the following joke that I heard as an undergraduate student many years ago in the UK. An astronomer, a physicist and engineer were given the task of proving that all numbers greater than 1 were prime. The astronomer argued: 2 is a prime and 3 is a prime. We have checked one even number and it turned out to be prime, and one odd number and that was also prime. This provides overwhelming evidence that all numbers are prime. The physicist was more careful. 2 and 3 are primes, but 4 is not a that all numbers are prime is probably false but about 75% of all numbers greater than 1 are prime. I have thought it wiser to leave out the part of the joke concerning the engineer... Andrzej Kozlowski Witten Penrose intuition Bell's inequality joke >> this is called a distribution or generalized function >> and not a function and it is only defined >> inside of an integral as my Vladimirov http://www.amazon.de/Methods-Generalized-Functions-Analytical-Special/dp/0415 273560/ref=sr_1_33?ie=UTF8&s=books-intl-de&qid=1233576829&sr=8-33 say. > That restriction is Vladimirov's. We who actually apply generalized > functions to physics and engineering problems are not shy about > using > them outside of integrals. This is the approach that Mathematica > implements, as you can see below. A better reference is Bracewell: > www.amazon.com/Fourier-Transform-Its-Applications/dp/0073039381, > especially applicable to this question. By the way, the term distribution seems designed to confuse the > innocent. Many applications of generalized functions also involve > probability, where the term distribution has a different and far > more > familiar meaning. Most physicists and engineers will drop the generalized and simply > consider things like delta functions to be functions. They often > have > the right properties to represent the behavior of real world > objects, > when other notions of function don't. Sorry, but the last paragraph isn't that much of a recommendation. >> There is hardly any (pseudo)-mathematical nonsense that has not been >> believed to be true or valid by some engineer, occasionally with >> lamentable consequences. I remember that when, I was a math >> undergraduate, a popular mathematics journal published a long list >> of examples (with detailed references) of mathematical nonsense >> perpetrated by engineers, economists and some others (some quite >> hilarious). Well, the classic of this genre is Berkeley's mocking demolition of > calculus. Should physicists and engineers have abandoned calculus > after > Berkeley demonstrated that it was pseudo-mathematical nonsense? One I recall from my undergraduate days was a university computer > center > director who advocated automated scanning of student Fortran jobs on > the > mainframe to detect time-wasting infinite loops. He was ridiculed > as a > disgrace to his profession: doesn't he know about the halting > problem?. But the mockers got it wrong: he wasn't asking for a > perfect > decision procedure, merely a practical one that could weed out the > easily decidable cases. Of course, mathematicians perpetrate mathematical howlers, too. > Euler's > assertion that a divergent series may be replaced by its genesis > formula > is an example. The idea that mathematics advances by stepping from > truth > to truth by proving theorems is easily seen to be a myth if you know > some history. Mathematics is much more interesting, creative, and > useful > than that. Jens' authority, Vladimirov, asserts that a delta function is only > defined inside an integral. But I've also heard a mathematician > complain > that's not what we mean by integration. And Jens earlier insisted > on > square integrable functions. Different notions of function and > integral lead to different ideas about what is allowable. Calculus, Fourier analysis, delta functions, renormalization, all > recognized as mathematical nonsense in their time, yet they proved > to > be indispensable tools for effectively applying mathematics to real > world problems. > I think some of it might have involved the use (or misuse) >> of generalized functions, though I am no longer sure. (I guess I >> could >> still trace the list, if you really wanted to see it ...but you could >> instead just search the archives of this forum ;-)) The most intuitive yet rigorous theory of generalized functions that >> allows then to be treated as functions was created by Jean Francois >> his theory entitled Elementary Introduction to new Generalized >> Functions (North-Holland 1985). >> The Colombeau genealized functions have values at all points, but >> they >> are generalized numbers (which include ordinary numbers). Thus the >> Dirac Delta is a function defined on R, whose value is 0 for x!=0 and >> a generalized number at x==0. Colombeau generalized functions have >> derivatives of all orders (which are themselves generalized >> functions) >> and classical distributions are precisely those generalized functions >> which, in a neighborhood of each point, are partial derivatives of >> continuous functions. >> Colombeau theory was the first one that solved satisfactorily the old >> problem of giving a satisfactory definition of multiplication of >> generalized functions (something that before Colombeau was considered >> impossible by many). Colembeau theory justified much of the >> heuristics >> that had been previously known to physicists but it also helped to >> uncover nonsense where there was nonsense to uncover. The physical design of the communication network you used to broadcast > this assertion involved heavy use of applied mathematics results > obtained earlier than this using generalized functions. What is white > noise anyway? Mathematical (at least at the time its use became > common) > and even physical nonsense, but an indispensable concept. Mathematical objects are products of human imagination. That we can > obtain reliable knowledge of their properties is a profound mystery. > That they can effectively model real world objects is another profound > mystery. But they don't do so perfectly: any particular mathematical > model of reality will have (often poorly understood) limits to its > applicability. The justification for any applied mathematics model is > that you can verify it gets correct answers. The scientific method. > The > problem with most bad applied math in my experience is the dogmatic > use > of inapplicable methods. > Last but not least, Mathematica's notion of a generalized function is >> based on Colombeau. To convince yourself look at the documentation >> for >> HeavisideTheta, in the section Possible issues. I quote: Products of distributions with coincident singular support cannot be >> defined (no Colombeau algebra interpretation). I would guess that this sort of formalization is more important to a > CAS > than a human. Physical intuition is reasonably effective at weeding > out > the nonsense here, otherwise these techniques would never have > gained a > foothold. But a CAS has no physical intuition. It is nice that Mathematica 7 seems to have improved here. > I get the impression that not all engineers believe in this even now. Many engineers are suspicious of mathematical abstraction. > Mathematical > notions of correct and true don't map completely reliably into > real > world situations. So, understanding the connection between the > abstraction and the physical situation is essential. > Andrzej Kozlowski > >> Jens >> the Fourier transform over the interval x in (-Infinity,Infinity) >> converges only for quadratic integrable functions, i.e., >> functions >> where Integrate[Conjugate[f[x]]*f[x],{x,-Infinity,Infinity}]< >> Infinity This is not the case for Cosh[x], and so no Fourier transform >> exist. >>> Depends on what you mean by function. Mathematica tries in its >>> pragmatic way to do what you might want here: >>>> In[1]:= FourierTransform[t^2,t,w] >>>> Out[1]= -(Sqrt[2 Pi] DiracDelta''[w]) >>>> t^2 is certainly not square integrable, but this is the kind of >>> useful >>> result scientists and engineers want. >>>> Mathematica's support for generalized functions still has room >>> for >>> improvement, but it has come a long way. The bizarre problems I >>> saw in >>> the past trying Fourier methods to perform fractional >>> differentiation >>> and integration >>> (http://forums.wolfram.com/mathgroup/archive/2000/Apr/msg00043.html >>> ) >>> seem no longer to be with us in Mathematica 7. >>> -- > John Doty, Noqsi Aerospace, Ltd. > http://www.noqsi.com/ > -- > The axiomatic method of mathematics is one of the great achievements > of > our culture. However, it is only a method. Whereas the facts of > mathematics once discovered will never change, the method by which > these > facts are verified has changed many times in the past, and it > would be > foolhardy to expect that changes will not occur again at some future > date. - Gian-Carlo Rota -- > John Doty, Noqsi Aerospace, Ltd. > http://www.noqsi.com/ > -- > In theory there is no difference between theory and practice. In > practice there is. -Yogi Berra > === Subject: Re: Something for this list Well, I'm not going to try and build the tool but I think Mathematica can come quite close with a couple of standard tools, foremost of which is the new v7 BubbleChart in combination with Manipulate. CountryData contains (among many other bits of information) information on GDP, birth rate, population size and life expectancy. However, birth rate and life expectancy are available only for a single year so many of the charts in the TED talk can be done for a single year only. > Please check out the following links: Debunking third-world myths with the best stats you've ever seen http://www.ted.com/index.php/talks/hans_rosling_shows_the_best_stats_... New insights on poverty and life around the world http://www.ted.com/index.php/talks/hans_rosling_reveals_new_insights_... There are three reasons for posting this message: 1) to challenge > Mathematica 7 gurus to > produce an equivalent tool (look at the videos) for the dynamic display > of data, 2) a request to include > these poverty data in Mathematics WWW data sets (if they are not yet > there), and 3) to > make the mathgroup list aware of the TED talks site. --V. Stokes === Subject: Re: How to simplify? My apologies - I screwed up the original email. Here's the correct code which fails to simplify properly. The first two lines are designed to indicate what it ought to simplify to. S[r_] := 1/2 r BesselJ[1, r]; D[S[r], {r, 2}] + 1/r D[S[r], r] + S[r] // FullSimplify DSolve[y''[r] + 1/r y'[r] + y[r] == BesselJ[0, r], y[r], r] // FullSimplify (* Note: y[r] instead of S[r] *) Aaron === Subject: Re: most ChemicalData molecule plots missing? Hi Jean-Marc, I see exactly the same behaviour. Please report this to Wolfram. Daniel > i'm getting a lot of missing molecule plots for even the simplest and >> most common molecules in ChemicalData[]... in[]:= ChemicalData[CarbonMonoxide, MoleculePlot] >> ChemicalData[NitrogenDioxide, MoleculePlot] out[]= >> Missing[NotAvailable] >> Missing[NotAvailable] most hydrocarbons are also missing. is this normal, or could there be something wrong with my mathematica >> install or a cached curated data problem? > I tried the above examples with Mathematica 7.0 on a 32-bit Windows XP > Pro SP3 machine and got the same Missing[NotAvailable] results. I doubt that your installation might I have been corrupted because > ChemicalData have never been used on my test machine (everything had > been installed anew last week): it took several minutes to get the > initial process completed, displaying the waiting bar Accessing > server..., Initializing..., and the like, and nothing at the end :-) --Jean-Marc > === Subject: Re: most ChemicalData molecule plots missing? Hello Mitch: I am interested in this too. The number of missing plots is not evenly distributed. I ran some quick sample statistics: which molecules %missing first 100 90 last 100 97 900-1000 70 2900-3000 51 4900-5000 68 I did this with: partialCD = Take[Take[ChemicalData[], 1000], -100]; partialPlots = {#, ChemicalData[#, MoleculePlot]} & /@ partialCD; (* how many are missing *) Select[partialPlots, MatchQ[#[[2]], _Missing] &] // Length HTH. Roger Williams Franklin Laboratory > i'm getting a lot of missing molecule plots for even the simplest and > most common molecules in ChemicalData[]... > === Subject: Re: very slow Save[]s on Mathematica V7?? > I used to do complicated graphics with V6 and I am sure Save[] did not > take this long. Here is more strange info on this. The last command > below is: Import[http://exampledata.wolfram.com/usamap.zip, > ImageSize -> Medium] On V7 % // ByteCount gives 14792200 > On V6 the same command shows only 312?!?!? Does anyone know of a work-around for this annoying V7 problem? Franklin, Support for SHP files was added in V7. In version 6, you're just importing the list of filenames inside the zip file. With V7, Import expands the zip file, recognizes the SHP bundle, and Imports the map contained in the file. In[2]:= a = Import[http://exampledata.wolfram.com/usamap.zip, ImageSize -> Medium] Out[2]= {railroads.dbf, railroads.prj, railroads.shp, railroads.shx, states.dbf, states.prj, states.shp, states.shx} In[3]:= $Version Out[3]= 6.0 for Mac OS X x86 (64-bit) (May 21, 2008) In[5]:= a = Import[http://exampledata.wolfram.com/usamap.zip, ImageSize -> Medium]; In[6]:= Head@a Out[6]= Graphics In[7]:= ByteCount@a Out[7]= 15319544 In[8]:= $Version Out[8]= 7.0 for Mac OS X x86 (64-bit) (November 11, 2008) Igor === Subject: Re: testing if a point is inside a polygon Here is a function based on the code in Robert Sedgewick's Algorithms book: PointInPoly[{x_, y_}, poly_List] := Module[{i, j, c = False, npol = Length[poly]}, For[i = 1; j = npol, i <= npol, j = i++, If[((((poly[[i, 2]] <= y) && (y < poly[[j, 2]])) || ((poly[[j, 2]] <= y) && (y < poly[[i, 2]]))) && (x < (poly[[j, 1]] - poly[[i, 1]])*(y - poly[[i, 2]])/(poly[[j, 2]] - poly[[i, 2]]) + poly[[i, 1]])), c = [Not] c ]; ]; Return [c]; ] > is there a way to test whether a point is inside a polygon? ie. PointInsidePolygonQ[point_,polygon_] -> True or False i'm trying to do something like ... ListContourPlot[table,RegionFunction->CountryData[Canada= ,Polygon]] to create what would be called a clipping mask in photoshop. cheers, > Mitch === Subject: Re: testing if a point is inside a polygon Hi Mitch, To write a routines that checks if a point is inside a polygon you must realize that if you walk around the polygon you see a inner point always on the same side. This is false for a outside point. Therefore, the test is to check if the point in question: p0 is always on the same side of the polygon sides. Assume {p1,p1,..} are the polygon points, arrange in a definite order (clockwise or anti-clockwise). How can we check on which side of {pi+1, pi} p0 is? We may get a vector perpendicular to the side by rotating by Pi/2: {{0,1},{-1,0}}.(pi+1 - pi). If we take the dot product with (p0 -pi) the sign will tell us the side. Here is an example: pts = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; p0 = {0.5, 0.5}; sides= Subtract @@ # & /@ Partition[Append[pts, pts[[1]]], 2, 1]; perp= {{0,1},{-1,0}}.#& /@ sides; Equal @@ Sign @ MapThread[Dot, {p0 - # & /@ pts, perp}] The third lines calculates (pi+1 - pi), note that we added to first point to the end of the list to close the polygon. The fourth turns each vector by Pi/2. The fifth calculates p0-pi = {p0 - # & /@ pts and takes the Dot product of corresponding vectors. Finally it takes the sign and checks if all signs are the same. hope this helps, Daniel > is there a way to test whether a point is inside a polygon? ie. PointInsidePolygonQ[point_,polygon_] -> True or False i'm trying to do something like ... ListContourPlot[table,RegionFunction->CountryData[Canada,Polygon]] to create what would be called a clipping mask in photoshop. cheers, > Mitch > === Subject: Re: testing if a point is inside a polygon > is there a way to test whether a point is inside a polygon? ie. PointInsidePolygonQ[point_,polygon_] -> True or False You could have a look at the different algorithms presented in Paul Bourke's paper [1], pick up one of your liking, then code it from the provided C source code to Mathematica syntax. How the algorithms work, their benefits and draw backs, as well as tested C code and diagrams, are neatly presented. Depending of your level of familiarity with Mathematica programming, it might be easier to translate the C syntax into equivalent Mathematica procedural constructs, test the code, and then convert it into fast functional Mathematica code. If you have performance issues or troubles converting procedural code (fast in C, but slow in Mathematica) into functional code (fast in Mathematica), people in MathGroup will help you to improve performances or overcome coding issues. --Jean-Marc [1] Paul Bourke, Determining If A Point Lies On The Interior Of A Polygon, http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ === Subject: Re: testing if a point is inside a polygon Mitch, Here is my attempt. The idea is to move around the polygon and add up the angles made with the point. If the point is outside this will be zero. The steps are basically: 1) Check if the point is one of the vertices of the polygon. 2) Add the first polygon point to the end of the list of points. 3) Subtract the test point from each of the polygon vertices. 4) Partition the points into pairs. 5) Rotate each pair so the first one lies along the x axis. (To prevent crossing the branch line) 6) Find the ArcTan of the second point. This will have a sign. 7) Sum the angles and take the absolute value. 8) Test if this is zero or some multiple of 2[Pi]. PointInsidePolygonQ::usage = PointInsidePolygonQ[point,polygon] will return True if the point is on the boundary or inside the polygon and False otherwise.; PointInsidePolygonQ[point_, polygon_] := Module[{work}, If[ [Not] FreeQ[work, point], Return[True]]; work = # - point & /@ Join[work, {First[work]}]; work = Partition[work, 2, 1]; work = RotationTransform[{First[#], {1, 0}}]@# & /@ work; work = Abs@Total[ArcTan @@ Last[#] & /@ work] // Chop // Rationalize; TrueQ[work != 0] ] Here is a graphical test for a simple polygon: testpoints = testpoints = RandomReal[{-9, 9}, {100, 2}]; polypoints = {{-1.856, 3.293}, {1.257, 2.635}, {2.395, -0.6587}, {-1.018, -2.455}, {-3.293, -0.05988}}; Graphics[ {Lighter[Green, .8], Polygon[polypoints], AbsolutePointSize[4], {If[PointInsidePolygonQ[#, polypoints], Black, Red], Point[#]} & /@ testpoints}, PlotRange -> 10, Frame -> True] Here is a test for a more complex polygon. testpoints = testpoints = RandomReal[{-9, 9}, {100, 2}]; polypoints = {{-3.653, 5.329}, {0.2395, 6.168}, {-0.8982, 1.138}, {-0.6587, 1.138}, {5.569, 3.234}, {6.527, -2.036}, {1.677, 0.479}, {-6.407, -1.976}, {-5.21, 2.635}, {1.856, -3.713}}; Graphics[ {Lighter[Green, .8], Polygon[polypoints], AbsolutePointSize[4], {If[PointInsidePolygonQ[#, Polygon[polypoints]], Black, Red], Point[#]} & /@ testpoints}, PlotRange -> 10, Frame -> True] There might be simpler methods. David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ is there a way to test whether a point is inside a polygon? ie. PointInsidePolygonQ[point_,polygon_] -> True or False i'm trying to do something like ... ListContourPlot[table,RegionFunction->CountryData[Canada,Polygon]] to create what would be called a clipping mask in photoshop. cheers, Mitch === Subject: Re: testing if a point is inside a polygon the web is full of this test as well as any graphics book. Look at http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ http://tog.acm.org/editors/erich/ptinpoly/ Jens > is there a way to test whether a point is inside a polygon? ie. PointInsidePolygonQ[point_,polygon_] -> True or False i'm trying to do something like ... ListContourPlot[table,RegionFunction->CountryData[Canada,Polygon]] to create what would be called a clipping mask in photoshop. cheers, > Mitch > === Subject: Re: testing if a point is inside a polygon Mitch, please find below what I use for his purpose. I hope it is useful. Frank is there a way to test whether a point is inside a polygon? ie. PointInsidePolygonQ[point_,polygon_] -> True or False i'm trying to do something like ... ListContourPlot[table,RegionFunction- >CountryData[Canada,Polygon]] to create what would be called a clipping mask in photoshop. cheers, > Mitch > PointInPolygonQ::usage=PointInPolygonQ[pt, poly] uses the winding- number algorithm (Godkin and Pulli, 1984) to check, if point pt is inside the closed polygon poly, which is given as list of its vertices. (* checks, if a point is inside a polygon pt: point as {lat [deg], lon [deg]} to test poly: list of polygon vertices coordinates GODKIN,C.B. AND J.J.PULLI: APPLICATION OF THE WINDING-NUMBER ALGORITHM TO THE SPATIAL SORTING OF CATALOGED EARTHQUAKE DATA. Bull. Seismol. Soc. Am. 74, 5, PP. 1845-1848, OCTOBER 1984 RETURN VALUE: 0 IF POINT OUTSIDE +/-1 IF POINT INSIDE 2 IF POINT IS ON AN EDGE OR VERTEX *) PointInPolygonQ[pt_,poly_] := Module[ { i,n,isicr,inside,px,py,pxx,pyy,x0,y0 }, n = Length[poly]; (* ACCUMULATE SIGNED CROSSING NUMBERS WITH INSIDE *) inside = 0; {x0,y0}=pt; For[i=1,i < n,i++, (* PROCEED AROUND POLYGON CHECKING EACH SEGMENT TO SEE IF NEGATIVE X-AXIS WAS CROSSED TRANSLATE COORDINATES OF POLYGON TO PUT TEST POINT AT ORIGIN *) {px,py} = poly[[i]]; {pxx,pyy} = poly[[i+1]]; isicr = ksicr[px - x0, py - y0, pxx - x0, pyy - y0]; (* STOP COUNTING IF POINT IS ON EDGE *) If[isicr == 4, Return[2]]; inside += isicr; ]; (* CHECK SEGMENT FROM LAST VERTEX TO FIRST VERTEX *) {px,py} = poly[[n]]; {pxx,pyy} = poly[[1]]; isicr = ksicr[px - x0, py - y0, pxx - x0, pyy - y0]; If[isicr == 4, Return[2]]; inside = (inside + isicr)/2; Return[inside]; ]; (* COMPUTE SIGNED CROSSING NUMBER A SIGNED CROSSING NUMBER TELLS WETHER A SEGMENT (IN THIS CASE THE SEGMENT FROM (X1,Y1) TO (X2,Y2)) CROSSES THE NEGATIVE X-AXIS OR GOES THROUGH THE ORIGIN THE RETURN VALUES ARE: +2 IF SEGMENT CROSSES FROM BELOW +1 IF SEGMENT EITHER ENDS ON -X-AXIS FROM BELOW OR STARTS UPWARDS FROM -X-AXIS (HALF CROSSING) 0 IF THERE IS NO CROSSING -1 IF SEGMENT EITHER ENDS ON -X-AXIS FROM ABOVE OR STARTS DOWNWARDS FROM -X-AXIS (HALF CROSSING) -2 IF SEGMENT CROSSES FROM ABOVE +4 IF SEGMENT CROSSES THROUGH THE ORIGIN *) ksicr[x1_,y1_,x2_,y2_] := Module[ { }, If[N[y1*y2 > 0.], Return[0] (* no crossing *)]; (* CHECK IF SEGMENT CROSSES THROUGH THE ORIGIN *) If[x1*y2 != x2*y1 || x1*x2 > 0., If[y1 * y2 < 0, (* COMPLETE CROSSING OF -X-AXIS? BREAK INTO CASES ACCORDING TO CROSSING DIRECTION *) If[y1 > 0, (* CASE Y1 > 0 > Y2 *) If[y1 * x2 >= x1 * y2, Return[0];, (* no crossing *) Return[-2]; (* downward crossing *) ]; , (* CASE Y1 < 0 < Y2 *) If[x1 * y2 >= y1 * x2, Return[0];, (* no crossing *) Return[2]; (* upward crossing *) ]; ]; , (* HALF CROSSING? ONE END OF SEGMENT TOUCHES X-AXIS! WHICH END? *) If[y2 == 0, (* HERE Y2==0 CHECK IF SEGMENT TOUCHES +X-AXIS *) If[y1 == 0 || x2 > 0, Return[0]; (* no crossing *) , (* UPWARD OR DOWNWARD? *) If[y1 > 0., Return[-1]; (* Downward half crossing *) , Return[1]; (* Upward half crossing *) ]; ]; , (* HERE Y1==0 CHECK IF SEGMENT TOUCHES +X-AXIS *) If[x1 > 0, Return[0]; , (* UPWARD OR DOWNWARD? *) If[y2 > 0, Return[1]; (* Upward half crossing *) , Return[-1]; (* Downward half crossing *) ]; ]; ]; (* HERE Y1=0 CHECK IF SEGMENT TOUCHES +X-AXIS *) If[x1 > 0, Return[0]; (* no crossing *) ]; (* UPWARD OR DOWNWARD? *) If[y2 > 0., Return[-1]; (* Downward half crossing *), Return[1]; (* Upward half crossing *) ]; ]; , Return[4]; ]; ]; === Subject: Re: Problem importing HTML with Mathematica Add the Source tag to your Import line to get the source. By default Mathematica uses the Plaintext tag (see ref/format/HTML in v7's documentation centre): Import[http://www.atpworldtour.com/5/en/vault/draws.asp?TournamentID= 352&TournamentYear=1993, Source] > Hi there, I had a Mathematica program that, among other things, had to import > html code from a web site. Recently they made some changes in the web site and the program is not > importing properly anymore. Instead of getting the source html code I > would see with my internet browser I am just getting a simplified > version of it (with no html syntax at all). I do not know what may have changed, but as a guess, it seems to me as > if the web site realized that it is not a proper internet browser the > one who is connecting and therefore it is sending back a simplified > version of the page. As an example, you can just run: > Import[http://www.atpworldtour.com/5/en/vault/draws.asp?TournamentID= 352&TournamentYear=1993] > === Subject: Re: Problem importing HTML with Mathematica > Hi there, I had a Mathematica program that, among other things, had to import > html code from a web site. Recently they made some changes in the web site and the program is not > importing properly anymore. Instead of getting the source html code I > would see with my internet browser I am just getting a simplified > version of it (with no html syntax at all). I do not know what may have changed, but as a guess, it seems to me as > if the web site realized that it is not a proper internet browser the > one who is connecting and therefore it is sending back a simplified > version of the page. As an example, you can just run: > Import[http://www.atpworldtour.com/5/en/vault/draws.asp?TournamentID= 352&TournamentYear=1993] Did you just upgrade your version of Mathematica? Try adding an explicit second argument to Import telling it which format you want. For example, these all work: Import[http://www.atpworldtour.com/5/en/vault/draws.asp? TournamentID=352&TournamentYear=1993,Plaintext] Import[http://www.atpworldtour.com/5/en/vault/draws.asp? TournamentID=352&TournamentYear=1993,Text] Import[http://www.atpworldtour.com/5/en/vault/draws.asp? TournamentID=352&TournamentYear=1993,XMLObject] -Rob === Subject: Re: Problem importing HTML with Mathematica > I had a Mathematica program that, among other things, had to import > html code from a web site. Recently they made some changes in the web site and the program is not > importing properly anymore. Instead of getting the source html code I > would see with my internet browser I am just getting a simplified > version of it (with no html syntax at all). As specified in the documentation about the HTML file format [1], Import[file.html] gives a plain text representation of an HTML file. > I do not know what may have changed, but as a guess, it seems to me as > if the web site realized that it is not a proper internet browser the > one who is connecting and therefore it is sending back a simplified > version of the page. Works the same with version 6.0.3 or 7.0 on two different platforms. Perhaps you have change something on your system. > As an example, you can just run: > Import[http://www.atpworldtour.com/5/en/vault/draws.asp?TournamentID= 352&TournamentYear=1993] Anyway, add the element Source to your query to get the HTML source of the page. In[2]:= Import[http://www.atpworldtour.com/5/en/vault/draws.asp? TournamentID=352&TournamentYear=1993, Source] Out[2]= atpworldtour.com - Event Draw --Jean-Marc [1] HTML (.html, .htm), doc centre ref/format/HTML, web http://reference.wolfram.com/mathematica/ref/format/HTML.html === Subject: Re: FindFit & NIntegrate On Feb 9, 4:34 am, Jens-Peer Kuska no, but the news group has ruleshttp://smc.vnet.net/mathgroup.html > and one of these rules is: PLEASE SEARCH THE ARCHIVES BEFORE YOU ASK WHAT MIGHT BE A COMMON QUESTION and I think a poster in the group should > try to follow the group rules. Jens if a questions appears over and over (10^6 times before) it should > mean something to thinking people! Latins used to say, Errare humanum est, perseverare diabolicum. Does > this mean anything to Mathematica developers? Do you mean that it is > impossible to find a sensible way to do something that 10^6 people > would do differently? ADL On 6 Feb, 10:10, Jens-Peer Kuska > and > model[x_?NumericQ,a_?NumericQ,b_?NumericQ,c_?NumericQ]:= >> NIntegrate[function[x_,t_,a_,b_,c_],{t,0,inf}]; > will work. We had this 10^6 times before. > Jens I want to use the FindFit function (or similar) to fit some > experimental data: > fit=FindFit[data,expr,pars,vars] > Usually this works very well, but in this particular case the model > expr consists of a NIntegrate over another function, like: > model[x_,a_,b_,c_]:=NIntegrate[function[x_,t_,a_,b_,c_],{t,0,inf}]; > fit=FindFit[data,model[x,a,b,c],{a,b,c},x] > FindFit now complains about non-numerical values; of course that makes > sense. > How can I force FindFit to do the fitting anyway? My opinion counts for nothing, but I found the topic very useful. Perhaps posters who ask questions that have already been treated should have to provide a supply of extra electrons to replace for those that were wasted. === Subject: Re: Map[] and multiple args function >I know this has to be FAQ, but I'm just not able to find an answer >anywhere, so - here it goes: I have a multiple-arguments function, >say something like: >Foo[x_, y_, z_] := x + 2*y + 3*z >Now, I want to call this function number of times, over different >sets of arguments, and then to sum results. I thought about storing >argument triplets into some kind of list, and then employing >sequence of Map[] and Apply[] to get the job done. After number of >trials and errors, I came up with following piece of code doing the >thing: >Plus @@ Foo /@ {{1, 2, 3}, {4, 5, 6}} /. List -> Sequence >but I even don't fully understand what's going here, and also I'm >wondering is there a better way to accomplish this. So - any >suggestion? Better always depends on what is meant by better. There are alternatives. One alternative that is more compactly written would be: Total[Foo @@@ {{1, 2, 3}, {4, 5, 6}}] === Subject: Re: newbie: explicit function works, function object doesn't Tom, It is generally good practice to have ALL symbols in a function definition be part of the definition itself and not just 'hanging loose'. This made a difference in the Manipulate statement because the control parameters are local variables within the Manipulate statement. That is why it would not work for you until you put the definitions and solution inside the Manipulate statement. First solve the differential equation and obtain a function for theta that contains the parameters in the definition of the function. In this case the parameters are entered as what are called SubVaues in Mathematica. You could remove the semicolons to see the intermediate steps. Clear[theta]; linearPendulum = {theta''[t] == -omega^2 theta[t]}; Part[DSolve[{linearPendulum, theta'[0] == v0, theta[0] == theta0}, theta, t], 1, 1]; theta[omega_, theta0_, v0_][t_] = theta[t] /. % (omega theta0 Cos[omega t] + v0 Sin[omega t])/omega We can see that we now have a way to express the function with any particular set of parameters. theta[2, 3, 1][t] 1/2 (6 Cos[2 t] + Sin[2 t]) Now the Manipulate statement is much simpler. All we need is the Plot statement. Dynamic plots like this are much better if they are displayed with a fixed PlotRange. However, you might want to add an additional control to set the vertical plot range. Manipulate[ Plot[theta[omega, theta0, v0][t], {t, -2 [Pi], 2 [Pi]}, Frame -> True, AxesStyle -> LightGray, PlotRange -> {{-2 [Pi], 2 [Pi]}, {-5, 5}}], {{omega, 1}, 0.0001, 5, Appearance -> Labeled}, {{theta0, 1}, 0, 5, Appearance -> Labeled}, {{v0, 1}, 0, 5, Appearance -> Labeled}] Now you should be able to do the damped oscillator. David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ summary: I've got a function that I can Manipulate, but I can't Manipulate the things to which the function is assigned. I'm assuming this is due to a syntax error. details: === As advertised by the Subject:, I'm new to Mathematica (specifically M7 running on a linux cluster) so please excuse any lapses in terminology. I'd also appreciate pointers to specific docs rather than just an RTFM. Also feel free to refer to my notebook @ http://www.unc.edu/~tr/classes/GEOL861/hw1Notebook.nb I'm trying initially to model a linearized pendulum theta''[t] == -omega^2 theta[t] (where omega=g/l) with the simple initial conditions theta'[0]==v0 theta[0]==theta0 Using soln = DSolve[{linearPendulum, theta'[0] == v0, theta[0] == theta0}, theta[t], t] I get the solution theta[t] -> (omega*theta0*Cos(omega*t) + (v0*Sin(omega*t)))/omega However, when I try to Manipulate[Plot[soln...]], I get ... nothing. Not an error, and I do get the appropriate UI, but I don't get a plot. RHS of 'soln', which I'll refer to here as a function. (Please correct my usage as needed.) I got a function object with ReplaceAll happysoln[t_] = theta[t] /. soln[[1]] similar to a working example I've seen. But Manipulate[Plot[happysoln...]] also fails silently, like the previous. However, when I manipulate the function directly Manipulate[Plot[(omega theta0 Cos[omega t] + v0 Sin[omega t])/omega, {t, -2 Pi, 2 Pi}], {{omega, 1}, 0, 5}, {{theta0, 1}, 0, 5}, {{v0, 1}, 0, 5}] it works as designed: I get the UI with the plot, which I can twiddle with the sliders. Why can I Manipulate the function, but not the containers of the function (i.e. soln, happysoln)? More importantly, with what syntax can I Manipulate those containers? TIA, Tom Roche === Subject: Re: newbie: explicit function works, function object doesn't you get nothing because a global symbol named v0 has nothing to do with a symbol Manipulate[__,{v0,-1,1},__] because Mathematica localize the symbols. You can see this with Manipulate[{Hold[v0], v0}, {v0, -1, 1}] it will show you the true name of v0 as FE`v0$$* And so the simple version f[t_]:=Sin[w*t] Manipulate[Plot[f[t], {t, 0, Pi}], {{w, 1}, 0, 10}] will not work, because the w in the definition of f[] is total different from the w inside Manipulate[] But Manipulate[ Plot[f[t] /. w -> w1, {t, 0, Pi}], {{w1, 1, [Omega]}, 0, 10}] will work, because the outside w is replaced by the inside-Manipulate w1 Jens > summary: I've got a function that I can Manipulate, but I can't > Manipulate the things to which the function is assigned. I'm assuming > this is due to a syntax error. details: > === > As advertised by the Subject:, I'm new to Mathematica (specifically M7 > running on a linux cluster) so please excuse any lapses in > terminology. I'd also appreciate pointers to specific docs rather than > just an RTFM. Also feel free to refer to my notebook @ http://www.unc.edu/~tr/classes/GEOL861/hw1Notebook.nb I'm trying initially to model a linearized pendulum theta''[t] == -omega^2 theta[t] (where omega=g/l) with the simple initial conditions theta'[0]==v0 > theta[0]==theta0 Using soln = DSolve[{linearPendulum, theta'[0] == v0, theta[0] == theta0}, > theta[t], t] I get the solution theta[t] -> (omega*theta0*Cos(omega*t) + (v0*Sin(omega*t)))/omega However, when I try to Manipulate[Plot[soln...]], I get ... nothing. > Not an error, and I do get the appropriate UI, but I don't get a plot. RHS of 'soln', which I'll refer to here as a function. (Please > correct my usage as needed.) I got a function object with ReplaceAll happysoln[t_] = theta[t] /. soln[[1]] similar to a working example I've seen. But > Manipulate[Plot[happysoln...]] also fails silently, like the previous. However, when I manipulate the function directly Manipulate[Plot[(omega theta0 Cos[omega t] + v0 Sin[omega t])/omega, > {t, -2 Pi, 2 Pi}], {{omega, 1}, 0, 5}, {{theta0, 1}, 0, 5}, {{v0, 1}, > 0, 5}] it works as designed: I get the UI with the plot, which I can twiddle > with the sliders. Why can I Manipulate the function, but not the containers of the > function (i.e. soln, happysoln)? More importantly, with what syntax > can I Manipulate those containers? TIA, Tom Roche