Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Can someone please explain how to write functions in Wolfram Mathematica ?

  1. Jan 6, 2010 #1
    I'm good in writing functions in Matlab , however since moving to Mathematica , I find it pretty hard to write them . For instance I need to write a function that returns a [1,0,-1] to integers, meaning x>0 , x==0 , x<0

    with a single If , but I didn't find a way with one (only two)
    sigNum[x_] := If[x < 0, -1, If[x > 0, 1, 0]]

    and then using with PATTERNS . what are patterns and how do I use them ? tnx
     
  2. jcsd
  3. Jan 9, 2010 #2

    Dale

    Staff: Mentor

    There is a built in function for this called Sign.

    Regarding patterns, you may want to start with the tutorial on patterns. In the search field of the help window type in: tutorial/PatternsOverview

    Basically, you are already using patterns in the above definition, specifically, in sigNum[x_] the x_ is a pattern named x. You can refine your patterns to only apply in certain conditions by using the /; operator and the ? operator and you can also specify the head of the pattern. So x_Integer/;(x<0) would be a pattern that would match any negative integer.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Can someone please explain how to write functions in Wolfram Mathematica ?
Loading...