Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

MATLAB BEGINNER'S GUIDE, Study notes of Engineering

In general, MATLAB is a useful tool for vector and matrix manipulations. Since the majority of the engineering systems are ... both beginners and experts.

Typology: Study notes

2021/2022

Uploaded on 09/27/2022

mrbean3
mrbean3 🇬🇧

4

(5)

214 documents

1 / 24

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
0
MATLAB
BEGINNER’S
GUIDE
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download MATLAB BEGINNER'S GUIDE and more Study notes Engineering in PDF only on Docsity!

MATLAB

BEGINNER’S

GUIDE

About MATLAB MATLAB is an interactive software which has been used recently in various areas of engineering and scientific applications. It is not a computer language in the normal sense but it does most of the work of a computer language. Writing a computer code is not a straightforward job, typically boring and time consuming for beginners. One attractive aspect of MATLAB is that it is relatively easy to learn. It is written on an intuitive basis and it does not require in-depth knowledge of operational principles of computer programming like compiling and linking in most other programming languages. This could be regarded as a disadvantage since it prevents users from understanding the basic principles in computer programming. The interactive mode of MATLAB may reduce computational speed in some applications. The power of MATLAB is represented by the length and simplicity of the code. For example, one page of MATLAB code may be equivalent to many pages of other computer language source codes. Numerical calculation in MATLAB uses collections of well-written scientific/mathematical subroutines such as LINPACK and EISPACK. MATLAB provides Graphical User Interface (GUI) as well as three-dimensional graphical animation. In general, MATLAB is a useful tool for vector and matrix manipulations. Since the majority of the engineering systems are represented by matrix and vector equations, we can relieve our workload to a significant extent by using MATLAB. The finite element method is a well-defined candidate for which MATLAB can be very useful as a solution tool. Matrix and vector manipulations are essential parts in the method. MATLAB provides a help menu so that we can type the help command when we need help to figure out a command. The help utility is quite convenient for both beginners and experts.

which is the third column of matrix A. In addition,

A(:,1) represents the first row of A as ans = 1 3 6 We can also try A(:,1)+A(:,3) as addition of the first and third rows of A with the result ans= 1 6 15 Now let us introduce another matrix B as B = [3,4,5; 6,7,2:8,1,0]; Then there seems to be no output on the screen. MATLAB does not prompt output on the screen when an operation ends with the semicolon (;). If we want to check the B matrix again, we simply type B The screen output will be 3 4 5 B = 6 7 2 8 1 0 Matrix addition Adding two matrices is straightforward like C = A + B 4 7 11 C = 8 14 10 8 4 9

Matrix subtraction In order to subtract matrix B from matrix A, we type

>> C = A-B

C = -4 0 6

Note that C is now a new matrix, not the summation of A and B anymore. Matrix multiplication Similarly, matrix multiplication can be done as

C = A*B

69 31 11 C= 112 65 24 90 30 6 Matrix Functions Manipulation of matrices is a key feature of the MATLAB functions. MATLAB is a useful tool for matrix and vector manipulations. Collections of representative MATLAB matrix functions are listed in Table 1. Examples and detailed explanations are provided for each function below.

Table 1. Basic Matrix Functions Symbol Explanations inv inverse of a matrix det determinant of a matrix rank rank of a matrix cond condition number of a matrix eye(n) the n by n identity matrix zeros(n,m) the n by m matrix consisting of all zeros

ans = 0.0470 0.9347 0. 0.6789 0.3835 0. That is, rand(3,3) produces a 3 by 3 matrix whose elements consist of random numbers. The general usage is rand(n, m). trace Summation of diagonal elements of a matrix can be obtained using the trace operator. For example,

