Monday, February 2, 2015

MATLAB TuTer 3: Matrices, Vectors, and Arrays in MATLAB

Working with Matrices, Vectors, and Arrays using Matlab

* Some facts about MATLAB:

          MATLAB is originally designed to work with anything as a matrix; if it's one element then it's 1 by 1 matrix, if it's a vector of elements sorted vertically or horizontally then it's one dimensional matrix, and if it's an array of elements or data then it's a matrix of cells.     

Working with Vectors and matrices:  

Inputting and Extracting Components:

MATLAB was written originally to allow mathematicians, scientists, and engineers to handle the mechanics of linear algebra that is, vectors and matrices as effortlessly as possible. In this section we introduce these concepts.
In physics or mechanics we sometimes have to deal with some variables which have more than one value like velocity, acceleration, force, or to describe the position of some object you need to specify its direction in the three axis (X,Y,Z) or in other fields (i,j,k), so MATLAB also helps to use this variables which called vectors.    
Inputting elements:   

Basic Manual method:

A vector is an ordered list of numbers. You can enter a vector of any length in MATLAB by typing a list of numbers, separated by commas or spaces, inside square brackets. For example,
>> Z = [2,4,6,8]  Z = 2 4 6 8
>> Y=[4 -35 -281]  Y = 4 -35 -281
A matrix is a rectangular array of numbers. Row and column vectors, which we discussed above, are examples of matrices. Consider the 3 × 4 matrix can be entered in MATLAB with the command:
>> A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]
A=
1   2   3   4
5   6   7   8
9  10  11  12
>> a = [4 9 -3; 1.5 24 7;6 78 -3]
a =
4     9    -3
1.5   24    7
6     78   -3  

Note that the matrix elements in any row are separated by commas, and the rows are separated by semicolons. The elements in a row can also be separated by spaces. 

Colon method:

Suppose you want to create a vector of values running from 1 to 9. Here’s how to do it without typing each number:
>> X = 1:9 ; X = 1 2 3 4 5 6 7 8 9
The notation 1:9 is used to represent a vector of numbers running from 1 to 9 in increments of 1. The increment can be specified as the second of three arguments:
>> X = 0:2:10 ; X = 0 2 4 6 8 10
You can also use fractional or negative increments, for example, 0:0.1:1 or 100:-1:0.

Linspase and logspace functions:

The linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct control over the number of points.
The logspace function generates logarithmically spaced vectors. Especially useful for creating frequency vectors, it is a logarithmic equivalent of linspace and the ":" or colon operator.
y = linspace(a,b)
Generates a row vector y of 100 points linearly spaced between and including "a" and "b".
y = linspace(a,b,n)
Generates a row vector y of n points linearly spaced between and including "a" and "b". For n < 2, linspace returns b. for e.g. linspace(0,10,5) gives the vector 01st 2.52nd 53rd 7.54th 105th.
y = logspace(a,b)
Generates a row vector y of 50 logarithmically spaced points between decades 10^a and 10^b.
y= logspace(a,b,n)
Generates n points between decades 10^a and 10^b.
y = logspace(a,pi)
Generates the points between 10^a and pi, which is useful for digital signal processing where frequencies over this interval go around the unit circle.

Random elements generation method: 

        MATLAB has three functions to generate random elements, these functions are "rand", "randn", and "randperm", and these functions can be used for as below:
Function Command
Result
Rand
Generates one random number between (0 – 1)"by default".
rand(n)
Generate n x n matrix of Uniformly distributed random elements with values between (0 – 1)"by default".
randn(n)
Generate n x n matrix of normally distributed random elements with values between (-n – n)"by default".
K*rand(n)
Generate n x n matrix of random elements with values between (0 – K)"by default".
rand(n,m)
Generate n x m matrix of random elements with values between (0 – 1)"by default", if n=1 or m=1 it generate a vector.
K*rand(n,m)
Generate n x m matrix of random elements with values between (0 – K)"by default", if n=1 or m=1 it generate a vector.
randperm(n)
"Random permutation"
Generates a vector with n random elements their values between (1 – n).
randperm(n,m)
Generates a vector with m random elements their values between (1 – n), m n.
K* randperm(n)
Generates a vector with n random elements their values between (1 – (n*K)).
K* randperm(n,m)
Generates a vector with m random elements their values between (1 – (n*K)), m n.
      There is other MATLAB functions are used to generate matrices or vectors elements automatically, like:
