Kahibaro
Discord Login Register

Using Built-In Constants and Functions

Overview

MATLAB provides a large collection of built in constants and functions that you can use immediately, without defining them yourself. Understanding how to call these functions correctly, how they differ from variables, and how to discover new ones is an essential part of working efficiently in MATLAB.

This chapter focuses on using constants and functions that are already available in MATLAB, rather than creating your own. You will see how to call simple numeric functions, how to use basic mathematical constants, and how to explore what else is available.

Built in constants

Some mathematical quantities appear so often that MATLAB provides them as built in values. These are not variables you define yourself, and you should avoid overwriting their names.

The most common constants you will use are:

The constant pi represents the number $\pi \approx 3.14159265358979$. You can use it directly in expressions, for example 2pi, sin(pi/4), or exp(1ipi).

The constant Inf represents positive infinity, which you might see when a value grows beyond the largest finite floating point number, or when you divide a nonzero number by zero, as in 1/0. Negative infinity is represented by -Inf.

The constant NaN means “Not a Number”. It represents undefined numeric results, such as 0/0 or Inf - Inf. MATLAB treats NaN as a special value in computations and comparisons.

The constant eps represents the distance between 1 and the next larger double precision floating point number. It is useful in numerical work when you need a sense of machine precision.

For complex numbers, the symbol 1i (or equivalently 1j) represents the imaginary unit $\sqrt{-1}$. The letters i and j alone can also be used, but only if you have not assigned them your own values.

You can display the values of these constants directly in the Command Window, for example by typing pi or Inf and pressing Enter.

Avoiding overwriting built in constants

Since built in constants are just names in the workspace, MATLAB does not prevent you from creating variables with the same names. For example, you can accidentally write pi = 3; and from that moment on, pi in your workspace will no longer refer to the mathematical constant.

If you suspect that you have overwritten a constant, you can remove your variable with clear, for example clear pi, and MATLAB will again use the built in value.

The same applies to i and j. If you assign i = 5;, then 1i still works as the imaginary unit, but plain i refers to your variable. It is usually safer to use 1i or 1j in numeric expressions involving complex numbers to avoid any confusion.

Calling built in functions

A function in MATLAB is called by writing its name followed by parentheses. The inputs to the function, also called arguments, go inside the parentheses, separated by commas. The function typically returns at least one output value.

For example, sin(1) computes the sine of 1 radian, and sqrt(9) computes the square root of 9. In both cases, the function name, such as sin or sqrt, is followed by parentheses that contain the expression you want to evaluate.

Many built in functions operate elementwise on arrays, so if x is a vector, then sin(x) computes the sine of each element of x and returns a vector of the same size. Some functions, such as sum or mean, combine the elements of an array and return a single result or a result with fewer dimensions.

You can assign the output of a built in function to a variable by writing an assignment, for example y = log(10); or r = abs(-3);.

If a function does not require any input arguments, you still use parentheses, but leave the inside empty. For instance, now() returns the current date and time as a numeric value, and rand() returns a single random number between 0 and 1.

Function names versus variable names

In MATLAB, function names and variable names share the same namespace. This means that if you create a variable with the same name as a built in function, MATLAB will treat that name as a variable first and the function will no longer be directly callable using that name.

For example, if you write sin = 5;, then try to run sin(1), MATLAB will attempt to index into the variable sin instead of calling the sine function, and you will see an error. To restore access to the function, you must clear the variable with clear sin.

Because of this, avoid using names of common functions, such as sum, mean, max, min, plot, or rand, as variable names. If you accidentally shadow a function with a variable, which can help you check what MATLAB is using. Typing which sin after you have created sin = 5; will indicate that MATLAB sees a variable rather than a function.

Basic mathematical functions

MATLAB has many built in functions for common mathematical operations. These go far beyond the basic arithmetic operators and let you perform more complex calculations with simple expressions.

Trigonometric functions such as sin, cos, and tan compute the standard trigonometric ratios in radians. Inverse functions are available as asin, acos, and atan. There are also hyperbolic versions like sinh, cosh, and tanh.

Exponential and logarithmic functions include exp for $e^x$, log for the natural logarithm $\ln(x)$, and log10 for the base 10 logarithm. These functions work with scalars and also apply elementwise to vectors and matrices.

