Upload
adam-gregory
View
242
Download
5
Embed Size (px)
Citation preview
1
Computer ProgrammingComputer Programming(ECGD2102 )(ECGD2102 )
Using MATLAB Using MATLAB
Instructor: Instructor: Eng. Eman Al.Swaity
Lecture (2): Lecture (2): MATLAB EnvironmentMATLAB Environment
(Chapter 1)
2
ObjectivesObjectives
CHAPTER (1):MATLAB EnvironmentCHAPTER (1):MATLAB Environment
- Perform simple calculations with MATLAB.Perform simple calculations with MATLAB.
- Observe the display formats available and select Observe the display formats available and select specific formats.specific formats.
- List the predefined MATLAB variables.List the predefined MATLAB variables.
- Perform arithmetic calculations.Perform arithmetic calculations.
- Introduce simple matrix operations.Introduce simple matrix operations.
3
1.1 MATLAB as a Calculator1.1 MATLAB as a Calculator
MATLAB performs simple calculations as if it were a calculator. The basic arithmetic operators are + - * / ^ and these are used in conjunction with brackets: (parentheses ). The symbol^ is used to get exponents (powers): 2^4=16.You should type in commands shown following the prompt: >> (in command window).For example, type 5+3 and press the ENTER key:
» 5+3ans = 8
4
1.1 MATLAB as a 1.1 MATLAB as a Calculator-contCalculator-cont
Another example>> 2 + 3/4*5ans = 5.7500>>Is this calculation 2 + 3/(4*5) or 2 + (3/4)*5? Matlab works according to the priorities (Operator precedence ):1. quantities in brackets,2. powers 2 + 3^2 )2 + 9 = 11,3. * /, working left to right (3*4/5=12/5),4. + -, working left to right (3+4-5=7-5),Thus, the earlier calculation was for 2 + (3/4)*5 by priority 3.
5
1.1 MATLAB as a 1.1 MATLAB as a Calculator-contCalculator-cont
Another examples
6
1.1 MATLAB as a 1.1 MATLAB as a Calculator-contCalculator-cont
Another examples
» 1+2-3*4/5
ans =
0.6000
» -4/5*3+2+1
ans =
0.6000
7
1.2 Defining Variables1.2 Defining Variables
Variables are named locations in memory where numbers, strings and other elements of data may be stored while the program is working. Variable names are combinations of letters , digits, andthe underscore character, but must start with a latter (These are allowable: NetCost, Left2Pay, x3, X3, z25c)We define variables by typing a variable name followed by the equals sign and then a value or a mathematical expression. Example: » A5=6 A5 = 6
8
1.2 Defining Variables-cont1.2 Defining Variables-cont
Variable types:Not all variables are created equal.
The most commonly used unit of computer storage is the byte, itself made of up 8 bits.
A byte represents an 8-bit binary number, i.e. it is an eight digit number in base 2 (as opposed to base 10 or decimal with which we are most familiar.)
9
1.2 Defining Variables-cont1.2 Defining Variables-cont
Variable types:
A byte can thus hold the equivalent of decimal integers 0 (000000002) through 255 (111111112).
To represent other forms of information than simply the integers 0-255, computers use different types of encoding and groups of bytes to represent e.g. letters, punctuation, and numbers of greater precision and magnitude.
10
1.2 Defining Variables-cont1.2 Defining Variables-cont
Variable types:
The byte arose as the fundamental unit because it is capable of representing all the most common numbers, letters (upper and lower case), punctuation, and special control characters commonly used in computer communication (things like <ENTER>, <ESC>, <BACKSPACE>, etc.). The most common encoding for alpha-numerics is the American Standard Code for Information Interchange, or ASCII.
11
1.2 Defining Variables-cont1.2 Defining Variables-cont
MATLAB does not require you to declare the names of variables in advance of their use. This is actually a common cause of error.
variable names are case sensitive variable names start with a letter and can contain up to 31 characters which include letters, digits and underscore ( punctuation characters and math operators are not allowed)
12
1.2 Defining Variables-cont1.2 Defining Variables-cont
To know what is stored in a variable type its name at the command prompt
Matlab has built in variable names. the following are some of the built in variables: (ans, pi, eps, flops,
inf, NaN or nan, i , j, nargin, nargout, realmin, realmax). Avoid using built-in names.
13
1.2 Defining Variables-cont1.2 Defining Variables-cont
14
1.2 Defining Variables-cont1.2 Defining Variables-cont
Rules for Variable Names: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.
>>N = namelengthmaxN =
63
15
1.2 Defining Variables-cont1.2 Defining Variables-contRules for Variable Names-cont:Making Sure Variable Names Are Valid.
(Using: isvarname function). Ex: >>isvarname 8thColumn ans = 0
Matlab Variables Names Legal variable names:• Should not be the name of a built-in variable, built-in function, or user-defined functionExamples:xxxxxxxxxpipeRadiuswidgets_per_boxmySummysum
16
1.2 Defining Variables-cont1.2 Defining Variables-cont
Important commands:clc => Clear the command window clear or clear variables => clears all variables from the workspace.Delete => Delete files .quit => Terminates MATLABwho, whos =>List a directory of variables currently in memory. Lists the current variables, their sizes, and whether they have nonzero imaginary parts.Lookfor => search toolSave =>command saves variables from the workspace to a named file Load => recover Data
17
1.2 Defining Variables-cont1.2 Defining Variables-contLooking for Functions
Syntax:
lookfor string
searches first line of function descriptions for “string”.
Example:
>> lookfor cosine
produces
ACOS Inverse cosine.
ACOSH Inverse hyperbolic cosine.
COS Cosine.
COSH Hyperbolic cosine.
18
1.2 Defining Variables-cont1.2 Defining Variables-cont
Example:» a=5;» A=7.9;» aa = 5» AA = 7.9000» clc» who
19
1.3 Functions(1.3 Functions(Built-In Built-In Functions)Functions)
» Except for basic commands such as addition, subtraction, multiplication and division, most MATLAB commands are functions. Functions usually require an input argument (such as x above) and they return value.
A) Trigonometric FunctionsThose known to Matlab are sin, cos, tan and their arguments
should be in radians. e.g. to work out the coordinates of a point on a circle of
radius 5 centered at the origin and having an elevation 30o = pi/ 6 radians:
>> x = 5*cos(pi/6), y = 5*sin(pi/6)x = 4.3301y = 2.5000
20
1.3 Functions(1.3 Functions(Built-In Built-In Functions)Functions)
A) Trigonometric Functions-contThe inverse trig functions are called asin, acos, atan (as opposed
to the usual arcsin or sin-1etc.). The result is in radians.
>> acos(x/5), asin(y/5)ans = 0.5236ans = 0.5236>> pi/6ans = 0.5236
B) Other Elementary FunctionsThese include sqrt, exp, log, log10…..etc.
21
1.4 Display 1.4 Display FormatsFormats
Values are displayed with MATLAB i n several ways.
Matlab command Display Comments
Format short 3.1416 default
Format long 3.14159265358979 16 digit
Format short e 3.1416e+000 5 digit plus exponent
Format long e 3.14159265358979e+000
16 digit plus exponent
Format bank 3.14 2 decimal places
Format + + positive
Format rat 355/113 ratio
Format hex 400921fb54442d18 hexadecimal
22
1.5 Saving the Variables Stored in 1.5 Saving the Variables Stored in MemoryMemory
Suppose a large number of variables are defined. You need to quit using MATLAB f o r the moment, but you would
like to use these variables in the future.
This can be done in two ways:
1. Use the MATLAB menus and use the File and Save Workspace As menu selections.
2. Or you can use the MATLABSAVE command.
23
1.5 Saving the Variables Stored in 1.5 Saving the Variables Stored in MemoryMemory
Example:» a=l;» b=2;» c=3;» d=4;» e=5;» f=6;» g=7;» who
» saveSaving to: mat lab. mat
%To see that we can restore the variables, let's clear the workspace:
24
1.5 Saving the Variables Stored in 1.5 Saving the Variables Stored in MemoryMemory
Example-cont:» clear» whoYour variables are:No variables are in memory.
%Now let's use the LOAD command to load the default file, matlab.mat, and restore the variables:
loadLoading from: matlab.mat» who
25
1.5 Saving the Variables Stored in 1.5 Saving the Variables Stored in MemoryMemory
Example-cont:%If you wish to save the variables in a file with a different name, you
can use the LOAD and SAVE commands followed by a file name » save xyzzy
%Let's clear the workspace and restore the variables using file xyzzy.» clear» whoYour variables are:No variables are defined.%To load the variables saved in file xyzzy, use the LOAD command
with the file name:
» load xyzzy» who
26
1.5 Saving the Variables Stored in 1.5 Saving the Variables Stored in MemoryMemory
Example-2:» a=5;» A=7.9;» aa = 5» AA = 7.9000» clc» who
27
Example-cont:» save A a (A: File name a: variable to be saved)» clear Now list the variables stored in memory:» whoYour variables are:Now no variables are listed.»load A» whoYour variables are: As X
1.5 Saving the Variables Stored in 1.5 Saving the Variables Stored in MemoryMemory
28
» Pure imaginary and complex numbers are expressed in MATLAB by the letters i or j. Both i and j are defined as . If we take the square root of -1, MATLAB displays a number containing the letter i. The MATLAB SQRT function calculates the square root of a number.
» sqrt(-1)ans = 0 + 1. 0000i
1.7 Complex Numbers1.7 Complex Numbers
Real part.
Imaginary part.
29
MATLAB automatically handles calculations with complex numbersExamples:» (1+2i)/(3+Si)ans = 0.3824 + 0.0294i» a=3+4i;» b=l+i;» a*aans = -7.0000 +24.0000i» a-bans = 2.0000 + 3.0000i» a+bans = 4.0000 + 5.0000i
1.7 Complex Numbers1.7 Complex Numbers
30
Unit Imaginary Numbersi and j are ordinary Matlab variables pre-assigned with the value √−1.>> i^2ans = -1Both or either i and j can be reassigned>> i = 5;>> t = 8;>> u = sqrt(i-t) (i-t = -3, not -8+i)u = 0 + 1.7321i>> u*uans = -3.0000
1.7 Complex Numbers1.7 Complex Numbers
31
1.7 Complex Numbers1.7 Complex Numbers
32
1.7 Complex Numbers1.7 Complex NumbersFunctions for Complex ArithmeticExamples:
Remember: There is no “degrees” mode in Matlab. All angles are in radians.
33
MATLAB can store several numerical values in a single variable. For most of the text, we'll refer to these variables as arrays. MATLAB however, treats these variables as either matrices or arrays.
In MATLAB the default uses matrix algebra rather than array operations. Array operations are defined as element-by-element operations.
1.8 Matrices and Vectors1.8 Matrices and Vectors
matrix algebra operators+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
Array operators.* element-by-element multiplication
./ element-by-element divsion
.^ element-by-element power
.‘ transpose
34
1.8 Matrices and Vectors1.8 Matrices and VectorsIn this section we will use the terms matrix and vector.A vectoris a matrix with one row (a row vector) or one column (a column vector).
Row VectorsA row vector is an 1-by-n matrix so the number of rows is always one. The number of columns can be any integer value except one.
Column VectorsA column vector is an n-by-1 matrix so the number of columns is always one. The number of Rows can be any integer value except one.
35
1.8 Matrices and Vectors1.8 Matrices and Vectors
ScalarsAny single element or numerical value. Or said other way, any vector or matrix that has one row and one column. (Its size is equal to 1,1.)
Square MatricesAny matrix that has the number of rows equal to the number of columns (m = n).
In MATLAB matrices and vectors are created using square brackets [ ]. Rows are separated by the semicolon character (;).
36
1.8 Matrices and Vectors1.8 Matrices and Vectors
• Vectors (arrays) are defined as• >> v = [1, 2, 4, 5]• >> w = [1; 2; 4; 5]
• Matrices (2D arrays) defined similarly• >> A = [1,2,3;4,-5,6;5,-6,7]
37
1.8 Matrices and Vectors1.8 Matrices and Vectors
1.8.1 Matrix MultiplicationMatrices are multiplied by using the * operator:Example:
» c=A*B
» c2=B*A
» d=5*A matrix by a scalar
38
1.8 Matrices and Vectors1.8 Matrices and Vectors
1.8.2 Matrix Addition and SubtractionExample:
» q=A-B q= -8 - 6 -4 -2 0 2 4 6 8
1.8.3 The Inverse of a Matrix
39
1.8 Matrices and Vectors1.8 Matrices and Vectors
1.8.4 The Determinant of a MatrixExample:
1.8.5 Solving Systems of Equations
» det(B)ans = 0
In matrix notation, we write this system of equations as Ax =b where
40
1.8 Matrices and Vectors1.8 Matrices and Vectors
1.8.5 Solving Systems of Equations
We now solve for x using A-1*b.» x=inv(A)*bx = 1.2921 -0.2141 -1.3206
41