C= [1 3 9; 672; 8 -1 -2]; Then, trace(C) produces 6, which is the sum of diagonal elements of C. zero matrix zeros(5,4) produces a 5 by 4 matrix consisting of all zero elements. In general, zeros(n,m) is used for an n by m zero matrix. condition number The command cond(A) is used to calculate the condition number of a matrix A. The condition number represents the degree of singularity of a matrix. An identity matrix has a condition number of unity, and the condition number of a singular matrix is infinity. cond(eye(6)) ans = 1 An example matrix which is near singular is A=[1 1;1 1+1e-6] The condition number is cond( A ) ans = 4.0000e+ Further matrix functions are presented in Table 2. They do not include all matrix functions of the MATLAB, but represent only a part of the whole MATLAB functions. Readers can use the MATLAB Reference Guide or help command to check when they need more MATLAB functions.

Table 2. Basic Matrix Functions (Continued) Symbol Explanations expm exponential of a matrix eig eigenvalues/eigenvectors of a matrix lu LU decomposition of a matrix svd singular value decomposition of a matrix qr QR decomposition of a matrix \ used to solve a setof linear algebraic equations

Matrix exponential The expm(A) produces the exponential of a matrix A. In other words,

A =rand(3, 3) 0.2190 0.6793 0. A = 0.0470 0.9347 0. 0.6789 0.3835 0. expm(A) 1.2448 0.0305 0. ans= 1.0376 1.5116 1. 1.0157 0.1184 2. Eigenvalues The eigenvalue problem of a matrix is defined as Aφ= λφ

