Lesson 02: Built-In MATLAB Functions
Objective
- To use a variety of common mathematical functions.
- To understand and use trigonometric function in MATLAB.
- Recognize and be able to use the special values and functions built into MATLAB.
Background
MATLAB includes many built-in functions for math operations. Here are a number of the most important ones. A big advantage of MATLAB is that function arguments can generally be either scalars or arrays.
Elementary Math Functions
Elementary math functions include logarithms, exponentials, absolute value, rounding functions, and functions used in discrete mathematics.
2.1 Common Computations
A few of the most common and useful MATLAB functions are shown in the following table. The functions listed in the following table accept either a scalar or a matrix of x values.
functions | Description | MATLAB Example |
---|---|---|
abs (x) | Finds the absolute value of x. | >> abs (-3) ans = 3 |
sqrt (x) | Finds the square root of x. | >> sqrt (85) >>ans = 9.2195 |
nthroot (x,n) | Finds the real nth root of x. This function will not return complex results. | >> nthroot(-2,3) ans = -1.2599 |
sign (x) | Returns a value:
|
>> sign (-8) ans = -1 |
rem (x, y) | Computes the remainder of x / y. | >> rem (25, 4) ans = 1 |
mod (x, y) | Remainder or modulo function. | >> mod (-10, 3) and = 2 |
exp (x) | Computes the value of ex, where e is the base for natural logarithms, or approximately 2.7183. | >> exp (10) ans = 2.2026e+04 |
log (x) | Computes ln(x), the natural logarithm of x (to the base e). | >> log (10) ans = 2.3026 |
log2 (x) | Computes log2 (x), the common logarithm of x (to the base 2). | |
log10 (x) | Computes log10 (x), the common logarithm of x (to the base 10). | >> log10(10) ans = 1 |
Practice Exercise 2.1
Use MATLAB functions or commands to solve the questions.
- Create a vector x from -9 to 12 with an increment of 3.
- Find the absolute value of each member of the vector.
- Find the square root of each member of the vector.
- Using the vector from Exercise 1, find ex.
- Using the vector from Exercise 1:
- Find ln(x) (the natural logarithm of x).
- FIng log10(x) *the common logarithm of x). Explain your result.
- Find the square root of both -3 and +3.
- Use the sqrt function.
- Use the nthroot function. (You should get an error statement for -3).
- Raise -3 and +3 to ½ power. (Use ^ operator).
2.2 Trigonometric Functions
MATLAB includes a complete set of the standard trigonometric functions in radians or degree, the hyperbolic trigonometric functions in radians, and inverse variants of each functions.You can use the rad2deg and deg2rad function to convert between radian and degree, or function like cart2pol convert between coordinate systems.
Sine
The Sine functions operate element-wise on arrays, and accept both real and complex inputs.
- For real values of X, sin(X) returns real values in the interval [-1, 1].
- For complex values of X, sin(X) returns complex values.
sin (x) | Finds the sine of x when x is expressed in radians. |
sind (x) | Finds the sine of x when x is express in degree. |
sinpi (x) | Computes sin (x * pi) accurately without explicitly computing x * pi. |
asin (x) | Finds the arcsine (sin -1 x), or inverse sine in radians, of x, where x must be between -1 and 1. |
asind (x) | Finds the arcsine (sin -1 x), or inverse sine in degrees, of x, where x must be between -1 and 1. |
sinh (x) | Finds the hyperbolic sine of x when x is expressed in radians. |
asinh (x) | Finds the inverse hyperbolic sine of x. |
Cosine
cos (x) | Finds the cosine of x when x is expressed in radians. |
cosd (x) | Finds the cosine of x when x is express in degree. |
cospi (x) | Computes cos (x * pi) accurately. |
acos (x) | Finds the arccosine (cos -1 x), or inverse cosine in radians, of x, where x must be between -1 and 1. |
acosd (x) | Finds the arccosine (cos -1 x), or inverse cosine in degrees, of x, where x must be between -1 and 1. |
cosh (x) | Finds the hyperbolic cosine of x when x is expressed in radians. |
acosh (x) | Finds the inverse hyperbolic cosine of x. |
Tangent
tan (x) | Finds the tangent of x when x is expressed in radians. |
tand (x) | Finds the tangent of x when x is express in degree. |
atan (x) | Finds the arctangent (tan -1 x), or inverse sine in radians. |
atand (x) | Finds the arctangent (tan -1 x), or inverse sine in degrees. |
atan2 (x,y) | Four-quadrant inverse tangent. |
ayan2d (x,y) | Four-quadrant inverse tangent in degrees. |
tanh (x) | Finds the hyperbolic tangent of x when x is expressed in radians. |
atanh (x) | Finds the inverse hyperbolic tangent of x. |
Cosecant
csc (x) | Finds the cosecant of x when x is expressed in radians. |
cscd (x) | Finds the cosecant of x when x is express in degree. |
acsc (x) | Finds the arccosecant (csc -1 x), or inverse cosine in radians. |
acscd (x) | Finds the arccosecant (cos -1 x), or inverse cosine in degrees. |
csch (x) | Finds the hyperbolic cosecant of x. |
acsch (x) | Finds the inverse hyperbolic cosecant of x. |
Secant
sec (x) | Finds the secant of x when x is expressed in radians. |
secd (x) | Finds the secant of x when x is express in degree. |
asec (x) | Finds the arcsecant (csc -1 x), or inverse cosine in radians. |
asecd (x) | Finds the arcsecant (cos -1 x), or inverse cosine in degrees. |
sech (x) | Finds the hyperbolic secant of x. |
asech (x) | Finds the inverse hyperbolic secant of x. |
Cotangent
cot (x) | Finds the cotangent of x when x is expressed in radians. |
cotd (x) | Finds the costangant of x when x is express in degree. |
acot (x) | Finds the arccotangant (csc -1 x), or inverse cosine in radians. |
acotd (x) | Finds the arccotangant (cos -1 x), or inverse cosine in degrees. |
coth (x) | Finds the hyperbolic cotangant of x. |
acoth (x) | Finds the inverse hyperbolic cotangant of x. |
Hypotenuse
hypot (x) | Square root of sum of squares (hypotenuse) |
Conversions
Degrees/Radians Conversion
deg2rad(deg) | Convert angle from degrees to radians | >> R = deg2rad(90) R = 1.5708 |
rad2deg(rad) | Convert angle from radians to degrees | >> D = rad2deg(pi) D = 180 |
Coordinate Conversion
[theta,rho] = cart2pol(x,y) [theta,rho,z] = cart2pol(x,y,z) |
Transform Cartesian coordinates to polar or cylindrical | x, y, z — Cartesian coordinates theta — Angular coordinate rho — Radial coordinate z — Elevation coordinate |
[azimuth,elevation,r] = cart2sph(x,y,z) | Transform Cartesian coordinates to spherical | x,y,z — Cartesian coordinates azimuth — Azimuth angle elevation — Elevation angle r — Radius |
[x,y] = pol2cart(theta,rho) [x,y,z] = pol2cart(theta,rho,z) |
Transform polar or cylindrical coordinates to Cartesian | theta — Angular coordinate rho — Radial coordinate z — Elevation coordinate x, y, z — Cartesian coordinates |
[x,y,z] = sph2cart(azimuth,elevation,r) | Transform spherical coordinates to Cartesian | azimuth — Azimuth angle elevation — Elevation angle r — Radius x,y,z — Cartesian coordinates |
In the mathematical texts, the notation sin-1(x) is usually used to represent an inverse sine function, also called an arcsine. Do not confuse this notation and try to create parallel MATLAB code. Note, however, that
a = sin^-1(x)
is not a valid MATLAB statement. The result stated below are also incorrect
a = sin(x) ^ -1
. It should be
a = asin(x)
Practice Exercise 2.2
Use MATLAB functions or commands to solve the questions.
- Compare the accuracy of sinpi(x) vs. sin(x * pi).
- Finds the sine value of \(2\pi \) using sin function.
- Finds the sine value of \(2\pi \) using sinpi function.
- Does a and b get same result? Which sine function is more accurate? Why?
- Verify the sin2(Θ)+cos2(Θ) = 1.
- Create an vector named theta of evenly spaced values from 0 to \(\pi \) with increment of \(\frac{\pi }{{10}}\).
- Show the results of the following command:
[theta' sin(theta)' cos(theta)' (sin(theta).^2+cos(theta).^2)'] - Doe sin2(Θ)+cos2(Θ) equal to 1?
2.3 Data Analysis Functions
Maximum and Minimum
Maximum and Minimum
[value, index] = max (x) | Returns the maximum value in array x, and optionally the location of the value. | |
[value, index] = min (x) | Returns the minimum value in array x and optionally the location of the value. |
M = max(A) returns the maximum elements of an array.
- If A is a vector, then max(A) returns the maximum of A.
- If A is a matrix, then max(A) is a row vector containing the maximum value of each column.
- If A is a multidimensional array, then max(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors. The size of this dimension becomes 1 while the sizes of all other dimensions remain the same.
- If A is an empty array whose first dimension has zero length, then max(A) returns an empty array with the same size as A.
Largest Vector Element
Create a vector and compute its largest element
>> A = [18 52 33 24 23];
>> M = max(A)
M = 52
Largest Complex Element
Create a complex vector and compute its largest element, that is, the element with the largest magnitude.
>> A = [2+2i 6-i -1+3i]
>> max(A)
ans = 6.0000 - 1.0000i
Largest Element in Each Matrix Column
Create a matrix and compute the largest element in each column.
>> A = [6 4 8; 2 9 7];
>> M = max(A)
M = 6 9 8
M = max(A,[],dim) returns the maximum element along dimension dim. For example, if A is a matrix, then max(A,[],2) is a column vector containing the maximum value of each row.
Largest Element in Each Matrix Row
>> A = [1.1 1.8 1.5; 1.2 1.6 0.8];
>> M = max(A,[],2)
M =
1.8000
1.6000
M = max(A,[],nanflag) specifies whether to include or omit NaN values in the calculation. For example, max(A,[],'includenan') includes all NaN values in A while max(A,[],'omitnan') ignores them.
M = max(A,[],dim,nanflag) also specifies the dimension to operate along when using the nanflag option.
Largest Element Involving NaN
- Create a vector and compute its maximum, excluding NaN values.
>> A = [1.77 -0.25 3.68 -2.50 NaN 0.68 NaN 0.19];
>> M = max(A,[],'omitnan')
M = 3.6800 - Use the 'includenan' flag to return NaN.
>> M=max(A,[],'includenan')
M = NaN
[M,I] = max(__) also returns the index into the operating dimension that corresponds to the maximum value of A for any of the previous syntaxes.
Largest Element Indices
Create a matrix A and compute the largest elements in each column, as well as the row indices of A in which they appear.
>> A = [2 9 -6; 8 5 -7];
>> [MaxNum,RowIdx] = max(A)
MaxNum = 8 9 -6
RowIdx = 2 1 1
The following command to find the largest element in each row, as well as the column indices of A in which they appear.
>> A = [2 9 -6; 8 5 -7];
>> [MaxNum,ColIdx] = max(A,[],2)
MaxNum =
9
8
ColIdx =
2
1
M = max(A,[],vecdim) computes the maximum over the dimensions specified in the vector vecdim. For example, if A is a matrix, then max(A,[],[1 2]) computes the maximum over all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2.
M = max(A,[],'all') finds the maximum over all elements of A. This syntax is valid for MATLAB versions R2018b and later.
Maximum of Array page
Create a 3-D array and compute the maximum over each page of data (rows and columns).
>> A(:,:,1) = [3 6 ; -4 1];
>> A(:,:,2) = [8 14; -5 3];
>> A(:,:,3) = [5 5 ; 9 2];
>> M1 = max(A,[],[1,2])
M1(:,:,1) = 6
M1(:,:,2) = 14
M1(:,:,3) = 9
Starting in R2018b, to compute the maximum over all dimensions of an array, you can either specify each dimension in the vector dimension argument, or use the 'all' option.
>> M2=max(A,[],[1,2,4])
M2(:,:,1) = 6
M2(:,:,2) = 14
M2(:,:,3) = 9
>> Mall=max(A,[],'all')
Mall = 14
C = max(A,B) returns an array with the largest elements taken from A or B.
C = max(A,B,nanflag) also specifies how to treat NaN values.
Largest Element Comparison
Create a matrix and return the largest value between each of its elements compared to a scalar.
>> A = [2 8 4 ; 6 5 9];
>> B = 5;
>> max(A,B)
ans =
5 8 5
6 5 9
Mean and Median
Mean and Median
mean (x) | Computes the average value of array. |
median (x) | Computes median value of array |
mode (x) | Finds the value that occurs most often in an array |
M = mean(A) returns the mean of the elements of A along the first array dimension whose size does not equal 1.
- If A is a vector, then mean(A) returns the mean of the elements.
- If A is a matrix, then mean(A) returns a row vector containing the mean of each column.
- If A is a multidimensional array, then mean(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors. This dimension becomes 1 while the sizes of all other dimensions remain the same.
Mean of Matrix Columns
Create a matrix and compute the mean of each column.
>> A = [0 1 1; 2 3 2; 1 3 2; 4 2 2];
>> mean(A)
ans = 1.7500 2.2500 1.7500
M = mean(A,dim) returns the mean along dimension dim. For example, if A is a matrix, then mean(A,2) is a column vector containing the mean of each row.
Mean of Matrix Rows
Create a matrix and compute the mean of each row.
>> A = [0 1 1; 2 3 2];
>> mean(A,2)
ans =
0.6667
2.3333
Mean of 3-D Array
Create a 4-by-2-by-3 array of integers between 1 and 10 and compute the mean values along the second dimension.
>> A = gallery('integerdata',10,[4,2,3],1);
>> M = mean(A,2)
M =
M(:,:,1) =
9.5000
6.5000
9.5000
6.0000
M(:,:,2) =
1.5000
4.0000
7.5000
7.5000
M(:,:,3) =
7.0000
2.5000
4.0000
5.5000
M = mean(A,vecdim) computes the mean based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then mean(A,[1 2]) is the mean of all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2.
M = mean(A,'all') computes the mean over all elements of A. This syntax is valid for MATLAB versions R2018b and later.
Mean of Array Page
Create a 3-D array and compute the mean over each page of data (rows and columns).
>> A(:,:,1) = [2 4; -2 1];
>> A(:,:,2) = [9 13; -5 7];
>> A(:,:,3) = [4 4; 8 -3];
>> M1 = mean(A,[1 2])
M1 =
M1(:,:,1) = 1.2500
M1(:,:,2) = 6
M1(:,:,3) = 3.2500
Starting in R2018b, to compute the mean over all dimensions of an array, you can either specify each dimension in the vector dimension argument, or use the 'all' option.
>> M2 = mean(A,[1 2 3])
M2 = 3.5000
>> Mall = mean(A,'all')
Mall = 3.5000
M = mean(___,outtype) returns the mean with a specified data type, using any of the input arguments in the previous syntaxes. outtype can be 'default', 'double', or 'native'.
Mean of Single-Precision Array
Create a single-precision vector of ones and compute its single-precision mean.
>> A = single(ones(10,1));
>> M = mean(A,'native')
M = 1
The result is also in single precision.
>> class(M)
ans = 'single'
M = mean(___,nanflag) specifies whether to include or omit NaN values from the calculation for any of the previous syntaxes. mean(A,'includenan') includes all NaN values in the calculation while mean(A,'omitnan') ignores them.
Mean Excluding NaN
Create a vector and compute its mean, excluding NaN values.
>> A = [1 0 0 1 NaN 1 NaN 0];
>> M = mean(A,'omitnan')
M = 0.5000
If you do not specify 'omitnan', then mean(A) returns NaN.
M = median(A) returns the median value of A.
- If A is a vector, then median(A) returns the median value of A.
- If A is a nonempty matrix, then median(A) treats the columns of A as vectors and returns a row vector of median values.
- If A is an empty 0-by-0 matrix, median(A) returns NaN.
- If A is a multidimensional array, then median(A) treats the values along the first array dimension whose size does not equal 1 as vectors. The size of this dimension becomes 1 while the sizes of all other dimensions remain the same.
median computes natively in the numeric class of A, such that class(M) = class(A).
Median of Matrix Columns
Define a 4-by-3 matrix.
>> A = [0 1 1; 2 3 2; 1 3 2; 4 2 2];
Find the median value of each column.
>> median(A)
ans =
1.5000 2.5000 2.0000
For each column, the median value is the mean of the middle two numbers in sorted order.
Median of 3-D Array
Create a 1-by-3-by-4 array of integers between 1 and 10.
>> A = gallery('integerdata',10,[1,3,4],1)
A =
A(:,:,1) = 10 8 10
A(:,:,2) = 6 9 5
A(:,:,3) = 9 6 1
A(:,:,4) = 4 9 5
Find the median values of this 3-D array along the second dimension.
>> M = median(A)
M =
M(:,:,1) = 10
M(:,:,2) = 6
M(:,:,3) = 6
M(:,:,4) = 5
This operation produces a 1-by-1-by-4 array by computing the median of the three values along the second dimension. The size of the second dimension is reduced to 1.
Compute the median along the first dimension of A.
>> M = median(A,1);
>> isequal(A,M)
ans = 1
This command returns the same array as A because the size of the first dimension is 1.
M = median(A,dim) returns the median of elements along dimension dim. For example, if A is a matrix, then median(A,2) is a column vector containing the median value of each row.
Median of Matrix Rows
Define a 2-by-3 matrix.
>> A = [0 1 1; 2 3 2];
Find the median value of each row.
>> M = median(A,2)
ans =
1
2
For each row, the median value is the middle number in sorted order.
M = median(A,vecdim) computes the median based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then median(A,[1 2]) is the median over all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2.
M = median(A,'all') computes the median over all elements of A. This syntax is valid for MATLAB versions R2018b and later.
Median of Array Page
Create a 3-D array and compute the median over each page of data (rows and columns).
>> A(:,:,1) = [2 4; -2 1];
>> A(:,:,2) = [6 2; -5 3];
>> A(:,:,3) = [4 4; 7 -3];
>> M1 = median(A,[1 2])
M1 =
M1(:,:,1) = 1.5000
M1(:,:,2) = 2.5000
M1(:,:,3) = 4
Starting in R2018b, to compute the median over all dimensions of an array, you can either specify each dimension in the vector dimension argument, or use the 'all' option.
>> M2 = median(A,[1 2 3])
M2 = 2.5000
>> Mall = median(A,'all')
Mall = 2.5000
M = median(___,nanflag) optionally specifies whether to include or omit NaN values in the median calculation for any of the previous syntaxes. For example, median(A,'omitnan') ignores all NaN values in A.
Median Excluding NaN
Create a vector and compute its median, excluding NaN values.
>> A = [1.77 -0.005 3.98 -2.95 NaN 0.34 NaN 0.19];
>> M = median(A,'omitnan')
M = 0.2650
Median of 8-Bit Integer Array
Define a 1-by-4 vector of 8-bit integers.
>> A = int8(1:4)
A = 1 2 3 4
Compute the median value.
>> M = median(A)
M = 3
>> class(M)
ans = 'int8'
M is the mean of the middle two numbers in sorted order returned as an 8-bit integer.
M = mode(A) returns the sample mode of A, which is the most frequently occurring value in A. When there are multiple values occurring equally frequently, mode returns the smallest of those values. For complex inputs, the smallest value is the first value in a sorted list.
- If A is a vector, then mode(A) returns the most frequent value of A.
- If A is a nonempty matrix, then mode(A) returns a row vector containing the mode of each column of A.
- If A is an empty 0-by-0 matrix, mode(A) returns NaN.
- If A is a multidimensional array, then mode(A) treats the values along the first array dimension whose size does not equal 1 as vectors and returns an array of most frequent values. The size of this dimension becomes 1 while the sizes of all other dimensions remain the same.
Mode of Matrix Columns
Define a 3-by-4 matrix.
>> A = [3 3 1 4; 0 0 1 1; 0 1 2 4];
Find the most frequent value of each column.
>> M = mode(A)
M = 0 0 1 4
Mode of Matrix Rows
Define a 3-by-4 matrix.
>> A = [3 3 1 4; 0 0 1 1; 0 1 2 4];
Find the most frequent value of each row.
>> M = mode(A,2)
M =
3
0
0
Mode of 3-D Array
Create a 1-by-3-by-4 array of integers between 1 and 10.
>> A = gallery('integerdata',10,[1,3,4],1)
A =
A(:,:,1) = 10 8 10
A(:,:,2) = 6 9 5
A(:,:,3) = 9 6 1
A(:,:,4) = 4 9 5
Find the most frequent values of this 3-D array along the second dimension.
>> M = mode(A)
M =
M(:,:,1) = 10
M(:,:,2) = 5
M(:,:,3) = 1
M(:,:,4) = 4
This operation produces a 1-by-1-by-4 array by finding the most frequent value along the second dimension. The size of the second dimension reduces to 1.
Compute the mode along the first dimension of A.
>> M = mode(A,1);
>> isequal(A,M)
ans = 1
This returns the same array as A because the size of the first dimension is 1.
M = mode(A,dim) returns the mode of elements along dimension dim. For example, if A is a matrix, then mode(A,2) is a column vector containing the most frequent value of each row
M = mode(A,'all') computes the mode over all elements of A. This syntax is valid for MATLAB versions R2018b and later.
Mode of Matrix Columns with Frequency Information
Create a 1-by-3-by-4 array of integers between 1 and 10.
>> A = gallery('integerdata',10,[1,3,4],1)
A =
A(:,:,1) = 10 8 10
A(:,:,2) = 6 9 5
A(:,:,3) = 9 6 1
A(:,:,4) = 4 9 5
Find the most frequent values of this 3-D array along the second dimension.
>> M = mode(A)
M =
M(:,:,1) = 10
M(:,:,2) = 5
M(:,:,3) = 1
M(:,:,4) = 4
This operation produces a 1-by-1-by-4 array by finding the most frequent value along the second dimension. The size of the second dimension reduces to 1.
Compute the mode along the first dimension of A.
>> M = mode(A,1);
>> isequal(A,M)
ans = 1
This returns the same array as A because the size of the first dimension is 1.
Mode of Matrix Columns with Frequency Information
Define a 3-by-4 matrix.
>> A = [3 3 1 4; 0 0 1 1; 0 1 2 4];
Find the most frequent value of each column, as well as how often it occurs.
>> [M,F] = mode(A)
M = 0 0 1 4
F = 2 1 2 2
F(1) is 2 since M(1) occurs twice in the first column.
[M,F] = mode(__) also returns a frequency array F, using any of the input arguments in the previous syntaxes. F is the same size as M, and each element of F represents the number of occurrences of the corresponding element of M.
[M,F,C] = mode(__) also returns a cell array C of the same size as M and F. Each element of C is a sorted vector of all values that have the same frequency as the corresponding element of M.
Mode of Matrix Rows with Frequency and Multiplicity Information
Define a 3-by-4 matrix.
>> A = [3 3 1 4; 0 0 1 1; 0 1 2 4];
Find the most frequent value of each row, how often it occurs, and which values in that row occur with the same frequency.
>> [M,F,C] = mode(A,2)
M =
3
0
0
F =
2
2
1
C =
{[ 3]}
{2x1 double}
{4x1 double}
C{2} is the 2-by-1 vector [0;1] since values 0 and 1 in the second row occur with frequency F(2).
C{3} is the 4-by-1 vector [0;1;2;4] since all values in the third row occur with frequency F(3).
Mode of 16-bit Unsigned Integer Array
Define a 1-by-4 vector of 16-bit unsigned integers.
>> A = gallery('integerdata',10,[1,4],3,'uint16')
A = 6 3 2 3
Find the most frequent value, as well as the number of times it occurs.
>> [M,F] = mode(A)
M = 3
F = 2
>> class(M)
ans = 'uint16'
M is the same class as the input, A.
Sums and Products
Sums and Products
sum (x) | Sums the element in vector |
prod (x) | Computes the product of element of a vector |
cumsum (x) | Computes a vector of the same size as, and containing cumulative sums of the elements of a vector |
cumprod (x) | Computes a vector of the same size as, and containing cumulative products of the elements of a vector |
S = sum(A) returns the sum of the elements of A along the first array dimension whose size does not equal 1.
- If A is a vector, then sum(A) returns the sum of the elements.
- If A is a matrix, then sum(A) returns a row vector containing the sum of each column.
- If A is a multidimensional array, then sum(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors. This dimension becomes 1 while the sizes of all other dimensions remain the same.
Sum of Vector Elements
Create a vector and compute the sum of its elements.
>> A = 1:10;
>> sum(A)
ans = 55
Sum of Matrix Columns
Create a matrix and compute the sum of the elements in each column.
>> A = [1 3 2; 4 2 5; 6 1 4];
>> sum(A)
ans = 11 6 11
S = sum(A,dim) returns the sum along dimension dim. For example, if A is a matrix, then sum(A,2) is a column vector containing the sum of each row.
Sum of Array Slices
Use a vector dimension argument to operate on specific slices of an array.
Create a 3-D array whose elements are 1.
>> A = ones(4,3,2);
To sum all elements in each page of A, specify the dimensions in which to sum (row and column) using a vector dimension argument. Since both pages are a 4-by-3 matrix of ones, the sum of each page is 12.
>> S1 = sum(A,[1 2])
S1 =
S1(:,:,1) = 12
S1(:,:,2) = 12
If you slice A along the first dimension, you can sum the elements of the resulting 4 pages, which are each 3-by-2 matrices.
>> S2 = sum(A,[2 3])
S2 =
6
6
6
6
Slicing along the second dimension, each page sum is over a 4-by-2 matrix.
>> S3 = sum(A,[1 3])
S3 = 8 8 8
Starting in R2018b, to sum over all dimensions of an array, you can either specify each dimension in the vector dimension argument, or use the 'all' option.
>> S4 = sum(A,[1 2 3])
S4 = 24
>> Sall = sum(A,'all')
Sall = 24
B = prod(A) returns the product of the array elements of A.
- If A is a vector, then prod(A) returns the product of the elements.
- If A is a nonempty matrix, then prod(A) treats the columns of A as vectors and returns a row vector of the products of each column.
- If A is an empty 0-by-0 matrix, prod(A) returns 1.
- If A is a multidimensional array, then prod(A) acts along the first nonsingleton dimension and returns an array of products. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same.
prod computes and returns B as single when the input, A, is single. For all other numeric and logical data types, prod computes and returns B as double.
Product of Elements in Each Column
Create a 3-by-3 array whose elements correspond to their linear indices.
>> A=[1:3:7;2:3:8;3:3:9];
Find the product of the elements in each column. The length of the first dimension is 1, and the length of the second dimension matches size(A,2).
>> B = prod(A)
B = 6 120 504
B = prod(A,dim) returns the products along dimension dim. For example, if A is a matrix, prod(A,2) is a column vector containing the products of each row.
Product of Elements in Each Row
Create a 3-by-3 array whose elements correspond to their linear indices.
>> A=[1:3:7;2:3:8;3:3:9];
Find the product of the elements in each row and reduce the length of the second dimension to 1. The length of the first dimension matches size(A,1), and the length of the second dimension is 1.
>> dim = 2;
>> B = prod(A,dim)
B =
28
80
162
B = prod(A,vecdim) computes the product based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then prod(A,[1 2]) is the product of all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2.
Product of Array Page
Create a 3-D array and compute the product over each page of data (rows and columns).
>> A(:,:,1) = [2 4; -2 1];
>> A(:,:,2) = [1 2; -5 3];
>> A(:,:,3) = [4 4; 1 -3];
>> B1 = prod(A,[1 2])
B1 =
B1(:,:,1) = -16
B1(:,:,2) = -30
B1(:,:,3) = -48
To compute the product over all dimensions of an array, you can either specify each dimension in the vector dimension argument, or use the 'all' option.
>> B2 = prod(A,[1 2 3])
B2 = -23040
>> Ball = prod(A,'all')
Ball = -23040
B = cumsum(A) returns the cumulative sum of A starting at the beginning of the first array dimension in A whose size does not equal 1.
- If A is a vector, then cumsum(A) returns a vector containing the cumulative sum of the elements of A.
- If A is a matrix, then cumsum(A) returns a matrix containing the cumulative sums for each column of A.
- If A is a multidimensional array, then cumsum(A) acts along the first nonsingleton dimension.
Sorting Values
Sorting Values
sort (x) sort (x,'descend') |
Sorts the elements in each column into ascending/descending order. | >> x = [1, 5, 3]; >> sort (x) ans 1 3 5 >> sort (x, 'descend') ans = 5 3 1 >> y = [1, 5, 3; 2, 4, 6]; >> sort (x) ans = 1 4 3 2 5 6 |
sortrows (x) | Sorts the rows in a matrix in ascending order on the basis of the values in the first column, and keeps each row intact. |
>> z = [3, 1 ,2; 1, 9, 3; 4, 3, 6]; >> sortrows (z) ans = 1 9 3 3 1 2 4 3 6 |
sortrows (x,n) | Sorts the rows in a matrix on the basis of the values in column n | >> sortrows (z, 2) ans = 3 1 2 4 3 6 1 9 3 |
Determining Matrix Size
Determining Matrix Size
size (x) | Determines the number of rows and columns in matrix x | >> x = [1, 5, 3; 2, 4, 6]; >> size (x) ans = 2 3 |
[r,c] = size (x) | Determines the number of rows and columns in matrix x, and assign the number of rows to r and the number of columns to c |
>> [r,c] = size(x) r = 2 c = 3 |
length (x) | Determines the largest dimension of a matrix x | >> length (x) ans = 3 |
numel (x) | Determines the total number of elements in a matrix x | >> numel (x) ans = 6 |
Variance and Standard Deviation
Variance and Standard Deviation
std (x) | Computes the standard deviation of the value in a array x | >> x = [1, 5, 3; 2, 4, 6]; >> std (x) ans = 0.7071 0.7071 2.1213 |
var (x) | Calculate the variance of the data in x | >> x = [1 5 3]; >> var (x) ans = 4 |
Practice Exercise 2.3
Use MATLAB functions or commands to solve the questions.
- Consider the following matrix:
\(x = \left[ {\begin{array}{ccccccccccccccc} 4&{90}&{85}&{75}\\ 2&{55}&{65}&{75}\\ 3&{78}&{82}&{79}\\ 1&{84}&{92}&{93} \end{array}} \right]\)- What is the maximum value in each column?
- In which row does that maximum occur?
- What is the maximum value in each row? (You'll have to transpose the matrix to answer this question.)
- In which column does the maximum occur?
- What is the maximum value in the entire table?
- Using the matrix from Exercise 1, find:
- Use the size function to determine the number of rows and columns in this matrix.
- Use the sort function to sort each column in ascending order.
- Use the sort function to sort each column in descending order.
- Use the sortrows function to sort the matrix so that the first column is in ascending order, but each row still retains its original data. Your matrix should look like this:
\(x = \left[ {\begin{array}{ccccccccccccccc} 1&{84}&{92}&{93}\\ 2&{55}&{65}&{75}\\ 3&{78}&{82}&{79}\\ 4&{90}&{85}&{75} \end{array}} \right]\)
- Using the matrix from Exercise 1, find
- Find the standard deviation for each column.
- Find the variance for each column.
- Calculate the square root of the variance you found for each column.
2.4 Random Numbers
Random numbers are often used in engineering calculations to simulate measured data. Two different types of random numbers can be generated in MATLAB:
- Uniform random numbers
- Gaussian random numbers (often called a normal distribution).
Uniform Random Numbers
Uniform random numbers are generated with the rand function. These numbers are evenly distributed between 0 and 1.
rand (n) | Returns an n x n matrix. Each value in the matrix is a random number between 0 and 1. |
>> rand (2) ans = 0.9501 0.6068 0.2311 0.4860 |
rand (m,n) | Returns an m x n matrix. Each value in the matrix is a random number between 0 and 1. |
>> rand (3,2) ans = 0.8913 0.0185 0.7632 0.8851 0.4255 0.4447 |
Gaussian Random Numbers
randn (n) | Returns an n x n matrix. Each value in the matrix is a Gaussian (or normal) random number with a mean of 0 and a variance of 1. |
>> randn(2) ans = 0.4326 0.1253 1.6656 0.2877 |
randn (m,n) | Returns an m x n matrix. Each value in the matrix is a Gaussian (or normal) random number with a mean of 0 and a variance of 1. |
>> randn(3,2) ans = 1.1465 0.0376 1.1909 0.3273 1.1892 0.1746 |
Practice Exercise 2.4
Use MATLAB functions or commands to solve the questions.
- Create a 3 x 3 matrix of evenly distributed random numbers.
- Find the maximum, the standard deviation, the variance, and the mean for each column in the matrix that you created in Exercise 1
- Create a 3 x 3 matrix of normally distributed random numbers.
- Find the maximum, the standard deviation, the variance, and the mean for each column in the matrix you created in Exercise 3.
2.5 Complex Numbers
MATLAB includes several functions used primarily with complex numbers. Complex numbers consist of two parts: a real and an imaginary component.
abs (x) | Computes the absolute value of a complex number, using the Pythagorean theorem. | >> x = 3+4i; >> abs(x) ans = 5 |
angle (x) | Computes the angle from the horizontal in radians when a complex number is represented in polar coordinates. | >> x = 3 + 4i; >> angle (x) ans = 0.9273 |
complex(x,y) | Generates a complex number with a real component x and an imaginary component y. | >> a = 3; b = 4; >> complex (a,b) ans = 3.000 + 4.000i |
real (x) | Extracts the real component from a complex number. | >> x = 3 + 4i; >> real (x) ans = 3 |
imag (x) | Extracts the imaginary component from a complex number. | >> x = 3 + 4i; >> imag (x) ans = 4 |
isreal (x) | Determines whether the values in an array are real.
|
>> x = 3 + 4i; >> isreal (x) ans = 0 |
conj (x) | Generates the complex conjugate of a complex number. | >> x = 3 + 4i; >> conj (x) ans = 3.000 - 4.000i |
Practice Exercise 2.5
Use MATLAB functions or commands to solve the questions.
- Create the following complex numbers:
A = 1 + i
B = 2 - 3i
C = 8 + 2i- Find the magnitude (absolute value) of each of the complex number you created.
- Find the angle from the horizontal of each of the complex numbers you created.
- Multiply A by its complex conjugate, and then take the square root of your answer. How does this value compare against the magnitude (absolute value) of A?
2.6 Computation Limitations
realmax | Returns the largest possible floating-point number used in MATLAB. |
realmin | Returns the smallest possible floating-point number used in MATLAB. |
intmax | Returns the largest possible integer number used in MATLAB. |
intmin | Returns the smallest possible integer number used in MATLAB. |
Questions
Use MATLAB functions or commands to solve the questions.
- Populations tend to expand exponentially, that is,
\(P = {P_0} \cdot {e^{r \cdot t}}\)
where
P = current population
P0 = original population
r = continuous growth rate expressed as a fraction
t = time.
If you originally have 100 rabbits that breed at a continuous growth rate of 90% ( r = 0.92) per year, find how many rabbits you will have at the end of 10 years. - You can use trigonometry to find the height of a building as shown in the following Figure.
Suppose you measure the angle between the line of sight and the horizontal line connecting the measuring point and the building. You can calculate the height of the building with the following formulas:
\(\begin{array}{l} \tan (\theta ) = \frac{h}{d}\\ h = d \cdot \tan (\theta ) \end{array}\)
Assume that the distance to the building along the ground is 120 m and the angle measured along the line of sight is 30° ± 3°. Find the maximum and minimum heights the building can be.