MathGroup Archive 1999

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

Search the Archive

RE: Magnitude of Vector

  • To: mathgroup at
  • Subject: [mg19415] RE: [mg19339] Magnitude of Vector
  • From: "Ersek, Ted R" <ErsekTR at>
  • Date: Mon, 23 Aug 1999 13:57:23 -0400
  • Sender: owner-wri-mathgroup at

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.


Magnitude::vect="Mag is only defined for vectors.  The expression `1` is not
a vector.";
Magnitude[expr_]/;Message[Magnitude::vect,expr]:="Never get here";
ever get here";


Sqrt[w^2 + x^2 + y^2 + z^2]


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

Magnitude[a + b]


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

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.

Ted Ersek

For Mathematica Tips, Tricks see

  • 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