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

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 4K views
Physics_rocks
Messages
12
Reaction score
0
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
 
Physics news on Phys.org
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.