Function
Result
ones(n,m)
Generates n x m matrix all it elements are equal to 1, if n =1 or m =1 will generate a vector.
zeros(n,m)
Generates n x m matrix all it elements are equal to 0, if n =1 or m =1 will generate a vector.
eye(n)
Returns n x n identity matrix with ones on the main diagonal and zeros elsewhere.
eye(n,m)
Returns n x m matrix with ones on the main diagonal and zeros elsewhere.
magic(n)
Returns n x n matrix constructed from the integers 1 through n^2 with equal row and column sums. The order n must be a scalar greater than or equal to 3.

 Hybrid elements:
MATLAB allows using any type of data in one vector or matrix and performing any calculation we need with these data, for example we can make a vector or matrix of data which contains ±decimal, ±double, ±complex, ±symbolic, and other number.
Examples:
>> syms a b c d X Y Z S
>> X = [ 15 2.6 -14 -3.4 pi sym(1/3) exp(3) log(5)]
>> Y = [ 13 2.8 a 122 ; -14 -3.4 pi 2i  ;sym(1/3) exp(3) log(5) 0.5]
>> Z = [a^2 3*b (-2*c)^2]
>> S = [2*a b^3 1/2*c]

Extracting elements:

The elements of the vector X can be extracted as X(1), X(2), etc. or you can also extract a subset of vector elements by X(i : j) to extract elements from the ith element to the jth element, For example,
>> X(3)  % get the 3rd element of X.
>> X([2 3 4]) % get the 2nd, 3rd, and the 4th elements of X.
>> X(2:5) % get the 2nd, 3rd, 4th, and the 5th elements of X.
The colon symbol ":" can be used as a single index to a matrix or a vector, try:
>> X (:)
In matrices we can use the colon symbol in much different syntax, some examples of this usage, if A is 5x5 matrix, then:
>> A(:,5) % returns the 5th column of A.
>> A(3,:) % returns the 3rd row of A.
>> A(3,5) % returns the element corresponding to the 3rd row and the 5th column.
>> A(:,[1:3]) % returns the 1st,2nd, and the 3rd column of A.
>> A([2:4],:) % returns the 2nd,3rd, and the 4th row of A.
>> A([2:4],[2,3] % returns the elements that corresponding to the rows 2,3,4 and the columns 2 and 3.
>> A(5,:)=[] % deletes the 5th row of A.
>> A(:,3)=0 % make all the 3rd column elements equal to 0.
>> A(2,:)=4:9 % change the 2nd row elements to 4,5,6,7,8,9.
>> A(n) % returns the n-indexed element.

Transpose elements:

To change the vector X from a row vector to a column vector, use the transpose function by put a prime (’) after X:
>> X’
ans =
0
2
4
6
8
10
Transpose function can be applied to a matrix too by changing rows to columns and columns to rows, for example:
X = [1 2 3; 4 5 6]
X' =
1 4
2 5
3 6

Joining elements together:

        You can join, merge, combine two or more vectors together in one big vector or add other elements to vectors by using the standard input method, as:
>> a = [1 2 3 4 5 6]
>> b = [9 8 7 11 12 10] 
>> c = [a b 15 a*2]
c = [1 2 3 4 5 6 9 8 7 11 12 10 15 2 4 6 8 10 12] 
c is become the new big victor which contains elements of "a" and elements of "b" and the element "15" and the elements of "a" multiplied by 2.
We can combine any number of vectors or matrices in one matrix using vertical concatenate function "vertcat (a,b,c)" or horizontal concatenate function "horzcat (a,b,c)", where a,b and c are vectors or matrices with the same number of columns, for example:
>> a = [0:5]
>> b = [-5:0]
>> c = [10:2:20]
>> d = vertcat (a,b,c)
d =  0   1   2   3   4   5
    -5  -4  -3  -2  -1   0
    10  12  14  16  18  20
>> e = [a ; b ; c] % do the same function of vertcat here
>> f = horzcat(a,b,c) % here will result a long row vector of a,b and c elements.

Sorting elements:

MATLAB has a good built-in function that can be used to sort any number of elements in ascending (default) or descending order, this function is "sort(X)" where X is a vector or matrix or array of data.
>> sort(x) % sorts elements in columns.
>> sort(x,2) % sorts in columns and rows.

Performing basic and advanced calculations:

Addition and subtraction:

To add or subtract two vectors or matrices, these two vectors should have the same size of elements, and the result vector vectors or matrix will have the same size too.
For example, if X and Y are vectors or matrices with the same size, then we can perform addition or subtraction easy by:
>> X + Y
>> X - Y 
If two matrices X and Y are the same size, their (element-by-element) sum is obtained by typing X+Y. You can also add a scalar (a single number) to a matrix; X+c adds c to each element in A. Likewise, X-Y represents the difference of X and Y, and X-c subtracts the number c from each element of X.
Note: you do not type a period for addition and subtraction.

Multiplication and Division:

You must type .* or ./ if you want to multiply or divide vectors or matrices element-by-element. For example, to multiply the elements of X by the corresponding elements of Y, type:
>> X.*Y
>> X./Y
The period "." or the element wise operator in this expression is very important; it says that the numbers in X should be squared individually, or element-by-element.
Matrices Multiplication is only possible if they are multiplicatively compatible (that is, if A is "n × m" and B is "m × l"), then their product A*B is "n × l". Recall that the element of A*B in the ith row and jth column is the sum of the products of the elements from the ith row of A times the elements from the jth column of B, that is:
You can multiply or divide all vector or matrix elements by a scalar or constant, e.g:
>> 5*X  or  X*5
>> 5./X  or  X/5
>> X*pi or pi*X
>> i*X or X*i
>> (2-3i)*X

Square root, Exponents, logarithms, Exponentials:

You can perform other mathematical operations on vectors. For example,
-         to square root a vector or a matrix  X element by element, e.g:
>> sqrt(X)
-         to apply the special square root function of matrices, use:
>> sqrtm(X) % results complex matrices.
-         to raise any number to a powers of vector or matrix, e.g:
>> 5.^X % powers 5 by X elements, element by element.
>> 5^X % the special matrices exponentials X must be a square matrix or just a scalar.
-         To raise a vector or matrix elements to any power:
>> X.^3 % powers elements of X element by element.
>> X^3 % use special matrices exponents function.
Typing Xˆ2 or X*X would tell MATLAB to use matrix multiplication to multiply X by itself and would produce an error message in case of matrices multiplication condition is not satisfied.
Most MATLAB operations are, by default, performed element-by-element. For example:
>> exp(X) % e to the power of each element of X.
>> expm(X) % special matrices exponential function.
To get the exponential of each number in X (the matrices special exponential function is expm). One of the strengths of MATLAB is its ability to efficiently perform operations on vectors and matrices.
Logarithm function also can be applied to a vector or matrix using:
>> log(X) % element by element logarithm.
>> logm(X) % special logarithm function of matrices.

Dot product and cross product of vectors or matrices:

You can perform the Dot product of two vectors "e.g. X and Y" by the type the function "dot (X,Y)", but these two vectors must be with the same size, and the result will be in one element or one number or a scalar that’s why it's called scalar product too. For e.g,
>> dot (X , Y)
Note"in vectors" dot(X,Y) = X * Y'
You can perform the Cross product of two vectors "e.g. X and Y" by the type the function "cross (X,Y)", but these two vectors must be same size and must have at least one dimension of length 3, this because MATLAB is always get vectors as matrices, so there is a cross product for only two vectors which has the size "3x1" or "1x3" , and the result will be a vector with the same size . For e.g, if X and Y are vectors with the same size"3x1", then we can perform cross product of them easy by:
>> cross (X , Y)
There is other built-in MATLAB functions can be used with vectors or matrices to perform some statistical or data analysis operations, for e.g. if X is a vector or a matrix of elements, so we can use:
Function
Result
length(X)
To get the number of elements in X "vector", or the length of X "matrix", in matrices returns the length of the longest dimension.
min(X)
In vectors it returns minimum value of X elements, in matrices gives the minimum value of each column elements and results a vector.
max(X)
In vectors it returns maximum value of X elements, in matrices gives the maximum value of each column elements and results a vector.
sum(X)
In vectors it returns the summation value of all X elements, in matrices returns the summation of each column elements and results a vector.
mean(X)
To get the mean or average value of X elements.
size(X)
To get the size of X (rows    columns)
median(X)
Returns the median value of X, if X is a nonempty matrix, then median(X) treats the columns of A as vectors and returns a row vector of median values
std(X)
returns the standard deviation of X, If X is a matrix, std(X) returns a row vector containing the standard deviation of the elements of each column of X.
var(X)
Returns the variance of X for vectors. For matrices, var(X) is a row vector containing the variance of each column of X.
numel(X)
Returns the number of elements in X.
Examples:
If X is  5x3 matrix:
>> sum(sum(X))
>> min(min(X))
>> max(man(X))

MATLAB special functions for matrices:

Function
Result
diag(X,k)
diag(X) ,k=0
X = diag(X,k) when X is a vector of n components, returns a square matrix X of order n+abs(k), with the elements of v on the kth diagonal. k = 0 represents the main diagonal, k > 0 above the main diagonal, and k < 0 below the main diagonal.
triu(X,k)
triu(X) ,k=0
returns the element on and above the kth diagonal of X. k= 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.
tril(X,k)
tril(X) ,k=0
Returns the elements on and below the kth diagonal of X. k= 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.
trace(X)
Returns the sum of the diagonal elements of the matrix X.
rank(X)
The rank function provides an estimate of the number of linearly independent rows or columns of a full matrix.
k = rank(X) returns the number of singular values of X that are larger than the default tolerance, max(size(A))*eps(norm(A)).
rref(X)
Produces the reduced row echelon form of X using Gauss Jordan elimination with partial pivoting. Default tolerance of (max(size(X))*eps *norm(X,inf)) tests for negligible column elements.
det(X)
Returns the determinant of the square matrix X.
inv(X)
Returns the inverse of the square matrix X, where X*inv(X) = the identity matrix.
norm(X)
The norm function calculates several different types of matrix and vector norms. If the input is a vector or a matrix: n = norm(X,2) returns the2-norm of X. n = norm(X) is the same as n = norm(X,2). n = norm(X,1) returns the1-norm of X.
When the input is a vector v: n = norm(v,p) returns the p-norm of v. The p-norm is sum (abs (v).^p)^(1/p).
eig(X)
eig(X,Y)
Returns a vector of the Eigen values of matrix X.
Returns a vector containing the generalized Eigen values, if X and Y are square matrices.
poly(X)
where X is an n-by-n matrix returns an n+1 element row vector whose elements are the coefficients of the characteristic polynomial, det(λI – A). eig(X) = roots(poly(X)).
rot90(A)
rot90(A,k)
Rotates matrix A counter clockwise by 90 degrees.
Rotates matrix A counterclockwise by k*90 degrees, where k is an integer.
reshape(A,m,n)
Returns a new matrix of A by reshaping its size to m by n.
B = fliplr(A)
Returns A with columns flipped in the left-right direction, that is, about a vertical axis.
B = flipud(A)
Returns A with rows flipped in the up-down direction, that is, about a horizontal axis.
A = pascal(n)

Returns the Pascal matrix of order n: a symmetric positive definite matrix with integer entries taken from Pascal's triangle. The inverse of A has integer entries.
B=repmat(A,m,n)
Creates a large matrix B consisting of an m-by-n tiling of copies of A. The size of B is [size(A,1)*m, (size(A,2)*n].The statement repmat(A,n) creates an n-by-n tiling.

Symbolic math toolbox with matrices and vectors:

Symbolic math toolbox is very useful with matrices and vectors when working with algebraic entities, fractions, and constants like "pi, i, …" , so some examples of the usage of the symbolic math toolbox will be discussed in this section.
>> syms x A B
>> A=[x^2 x-3;x^2-x x]
 A =
[     x^2, x - 3]
[ x^2 - x,     x]
>> B=[x x^4-x;x^2 x+4]
 B =
[   x, x^4 - x]
[ x^2,   x + 4]
Then you can perform any calculations into these two symbolic matrices simply and get the answers in the symbolic form, for example:
-         Addition:
>> A+B
 ans =
[   x^2 + x, x^4 - 3]
[ 2*x^2 - x, 2*x + 4]

-         Subtraction:
>> A-B
ans =
[ x^2 - x, - x^4 + 2*x - 3]
[      -x,              -4]

-         Multiplication by scalar:
>> 5*A
ans =
[       5*x^2, 5*x - 15]
[ 5*x^2 - 5*x,      5*x]

-         Matrices multiplication:
>> A*B
ans =
 [   x^2*(x - 3) + x^3,   (x - 3)*(x + 4) - x^2*(- x^4 + x)]
[ x^3 - x*(- x^2 + x), (- x^2 + x)*(- x^4 + x) + x*(x + 4)]

-         Element by element multiplication:
>> A.*B
 ans =
 [              x^3, -(- x^4 + x)*(x - 3)]
[ -x^2*(- x^2 + x),            x*(x + 4)]
-         Transpose:
>> A'
 ans =
[   conj(x)^2, conj(x)^2 - conj(x)]
[ conj(x) - 3,             conj(x)]

-         Determinant:
>> det(A)
ans =
4*x^2 - 3*x
We can apply in other functions of matrices functions into a symbolic matrix like dot, cross, inverse, trace, and other function using the proper way and the right syntax and according to MATLAB and Mathematics rules.

Matrices visualization:

There is some ways to manipulate data representation of a matrix using MATLAB, to figure out a matrix of data or elements we can use:

Spy command:

If we have the declared variable X which defined to hold the matrix as below:
>> X = [12 56 23 3.2 ; 14 8.5 96 48 ; 96 2 47 36]
Then use the command:
>> spy(X)
Will popup the figure window with dots which represents the positions of the elements of X that’s have a value, and at the bottom we see nz=12 which is the number of the elements of X.   
Another example, if we have created a 5 by 5 identity matrix M as:
>> M=eye(5)
Then use the spy command as:
>> spy(M)
The resulted figure will be:

Multidimensional arrays:

An array having more than two dimensions is called a multidimensional array in the MATLAB® application. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix. Matrices have two dimensions: the row dimension and the column dimension.
-         Multidimensional arrays use additional subscripts for indexing. A three-dimensional array, for example, uses three subscripts:
·        The first references array dimension 1, the row.
·        The second references dimension 2, the column.
·        The third references dimension 3. This illustration uses the concept of a page to represent dimensions 3 and higher.
-         If we have create the 3-D array as:
-         To specify the element in the second row, third column of page2, for example, you use the subscripts (2,3,2).

Generating Arrays Using Indexing

One way to create a multidimensional array is to create a two-dimensional array and extend it. For example, begin with a simple two-dimensional array A.
>> A = [5 7 8; 0 1 9; 4 3 6];
A is a 3-by-3 array, that is, its row dimension is 3 and its column dimension is 3. To add a third dimension to A,
>> A(:,:,2) = [1 0 4; 3 5 6; 9 8 7]
MATLAB responds with
A(:,:,1) =
     5     7     8
     0     1     9
     4     3     6

A(:,:,2) =
     1     0     4
     3     5     6
     9     8     7
You can continue to add rows, columns, or pages to the array using similar assignment statements.

Extending Multidimensional Arrays

To extend A in any dimension:
·       Increment or add the appropriate subscript and assign the desired values.
·       Assign the same number of elements to corresponding array dimensions. For numeric arrays, all rows must have the same number of elements, all pages must have the same number of rows and columns, and so on.
You can take advantage of the MATLAB scalar expansion capabilities, together with the colon operator, to fill an entire dimension with a single value:
>> A(:,:,3) = 5;
A(:,:,3)
ans =
     5     5     5
     5     5     5
     5     5     5

-          To turn A into a 3-by-3-by-3-by-2, four-dimensional array, enter
>> A(:,:,1,2) = [1 2 3; 4 5 6; 7 8 9];
>> A(:,:,2,2) = [9 8 7; 6 5 4; 3 2 1];
>> A(:,:,3,2) = [1 0 1; 1 1 0; 0 1 1];
Note that after the first two assignments MATLAB pads A with zeros, as needed, to maintain the corresponding sizes of dimensions.

Generating Arrays Using MATLAB Functions

You can use MATLAB functions such as randn, ones, and zeros to generate multidimensional arrays in the same way you use them for two-dimensional arrays. Each argument you supply represents the size of the corresponding dimension in the resulting array. For example, to create a 4-by-3-by-2array of normally distributed random numbers:
>> B = randn(4,3,2)
To generate an array filled with a single constant value, use the repmat function. repmat replicates an array (in this case, a 1-by-1 array) through a vector of array dimensions.
>> B = repmat(5, [3 4 2])
B(:,:,1) =
     5     5     5     5
     5     5     5     5
     5     5     5     5
B(:,:,2) =
     5     5     5     5
     5     5     5     5
     5     5     5     5
-         Another way using reshape function:
>> A = reshape(1:27 ,[3 3 3])
A(:,:,1) =
     1     4     7
     2     5     8
     3     6     9
A(:,:,2) =
    10    13    16
    11    14    17
    12    15    18
A(:,:,3) =
    19    22    25
    20    23    26
    21    24    27

No comments:

Post a Comment