MathGroup Archive 1999

[Date Index] [Thread Index] [Author Index]

Search the Archive

RE: Magnitude of Vector

  • To: mathgroup at smc.vnet.net
  • Subject: [mg19415] RE: [mg19339] Magnitude of Vector
  • From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
  • Date: Mon, 23 Aug 1999 13:57:23 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

Ed McBride wrote:
----------------------
Was doing some stuff that required 3-D vectors.  Found Dot and Cross,
but couldn't find a primitive operator for Magnitude.  Is there one?  If
not, there definitely should be.
---------------------

No it isn't built-in, and you have a good point.  Until it is a built-in
function the following should do it quite efficiently, and even post
messages for invalid arguments.  It also works for vectors of any dimension
(not only 3D).

I included the part about  /;(Length[v]=!=0)
so that   Magnitude[{}]  would be undefined as I think it should.

---------------------

In[1]:=
Magnitude::vect="Mag is only defined for vectors.  The expression `1` is not
a vector.";
Magnitude[v_?VectorQ]/;(Length[v]=!=0):=Sqrt[Plus@@(v^2)];
Magnitude[expr_]/;Message[Magnitude::vect,expr]:="Never get here";
Magnitude[_,more__]/;Message[Magnitude::argx,Magnitude,Length[{more}]+1]:="N
ever get here";


In[5]:=
Magnitude[{w,x,y,z}]

Out[5]=
Sqrt[w^2 + x^2 + y^2 + z^2]



In[6]:=
Magnitude[a+b]

Magnitude::vect: Mag is only defined for vectors.  The expression a+b is not
a vector.

Out[6]=
Magnitude[a + b]



In[7]:=
Magnitude[{x,y,z},{a,b,c}]

Magnitude::argx: Magnitude called with 2 arguments; 1 argument is expected.

Out[7]=
Magnitude[{x, y, z}, {a, b, c}]


Notice when Magnitude gets invalid input a message is posted and the
expression is returned unevaluated.  For the case when more than one
argument is given I used one of the 
General::tag messages found in the (messages.m) file.  For the case where
the argument isn't a vector I defined my own message (Message::vect).

You could make this a little more complicated and ensure a CompiledFunction
is used when possible.  I tried that, but it the speed advantage was only
about 25% for very long vectors.

---------------------
Regards,
Ted Ersek

For Mathematica Tips, Tricks see
http://www.dot.net.au/~elisha/ersek/Tricks.html
 


  • Prev by Date: Re: Simulation...Ooops
  • Next by Date: Re: Multiple sum with iterators that cannot equal
  • Previous by thread: Re: Magnitude of Vector
  • Next by thread: Re: Magnitude of Vector