where A is the eigenvalue of matrix A, and (j> is the associated eigenvector.

e =eig(A) gives the eigenvalues of A, and [V,D]=eig(A) produces the V matrix, whose columns are eigenvectors, and the diagonal matrix D whose values are eigenvalues of the matrix A. For example,

available

[L,U,P]=lu(A)

L =

U= 0 1.2500 4.

P= 1 0 0

Here, the matrix P is the permutation matrix such that P * A = L * U. Singular value decomposition The svd command is used for singular value decomposition of a matrix. For a given matrix, A =UΣV′ where Σ is a diagonal matrix consisting of non-negative values. For example, we define a matrix D like

D = [1 3 7; 2 9 5 ; 2 8 5 ] The singular value decomposition of the matrix is [U, Sigma, V]=svd(D) which results in

U =

Sigma =

V =

QR decomposition A matrix can be also decomposed into a combination of an orthonormal matrix and an upper triangular matrix. In other words, A = QR where Q is the matrix with orthonormal columns, and R is the upper triangular matrix. The QR algorithm has wide applications in the analysis of matrices and associated linear systems. For example,

A =

Application of the qr operator follows as

[Q,R]=qr(A) and yields

Q =

R =

Solution of linear equations The solution of a linear system of equations is frequently needed in the finite element method. The typical form of a linear system of algebraic equations is written as Ax = y and the solution is obtained by

x =inv(A) * y or we can use \ sign as x = A\y For example

Table 3 Loop and Logical Statements Symbol Explanations for loop command similar to other languages used while for a loop combined with conditional statement if produces a conditional statement elseif, else used in conjunction with if command break breaks a loop when a condition is satisfied

while The while command is useful for an infinite loop in conjunction with a conditional statement. The general synopsis for the while command is as follows: while condition statements end For example, i= 1 while (i < 100) i = i + l; end Another example of the while command is n = 1000; var = []; while (n > 0) n = n/2-1; var = [var,n]; end

The result is var = Columns 1 through 7 499.0000 248.5000 123.2500 60.6250 29.3125 13.6563 5. Columns 8 through 9 1.9141 -0.

where we used [ ] in order to declare an empty matrix. if, elseif, else The if, elseif, and else commands are conditional statements which are used in combination. if condition #1 statement # elseif condition #2 statement

else statement # end For example, n = 100; if (rem(n,3) ==0) x = 0; elseif (rem(n, 3) == 1) x=1; else x=2; end ,where rem(x,y) is used to calculate the remainder of x divided by y. Table 4 Loop and Logical Statements Symbol Explanations == two conditions are equal ~= two conditions are not equal <=(>=) one is less (greater) than or equal to the other <(>) one is less (greater) than the other & and operator - two conditions are met ~ not operator | or operator - either condition is met

solution. function [r1,r2]=secroot(a,b,c); % % Find Determinant -- Any command in MATLAB which starts with % % sign is a comment statement Det= 6^2 - 4 * a * c; if (Det < 0), r1=- (-b + j* sqrt(-Det))/2/a; r2 = (-b -j* sqrt(-Det))/2/a; disp('The two roots are complex conjugates'); elseif(Det == 0), r1 = -b/2/a; r2 = -b/2/a; disp('There are two repeated roots'); else(Det > 0) r1 = (-6 + sqrt(Det))/2/a; r2 = (-b - sqrt(Det))/2/a; disp('The two roots are real'); end Some commands appearing in the above example will be discussed later. Once the secroot.m is created, we call that function as

[rl,r2]=secroot(3,4,5) or [pl,p2] =secroot(3,4,5) One thing important about the function command is to set up the m-file pathname. The m-file should be in the directory which is set up by the MATLAB configuration set up stage. In the recent version of MATLAB, the set up procedure is relatively easy by simply adding a directory which we want to access in a MATLAB configuration file.

Another function subroutine fct.m is provided below. function [f] =fct(x) f= (l-x)^2; The above function represents f(x)= (l-x)^2. In the MATLAB command prompt, we call the function as

y =fct(9); The function subroutine utility of MATLAB allows users to write their own subroutines. It provides flexibility of developing programs using MATLAB.

File Manipulation Manipulating files is another attractive feature of MATLAB. We can save MATLAB workspace, that is, all variables used, in a binary file format and/or a text file format. The saved file can also be reloaded in case we need it later on. The list of file manipulation commands is presented in Table 5. Table 5 File Manipulation Commands Symbol Explanations save save current variables in a file load load a saved file into Matlab environment diary save screen display output in text format save The save command is used to save variables when we are working in MATLAB. The synopsis is as follows save filename var 1 var 2 ... where filename is the filename and we want to save the variables, var 1 var 2 .... The filename generated by save command has extension of .mat, called a mat- file. If we do not include the variables name, then all current variables are saved automatically. In case we want to save the variables in a standard text format, we use save filename var 1 var 2 .../ascii/double load The load command is the counterpart of save. In other words, it reloads the variables in the file which was generated by save command. The synopsis is as follows

input The input command is used to receive a user input from the keyboard. Both numerical and string inputs are available. For example,

age= input('How old are you?') name—input('What is your name','s') The 's' sign denotes the input type is string. disp The disp command displays a string of text or numerical values on the screen. It is useful when we write a function subroutine in a user-friendly manner. For example, disp('This is a MATLAB tutoriall') c=3*4; disp('T/ie computed value of c turns out to be') c format The format command is used to display numbers in different formats. MATLAB calculates floating numbers in the double precision mode. We do not want to, in some situations, display the numbers in the double precision format on the screen. For a display purpose, MATLAB provides the following different formats x = 1/ x = 0. format short e z = l.lllle- format long 1 = 0. format long e x- l.llllllllllllllle- format hex x = 3/6c71c71c71c71c Plotting Tools MATLAB supports some plotting tools, by which we can display the data in a desired format. The plotting in MATLAB is relatively easy with various options available. The collection of plotting commands is listed in Table 7. A sample plotting command is shown below.

t = 0:0.1: 10; y = sin(t); plot(y) title('plot(y)')

The resultant plot is presented at the top of Fig. 1.

t = 0 :0.1 : 10; y = sin(t); plot(t,y) title('plot(t,y)')

Table 7 Plotting Commands Symbol Explanations plot basic plot command xlabel(ylabel) attach label to x(y) axis axis manually scale x and y axes text place a text on the specific position of graphic title place a graphic title on top of the graphic ginput produce a coordinate of a point on the graphic gtext receives a text from mouse input grid add a grid mark to the graphic window pause hold graphic screen until keyboard is hit subplot breaks a graphic window into multiple windows

The resultant plot is presented at the bottom of Fig. 1. In the above example, t = 0 : 0.1 : 10 represents a vector t which starts from 0 and ends at 10 with an interval of 0.1. We can use just y or both y and t together. In the first case, the horizontal axis represents number of data, from 0 to 101. In the second case, the horizontal axis is the actual time scale t hi the plot(t,y) command.