MathGroup Archive 2005

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

Search the Archive

Re: New to Mathematica- How to write functions????????

  • To: mathgroup at
  • Subject: [mg58883] Re: [mg58876] New to Mathematica- How to write functions????????
  • From: "Yasvir A. Tesiram" <tesiramy at>
  • Date: Fri, 22 Jul 2005 01:58:32 -0400 (EDT)
  • References: <>
  • Sender: owner-wri-mathgroup at

On Thu, 21 Jul 2005, Someonekicked wrote:

> new to mathematica, looked at the help, but did not get the help i needed..
> I want to write a function that does multiple calculations in its body, then
> it returns a value.
> I am talking about functions similar to functions that you can declare in
> C++.
> can anyone give me an example?
> in C++, a function would be like, (note int means integer)
> int zzz(int s, int y)
> {
>   int  Q;
>   Q = s*y;
>   return Q;
> }
> well thats just a simple example, the body of my function is going to be
> complicated...
> I know in mathematica, I can solve the same zzz by
> zzz[s_,y_] := s*y;
> However, what if i want the body more complicated and do more than one
> thing??

Hi Someonekicked,

I would suggest the use of Module or Block. Here are some examples.

(*Perhaps the simplest example is;*)


(*arguments are of correct form here*)


(*arguments are not of correct form here*)


(*Here is another slightly complicated example.*)
(*Load up any packages you may need*)


(*Here is a function that will take a matrix and a vector as its arguments 
and it doesn't matter whether the matrix or the vector contain integers or 
pure numbers or reals. Inside the module once everything is structured 
properly the local variable m is forced to be numerical by Mathematicas N 
function. The assignment v = vec is somewhat of a habit for my sanities 
sake, but you can use vec in place of v in FoldList. The return type 
from a inside a Module is whatever the last line is. Leave the 
semi-colon out or the return type will default to Null.*)

hmm[b_?MatrixQ, vec_?VectorQ] := Module[{m, v},

     m = MapThread[RotationMatrix3D, b] // N;
     v = vec;
     FoldList[#2.#1 &, v, m]

(*Note, the magic number 629 is the length of the first list of the list 
contained in the variable pulse*)

pulse = {Table[Cos[ x], {x, -2Pi, 2Pi, Pi/(50Pi)}], Table[45, {629}],
       Table[45, {629}]};

(*Use the function hmm that was made above*)

rotation = hmm[pulse, {0, 0, 1}];

(*And here is a graphic that may be difficult to do directly from C++*)

         Sphere[0.25, 50, 50]
   Boxed -> False,
   ViewPoint -> {-1.5, 2.5, 0.2},
   AmbientLight -> CMYKColor[0.0, 1.0, 0, 0.2],
   Background -> IvoryBlack,
   ImageSize -> 400,
   PlotRange -> All


  • Prev by Date: Re: New to Mathematica- How to write functions????????
  • Next by Date: Re: Combinatorica functions doc
  • Previous by thread: Re: New to Mathematica- How to write functions????????
  • Next by thread: Re: New to Mathematica- How to write functions????????