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

Click For Summary
Writing functions in Mathematica can be challenging for those accustomed to Matlab. A specific function is needed to return values of [1, 0, -1] based on whether an integer is positive, zero, or negative. The initial attempt used nested If statements, but a more efficient solution is to utilize the built-in Sign function, which directly provides the desired output. Additionally, the discussion highlights the importance of understanding patterns in Mathematica. Patterns are integral to function definitions, as demonstrated by the use of x_ in the sigNum function. To refine patterns, users can employ the /; operator to set conditions and the ? operator to specify types, such as x_Integer/;(x<0) for matching negative integers. For further learning, it is recommended to explore the tutorial on patterns available in the Mathematica help window.
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.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K