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

Click For Summary
SUMMARY

This discussion focuses on writing functions in Wolfram Mathematica, specifically how to create a function that returns [1, 0, -1] based on integer input values. The user initially attempted to use nested If statements but was directed to utilize the built-in Sign function for this purpose. Additionally, the conversation delves into the concept of patterns in Mathematica, highlighting their importance in function definitions and providing guidance on refining patterns using the /; and ? operators.

PREREQUISITES
  • Familiarity with Wolfram Mathematica syntax
  • Understanding of function definitions in programming
  • Basic knowledge of conditional statements
  • Introduction to pattern matching in Mathematica
NEXT STEPS
  • Explore the built-in Sign function in Wolfram Mathematica
  • Study the tutorial on patterns in Mathematica
  • Learn about the /; operator for conditional pattern matching
  • Investigate the use of the ? operator for pattern specifications
USEFUL FOR

This discussion is beneficial for Mathematica users, programmers transitioning from Matlab, and anyone interested in mastering function writing and pattern matching in Wolfram Mathematica.

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
3K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 13 ·
Replies
13
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K