Ch01-02 MatlabBasics
Ch01-02 MatlabBasics
• Home Page
www.jspark.net
• Mobile : 010-5335-9009
• E-mail : [email protected]
Introduction Course Descriptions
• Lecture Time Table
- Course Number EP01004008 :
- Course Number EP01004009 :
- Course Number EP01004010 :
• Course Description:
- To learn MATLAB programming language constructs and concepts.
Year Semester Title Language
1 1 Business C
Computing
1 2 Computer MATLAB
Programming
JAVA
2 1 Programming C++
Language
Visual C++
MFC
3
Introduction Course Descriptions
• Lecture Hours
- One three-hours-per-week lectures and practical.
• Grading System
Attendance and Attitude : 20% Midterm Exam : 30%
Report and Practical Exercises : 20% Final Exam : 30% - 15th week
• Textbook
MATLAB - Matlab 7 Getting Started Guide, The MathWorks 2010.
JAVA and Android Eclipse – Lecture Note
• You need to prepare
- Text book or Lecture Note - USB memory
- MATLAB and Eclipse in your computer
4
5
Introduction Textbook
6
Chapter 01:
Introduction of MATLAB
By J.S. Park
Incheon National University
Introduction MATLAB History
• Revision History
• December 1996 First printing For MATLAB 5
• May 1997 Second printing For MATLAB 5.1
• September 2000 Fourth printing Revised for MATLAB 6 (Release 12)
• June 2004 Sixth printing Revised for MATLAB 7.0 (Release 14)
• September 2005 Online only Minor revision for MATLAB 7.1 (Release 14SP3)
• March 2006 Online only Minor revision for MATLAB 7.2 (Release 2006a)
• March 2010 Fifteenth printing Minor revision for MATLAB 7.10 (Release 2010a)
• (Release 2016a)
8
Software Development Philosophy
• Matrix-based numeric computation
• MATrix LABoratory
• High-level programming language
• Graphics and data visualization
• Toolboxes - provide application specific functionality
• Toolboxes extend
the MATLAB environment to solve problems in particular application areas.
• You can integrate your MATLAB code with other languages and applications.
10
Install MATLAB Dounload and Install
11
Install MATLAB Dounload and Install
12
Introduction Starting a MATLAB Session
• The Desktop
13
Introduction MATLAB Desktop
command window
• MATLAB code executes and type in your functions
• The MATLAB Workspace
edit window
• Use editor
• tty File->New->M-file in the upper-left corner of your command
window
• this window is used to create and edit MATLAB (M-files) files
graphics window
• this window (or figure) is used to display plots or other images
14
Introduction Finding MATLAB assistance
>> help
• help => Online help for MATLAB functions and M-files
• use >>help cos ↲ % i.e. “ help topic_name “
>> doc
• Displays The MathWorks, Inc. HTML (Online) documentation.
>> demos
• will open a window a "MATLAB Demos" Window on your screen.
>>lookfor
• keyword search through all help entries.
• lookfor topic searches for the string topic in the first comment
line of the help text.
15
>> cd : Changes working directory
>> mkdir : Make a directory
>> clc : Clear the command window
>> who, whos : show the current contents of the workspace
>> clear : Clear items from memory.
>> delete : Delete files
>> dir : dir lists the files in the current directory.
>> more : Control page output for command window.
>> quit :Terminates MATLAB
>> dbtype : List M-file code with line numbers
16
Column Vectors A column vector is an m-by-1
Row Vectors A row vector is an 1-by-n matrix
Matrices A matrix is a two-dimensional rectangular array of real or complex
numbers.
Scalars Any single element or numerical value.
Square Matrices Any matrix that has the number of rows equal to the number of columns (m =
n).
Transpose Using the single quote after a variable to make row vectors into column vectors and c
olumn
vectors into row vectors.
Ans The most recent answer and the default variable name.
The Percent Sign The Percent Sign (%) at the start of the line will create a comment out of that li
ne.
The Single Quote
The Single Quote (') at the end of a variable assignment transposes the array or matrix.
Single quotes on either side of text creates a string of the characters inside the quotes.
The Ellipsis The elipsis (...) => allows continuation of code or elements to the next line.
Variables MATLAB does not require any type declarations or dimension statements.
17
Introduction Command Window
>> s = 1 + 2 >>whos
s= Name Size Bytes Class
3 ans 1x1 16 double array (complex)
fun 1x1 8 double array
>> fun = sin(pi/4) s 1x1 8 double array
fun =
0.7071 Grand total is 3 elements using 32 bytes
>>s >>who
s= Your variables are:
3 ans fun s
>>format long
>>fun
fun =
0.70710678118655
18
Chapter 02:
Matrices and Arrays
By J.S. Park
Incheon National University
Matrices and Magic Squares
About Matrices
• A matrix is a m-by-n rectangular array of numbers.
• Scalars are 1-by-1 matrices
• Column vectors are m-by-1 matrices
• Row vectors are 1-by-n matrices
An example matrix
• To enter Dürer’s matrix(magic squres), simply type in the Command
Window
or
>> A = magic(4)
sum, transpose, and diag
Type in the Command Window >> sum(A')‘ • antidiagonal MATLAB does not
>>A=[1 2 3;4 5 6;7 8 9] produces a column vector have a function for it.
A= containing the row sums
• fliplr, flips a matrix from left to
1 2 3 ans =
right:
4 5 6 6
7 8 9 15 >> sum(diag(fliplr(A)))
24 ans =
15
The first statement to try is
>> sum(A) • The sum of the elements on the complex conjugate
main diagonal is obtained with
MATLAB replies with the sum and the diag functions:
>> z=[1+2i 3+4i]
z=
ans =
>> diag(A) 1.0000 + 2.0000i 3.0000 + 4.0000i
12 15 18
ans =
>>z‘
1
which is column sums ans =
5 1.0000 - 2.0000i
and the result is row vector 9 3.0000 - 4.0000i
>> A‘ >>z.‘
>> sum(diag(A)) ans =
produces ans = 1.0000 + 2.0000i
ans = 15 3.0000 + 4.0000i
1 4 7
2 5 8
3 6 9
Subscripts
The element in row i and column j of A is denoted by >> y=A;
A(i,j). >> y(3,4)=17
For example, y=
A(1,3) =3, which is the number in the first row and 1 2 3 0
third column. 4 5 6 0
>> A(2,3) 7 8 9 17
ans =
>>x=[-1.3 sqrt(3) (1+2+3)*4/5]
6
x=
>> A(3,2)
-1.3000 1.7321 4.8000
ans =
8 >>x(3) ↲
>> A(1,3)+A(2,3)+A(3,2) ans =
This subscript produces 4.8000
ans =
17 >> Ax=[A;x]
Ax =
1.0000 2.0000 3.0000
A single subscript, A(k), is the usual way of referencing
4.0000 5.0000 6.0000
row and column vectors.
7.0000 8.0000 9.0000
For example: -1.3000 1.7321 4.8000
A(6)=A(3,2) >>xA=[A ; x‘]
??? All rows in the bracketed expression must have
If you try to use the value of an element outside of the the same number of columns
matrix, it is an error:
>>x(5)=abs(x(1))
>> t = A(4,5)
x=
Index exceeds matrix dimensions. -1.3000 1.7321 4.8000 0 1.3000
The Colon Operator
The colon, :, occurs in several different forms. The colon by itself refers to all the elements
The expression in a row or column of a matrix. Thus:
>> 1:10 >> sum(A(:,end))
computes the sum of the elements in the last
is a row vector containing the integers from 1 to 10: column of A:
1 2 3 4 5 6 7 8 9 10 ans =
18
To obtain nonunit spacing, specify an increment. The colon can be used as subscripts of matrices
x=min_val : delta : max_val >> y=A;
For example, >> x=-3:-1;
>> y(1,1:3)=x
>>100:-7:50 y=
is -3 -2 -1
100 93 86 79 72 65 58 51 4 5 6
and 7 8 9
>> sum(sum(y))
>>0:pi/4:pi ans =
is 33
0 0.7854 1.5708 2.3562 3.1416
>>[r,c]=size(y) ↲
r=
Subscript expressions involving colons refer to 3
portions of a matrix: c=
3
>>A(1:k,j) >> y(:,[2 3 1])
is the first k elements of the jth column of A. Thus: ans =
-2 -1 -3
>>sum(A(1:3,3))
5 6 4
computes the sum of the third column. 8 9 7
Variables
• MATLAB does not require any type declarations or dimension statements.
• With a new variable name, it automatically creates the variable and allocates the appropriate amount
of storage.
• If the variable already exists, MATLAB changes its contents.
• For example,
num_students = 25 creates a 1-by-1 matrix named num_students and stores the value 25.
• To view the matrix assigned to any variable, simply enter the variable name.
• Variable names consist of a letter, followed by any number of letters, digits, or underscores.
• MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters.
A and a are not the same variable.
• Although variable names can be of any length, MATLAB uses only the first N characters of the name,
(where N is the number returned by the function namelengthmax), and ignores the rest.
Hence, it is important to make each variable name unique in the first N characters to enable MATLAB
to distinguish variables.
>> N = namelengthmax
N=
63
Numbers
• MATLAB uses an optional decimal point and leading plus or minus sign.
• Scientific notation uses the letter e to specify a power-of-ten scale factor.
• Imaginary numbers use either I or j as a suffix.
• Some examples of legal numbers are
3 -99 0.0001 9.6397238 1.60210e-20 6.02252e23 1i -3.14159j 3e5i
• All numbers are stored internally using the long format.
• Floating-point numbers have a finite precision of roughly 16 significant decimal digits
and a finite range of roughly 10-308 to 10+308.
• MATLAB software stores the real and imaginary parts of a complex number.
• For instance, the sort function sorts based on magnitude and resolves ties by phase angle.
>> sort([3+4i, 4+3i]) % result in ascending order
ans =
4.0000 + 3.0000i 3.0000 + 4.0000i
This is because of the phase angle:
>>angle(3+4i) >>angle(4+3i)
ans = ans =
0.9273 0.6435
• The “equal to” relational operator == requires both the real and imaginary parts to be equal.
• The other binary relational operators > <, >=, and <=
ignore the imaginary part of the number and consider the real part only.
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
\(\) Left division
^ Power
‘ Complex conjugate transpose
() Specify evaluation order
Functions
• Standard elementary mathematical functions
abs, sqrt, exp, and sin
• More advanced mathematical functions
Bessel and gamma functions
• For a list of the elementary mathematical functions, type
help elfun
• For a list of more advanced mathematical and matrix functions, type
help specfun
help elmat
• Built-in functions
- (ex.) sqrt, sin, sinh
- they are part of the MATLAB core so they are very efficient.
- you cannot see the code.
• Other functions
- (ex.) gamma, bessel
- they are implemented in M-files.
- you can see the code and even modify it if you want.
special functions
• Several special functions provide values of useful constants.
pi 3.14159265...
i Imaginary unit, 1
j Same as i
eps Floating-point relative precision, 252
realmin Smallest floating-point number, 2 1022
realmax Largest floating-point number, (2 )1023
Inf Infinity
NaN Not-a-number
• Infinity is generated by dividing a nonzero value by zero, or overflow, i.e., exceed realmax.
• Not-a-number is generated by trying to evaluate expressions like 0/0 or Inf-Inf
that do not have well defined mathematical values.
• The function names are not reserved. It is possible to overwrite any of them with a new
variable, such as
pi = 2
>>rho = (1+sqrt(5))/2
rho =
1.6180
>>a = abs(3+4i)
a=
5
>>z = sqrt(besselk(4/3,rho-i))
z=
0.3730+ 0.3214i
>>huge = exp(log(realmax))
huge =
1.7977e+308
>>toobig = pi*huge
toobig =
Inf
Working with Matrices
• Generating Matrices
• The load Function
• M-Files
• Concatenation
• Deleting Rows and Columns
Generating Matrices
• MATLAB software provides four functions that generate basic matrices.
The Pascal matrix is a
n infinite matrix
zeros All zeros containing the
binomial coefficients
ones All ones as its elements
rand Uniformly distributed random elements
randn Normally distributed random elements
eye Identity matrix
pascal Pascal matrix
magic Magic square
• Some examples:
>>Z = zeros(2,4) >>F = 5*ones(3,3) >>N = fix(10*rand(1,10))
Z= F= N=
0000 555 9264874084
0000 555
555 >>iden=eye(3) >>A=pascal(3)
iden = A=
>> R = randn(4,4) 1 0 0 1 1 1
R= 0 1 0 1 2 3
0.6353 0.0860 -0.3210 -1.2316 0 0 1 1 3 6
-0.6014 -2.0046 1.2366 1.0556
0.5512 -0.4931 -0.6313 -0.1132
-1.0998 0.4620 -2.3252 0.3792
M-Files
• You can create your own matrices using M-files,
which are text files containing MATLAB code.
• Use the MATLAB Editor or another text editor to create a file
containing the same statements you would type at the MATLAB
command line.
• Save the file under a name that ends in .m.
• For example, create a file in the current directory named magik.m
containing these five lines:
• The statement
magik
reads the file and creates a variable, A, containing the example matrix.
Concatenation
• Concatenation is the process of joining small matrices to make bigger ones.
• The pair of square brackets, [], is the concatenation operator.
• For an example, start with the 4-by-4 magic square, A, and form
>>B = [A A+32; A+48 A+16]
• This matrix is halfway to being another magic square. Its elements are a rearrangement
of the integers 1:64. Its column sums are the correct value for an 8-by-8 magic square:
>>sum(B)
ans =
260 260 260 260 260 260 260 260
Deleting Rows and Columns
• You can delete rows and columns from a matrix using just a pair of square brackets.
Start with
>>X = A;
Then, to delete the second column of X, use
>>X(:,2) = []
This changes X to
X=
16 2 13
5 11 8
9 7 12
4 14 1
• If you delete a single element from a matrix, the result is not a matrix anymore.
So, expressions like
>>X(1,2) = [] result in an error.
you will get a warning message: The coefficients in the The reduced row echelon form of A
Warning: Matrix is close to singular characteristic polynomial is not the identity:
or badly scaled. >>poly(A) >>R = rref(A)
are R=
1 -34 -64 2176 0 1001
0 1 0 -3
These coefficients indicate that the 0013
characteristic polynomial 0000
det( A I )
is
• If you want more control over the output format, use the sprintf and fprintf functions.
Command Line Editing
Suppressing Output
• If you simply type a statement and press Return or Enter, MATLAB automatically displays the results
on screen.
• However, if you end the line with a semicolon, MATLAB performs the computation but does not
display any output.
Key Action
Recall previous command line
Recall next command line
Move the cursor right
Move the cursor left
Home Move the cursor to beginning of the command line
End Move the cursor to end of command line
Matlab Operators and Priorities
Arithmetic Operators
+ Addition
- Subtraction
* multiplication .* Element-by-element multiplication
/ division ./ Element-by-element division
\(\) Left division .\ Element-by-element left division
Logical Operators
& AND
| OR
~ NOT
Matlab Operation Examples
Arithmetic Operators Relational Operators