Elementary Mathematics#
We can use MATLAB to solve all kinds of problems in calculus, linear algebra, differential equations and beyond. Let’s take a look at some foundational mathematical concepts in MATLAB that are relavant in all branches of mathematics such as numbers, vectors, matrices and functions.
See also
Check out the MATLAB documentation on elementary mathematics.
Numbers#
We can use MATLAB to perform all the usual arithmetic operations:
Operation |
MATLAB Syntax |
---|---|
addition |
|
subtraction |
|
multiplication |
|
division |
|
exponentiation |
|
Let’s do an example from calculus. Recall the Taylor series of the exponential function is:
Let’s use the first 6 terms of the Taylor series to approximate the value:
1 - (1/2) + (1/2)^2/2 - (1/2)^3/(2*3) + (1/2)^4/(2*3*4) - (1/2)^5/(2*3*4*5)
ans = 0.6065
Note that we group operations together using parentheses ( ... )
in the computation above.
Constants \(\pi\) and \(e\)#
The constant \(\pi\) is entered as pi
:
pi
ans = 3.1416
The exponential function \(e^x\) is entered as exp
in MATLAB therefore \(e=e^1\) is exp(1)
:
exp(1)
ans = 2.7183
Format short
and long
#
We can specify numerical output as long
(with 15 decimal places) or short
(with 4 decimals). Let’s look at our approximation of \(e^{-1/2}\) again using format long
:
format long
1 - (1/2) + (1/2)^2/2 - (1/2)^3/(2*3) + (1/2)^4/(2*3*4) - (1/2)^5/(2*3*4*5)
ans = 0.606510416666667
Compare to the value computed by the function exp
:
exp(-1/2)
ans = 0.606530659712633
Variables#
Just like the familiar variables \(x\) and \(y\) in mathematics, we use variables in programming to easily manipulate values. The assignment operator =
assigns a value to a variable in MATLAB. For example, let’s compute the values \(y = 1 + x + x^2\) and \(y' = 1 + 2x\) for \(x = 2\):
x = 2
x = 2
y = 1 + x + x^2
y = 7
dy = 1 + 2*x
dy = 5
Note that the variables x
, y
and dy
now appear in the workspace window and are available for us to use to subsequent computations.
Mathematical Functions#
All the standard mathematical functions are available in MATLAB:
Function |
MATLAB Syntax |
---|---|
\(\sin(x)\) |
|
\(\cos(x)\) |
|
\(\tan(x)\) |
|
\(\arctan(x)\) |
|
\(e^x\) |
|
\(\ln(x)\) |
|
\(\log_{10}(x)\) |
|
\(\sqrt{x}\) |
|
Let’s compute some examples:
cos(pi/4)
ans = 0.7071
1/sqrt(2)
ans = 0.7071
log(2)
ans = 0.6931
atan(1)
ans = 0.7854
Note
Trigonometric functions are defined in terms of radians.
The MATLAB function
log
is the natural logarithm andlog10
is the logarithm with base 10.
Custom Functions#
Create custom functions using the @
operator. For example, let’s create the function:
f = @(x) 1/(1 + x^2);
Compute some values of \(f(x)\):
f(0)
ans = 1
f(1)
ans = 0.5000
f(2)
ans = 0.2000