Other frequently used functions include abs for the absolute value or magnitude, sqrt for the square root, and power for exponentiation when you want a function call instead of the ^ operator. For many of these operations, MATLAB also provides operators, but the functions can be clearer in some contexts.

MATLAB also has functions for computing simple descriptive statistics, such as sum, prod, mean, median, min, and max. These can act along the elements of a vector or across dimensions of a matrix, depending on how you call them.

Getting information about a function

You do not have to memorize every function and its exact syntax. MATLAB includes built in help that describes what each function does and how to use it.

To read the documentation for a function directly in the Command Window, use the help command. For example, typing help sin shows a short description of the sine function, its syntax, and a few details about its behavior.

For more detailed information, use doc. For example, doc sin opens the full documentation page in the Help browser, with more examples and links to related functions. The documentation often shows how functions behave with vectors and matrices, which is important when you work with arrays.

If you are not sure whether a name refers to a built in function, a file, or something else, you can use which. Typing which sqrt tells you where the function sqrt is defined. If you have created your own function or variable that shadows a built in one, which helps you diagnose that.

Discovering available functions

MATLAB offers several ways to find functions that might be useful for a particular task, even if you do not know their exact names.

You can use the help function with a category name to see related functions. For instance, help elfun shows a list of elementary math functions like sin, cos, exp, log, and similar functions. The specfun and matfun categories cover special mathematical functions and matrix functions respectively.

In the Help browser, the search box lets you type a phrase such as “square root” or “random numbers”. MATLAB suggests relevant documentation pages and function names. This can be very helpful when you only remember what you want to achieve, not the precise function name.

In the Command Window and Editor, type a few characters of a function name and press the Tab key to see auto completion suggestions. MATLAB shows possible function and variable names that match what you have started to type.

Function syntax and parentheses

Correct use of parentheses is important when you call built in functions. Every function call must include parentheses, even if there are no input arguments.

For example, to create a 3 by 3 matrix of random numbers, you use rand(3,3). If you write rand 3,3 without parentheses, MATLAB interprets this as a command style call that may not behave as you expect, and this style is generally discouraged.

When an input expression is more complicated, place it inside the function parentheses, such as sin(2pi0.25) or log(1 + x.^2). MATLAB evaluates the inside of the parentheses first, then passes the result to the function.

If a function can return multiple outputs, you can capture them using square brackets, for example [m, idx] = max(v);, where m is the maximum value and idx is its position in the vector v. If you only need the first output, you can simply write m = max(v);.

Common mistakes with built in functions

Beginners often run into a few recurring issues when using built in functions and constants.

One common error is forgetting the parentheses when calling a function and expecting it to act like an operator. For example, writing sin = sin + 1; when you intend to compute the sine of something. This actually assigns a new value to a variable named sin. Always check that you have sin(x) instead of just sin in computations.

Another issue is confusing degrees and radians in trigonometric functions. MATLAB trigonometric functions interpret angles in radians. If you want to work in degrees, use functions with a d in the name, such as sind, cosd, and tand, or convert degrees to radians using the factor $\pi / 180$ with the constant pi.

A further source of confusion is assuming that every name in MATLAB is a function. Some names are constants like pi, Inf, and NaN, and you do not use parentheses with them. If you try to call pi() as a function, MATLAB will give an error, because pi is a value, not a function.

When working with functions that accept arrays, it is also important to remember the difference between operators and functions. For example, .^ is an elementwise power operator, while the power function can sometimes be used for clarity or specific purposes. If a function seems to give an error or unexpected result with arrays, check the documentation to see how it handles array inputs and whether it operates elementwise or in some other way.

Important points to remember:

  1. Built in constants like pi, Inf, NaN, eps, and 1i are always available, but you can accidentally overwrite their names with variables. Use clear to restore access if needed.
  2. Function and variable names share the same namespace. Avoid naming variables after common built in functions such as sum, mean, max, or sin, or you will shadow those functions.
  3. Every function call must use parentheses, even if there are no inputs. Expressions go inside the parentheses, for example sqrt(9) or sin(2*pi/3).
  4. Trigonometric functions like sin, cos, and tan use radians. Use sind, cosd, and tand for degrees, or convert degrees to radians with pi/180.
  5. Use help, doc, and which to learn what a function does, check its syntax, and see whether a name refers to a function or a variable in your current workspace.

Views: 6

Comments

Please login to add a comment.

Don't have an account? Register now!