Upload
creda
View
52
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Introduction to MATLAB. INGE3016 Algorithms and Computer Programming With MATLAB Dr. Marco A. Arocha oct 25, 2007; june 12, 2012. Some facts:. MATLAB MATrix LABoratory Matrix mathematics >1000 functions. Advantages Ease of use Platform independent Predefined functions Plotting - PowerPoint PPT Presentation
Citation preview
1
Introduction to MATLAB
INGE3016 Algorithms and Computer Programming With MATLABDr. Marco A. Arochaoct 25, 2007; june 12, 2012
2
Some facts: MATLABMATrix LABoratory Matrix mathematics >1000 functions
3
Some factsAdvantages Ease of use Platform independent Predefined functions Plotting Graphical User
Interface Compiler
Disadvantages Interpreted language Slower Expensive
Matrix & Array OperatorsScalar & Matrix Array
Addition + before .+ now +
Subtraction - before .- now -
Multiplication * .*Division / and \ ./ and .\Exponentiation ^ .^Modulus mod(x,y) mod(x,y)
4
To associate expressions use “( )”, i.e., regular parentheses. Do no use brackets “[ ].”
Do not use “( )” or “.” or “x” to mean multiplication.
5
Examples>> 2+3-2*4 <E>% note the precedence orderans = -3The division operators:>> 6/2 <E> % numerator/denominator
ans = 3>> 2\6 <E> % denominator/numerator
ans = 3
6
Rules to construct variable and file names:
uppercase letters: A-Z (26 of them) lowercase letters: a-z digits: 0-9 underscore _ first must be a letter any length, first 63 are significant (if more than
63 the rest will be ignored)
7
Rules to construct variable and file names:
No blank spaces within a name case sensitive, unless instructed otherwise by the case
function (i.e., case off) This rules must be extended to the construction of
MATLAB file names as file names can become variables
filename.m
Same rules as variable name
8
All variables are arrays The unit of data in MATLAB is the array A MATLAB variable is a region of memory
containing an array Array is a collection of data organized into
rows and columns and known by a single name
9
Common Library Functions & Parameters
Mathematics MATLAB Math & MATLAB
sqrt(x) sin(x)
ln(x) log(x) cos(x)
log10(x) log10(x) tan(x)
ex exp(x) asin(x)
xy x^y acos(x)
|x| abs(x) atan(x)
, 3.14159… pi
x
10
Common MistakePlease code in MATLAB the following
Correct: y=3*x*exp(x^2)-1
Incorrect: y=3*x*e^(x^2)-1Incorrect: y=3*x*exp^(x^2)-1
132
xxey
11
Scientific Notation Math: 1x10-3 Matlab: 1e-3 (correct) Matlab: 1*10^-3 ( accepted by MATLAB but not accepted by the instructor;
student using this approach denotes lack of knowledge of the scientific notation)
Common Mistakes: 1xe-3 10e-3 1e^-3 1e*-3 1*e-3
12
Assignment Statement The Syntax:
Variable Name = Expression
The assignment statement operates assigning the value of the right-hand side expression to the left-hand side variable.
13
Examplea=1;b=2;c=a+b; % c=3
Note: a mistake is to write a + b = c which is wrong as the compiler cannot assign the value of c
to a variable named a+b.
14
Examplea=1;a=a+1; % the new value of a in the LHS is 2
Think of the last statement as:
1;aa valueoldthevaluenewthe
15
Quiz, your first algorithm
Write a piece of program that switches the value of a and ba=1;b=3;……fprintf(‘a=%d, b=%d’, a, b);
Your statements
Output should be:
a = 3, b = 1
16
Quiz, your first algorithm
Write a piece of program that switches the value of a and ba=1;b=3;a=b;b=a;fprintf(‘a=%d, b=%d’, a, b);
Student first approach, is it right?
Output should be:
a = 3, b = 1
17
Quiz, apply your knowledge
Given: a=1; b=3; c=5;
Transfer the values of a c b a c b
18
Multiple Statements
>>x=1; y =2; % or>>x=1, y=2; multiple assignment statements can be
placed on a single line separated by semicolons or commas
19
clear; clc; <ctrl><c>
Commands to manage the work session in the Command Window clear;
remove the values of all variables from memory clear is short for clear all
clc; clears the Command Window but the values of the variable
remains [also: MATLAB edit menu: EditClear Command Window]
<ctrl><c>
stops program execution and return to editing phase
20
semicolon (;) commandIf an assignment statement is typed without the semicolon at the end, the results of the statement are automatically displayed in the command window:
>> x = 5*20 % statement without the colonx = 100
Displaying partial results is an excellent way to quickly check your work (debugging), but it slows down the execution of a program. Recommendation: leave off the semicolon while debugging and use it after the program is bugs-free.
21
The array unitUnder the array unit in MATLAB we can store: Scalar
1x1 array
Vectors: 1-D arrays Column-vector: m x 1 array Row-vector: 1 x n array
Multidimensional arrays m x n arrays Also called matrices One or more rows by one or more columns
22
Scalars, Vectors, Matrices Scalars are array with only one row and one
column a = [3.4] a = 3.4
a is a 1x1 array (a scalar) containing the value 3.4 Brackets are optional in this case and usually we don’t use it
for 1x1 array The only element is a(1) with a value of 3.4
Both are valid
23
Initializing 1-D arrays (vectors) Vectors are one-dimension either row-vectors or column-vectors Values are listed using brackets [ ] Blank spaces or commas can be used to separate values
Row vectors:>> prime=[2 3 5 7 13]prime = 2 3 5 7 13>> prime=[2, 3, 5, 7, 13]prime = 2 3 5 7 13
Two choices for Array assignmentUse either one
Memory
Row vectors:>> prime=[2, 3, 5, 7, 11, 13]prime = 2 3 5 7 11 13
The elements of an array are identified by indices starting with 1 With arrays pay attention to indices and values, they are not the same Each value is stored in memory in the order listed as:
prime(1)=2prime(2)=3prime(3)=5prime(4)=7prime(5)=11prime(6)=13
Array elements’ indices always start in one
indices values
25
Retrieving array elementsEach element can be retrieved one by one or all at once:
>> prime(1) <E>ans = 2>> prime(2) <E>ans = 3…>> prime(6) <E>ans = 13>> prime <E>prime = 2 3 5 7 11 13
26
Manipulating arrays
with individual elements:
>> prime(1)*prime(2)ans = 6>> prime(3)^2ans = 25>> log(prime(1))ans = 0.6931
Or with the whole array:
>> x=prime+1x = 3 4 6 8 14>> z=prime-2z = 0 1 3 5 11>> y=x+zy = 3 5 9 13 25>> m=x.*ym = 9 20 54 104 350
prime(1)=2prime(2)=3prime(3)=5prime(4)=7prime(5)=13After you have initialized prime all values are in memory
and we can perform operations
27
Clearing array values We can clear all the values previously entered
with the clear function>> clear prime
If we try to retrieve the values of prime after using clear prime, an error message is found
>> prime(1)
??? Undefined function or variable 'prime'.
28
Column vectors: Rows can be separated by
semicolon or new lines
>> b = [3; 2; 1] <E>>> b= [3 <E>
2 <E> 1] <E>
b is a 3 x 1 array (or simply a column-vector)
3
2
1
b
Transpose operator(‘)transpose a row-vector into a column-vector and vice verse
>> x=[1 2 3]’ x = 1 2 3
>> x=[1 ;2; 3]’
x = 1 2 3
29
• Transpose a column vector into a row vector• Transpose a row vector into a column vector• MATLAB displays row vectors horizontally and column vectors vertically• In the examples, changes are permanent, i.e., x changed form row to
column and from column to row not just on the printed output.
30
Colon Operator (:)
The colon operator (:) can generate large row vectors of regularly spaced elements.
>> x = [first:incr:last]first = first valuelast = last valueincr = increment, if omitted, the increment is 1
Ex
>> x = [0:2:8]x =
0 2 4 6 8
memory:x(1)=0x(2)=2x(3)=4x(4)=6x(5)=8
31
Colon Operator, examples>> x = [0:2:6]x = 0 2 4 6
>> u =[10:-2:4]u = 10 8 6 4
>> y = [1:1:4]' % combines the colon and transpose operatorsy = 1 2 3 4
Que sería la vida sin “:”
(1) x = [0 2 4 6 8]
(2) j=1;for ii=0:2:8
x(j)=ii;j=j+1;
end% j is the index generator% ii is the values generator
(3)j=1;x(j)=0;for j=2:1:5
x(j)=x(j-1)+2;end% j generates both: % indices and values
32
Tres ejemplos para inicializar x con otros métodos diferentes al operador “colon” y lograr en memoria: x(1)=0 x(2)=2 x(3)=4 x(4)=6 x(5)=8
33
QUIZ Using the Colon operator, calculate the
values of x from 1 up to 3 in increments of 0.1, (Application on the Trapezoidal integration rule)
34
linspace function: The linspace (short for linear space) function
creates a linearly spaced row vector, but instead you specify the number of values rather than the increment.
Syntax: linspace(first, last, pts.)
where: first= first valuelast= last valuepts.= number of points
35
linspace, exampleProblem: Want to produce the following values:
5.0 5.1 5.2 5.3 5.4 5.55.65.7 5.8 5.9 6.0
first value
last value
11 points x=linspace(5, 6, 11)
linspace, effect in memory Could you tell what is the effect in memory for the
linspace(5,6,11) instruction?
R 1-D array (row-vector) with 11 elements:
... linspace(5,6,11) is equivalent to x =[5:0.1:6]
36
5.0 5.1 5.2 5.3 5.9 6.0
37
Compare colon operator with linspace function
a= first valueb= last valuen= number of points -1 (=panels number, integration rule)
h=(b-a)/n = increment
x=[a:h:b] % orx=linspace(a,b,n+1)
Equivalent instructionsBoth produce n+1 elements of xBoth produce row-vectors
Compare colon operator with linspace functionx=[2,4,6,8,10,12,14,16,18,20];
a) Colon Operator x=[2:2:20];
b) linspace function x=linspace(2,20,10);
38
x=[a:h:b]x=linspace(a,b,n+1)
h=(b-a)/n
39
Data Types & Variable Declaration
Most common data types (default): double char
double means double precision 15-16 significant-digit variables automatically created whenever a numerical value
is assigned to a variable name.
40
char variables & strings Variables of type char consist of :
scalars (one character) or arrays (many characters),
(char arrays are most commonly called strings) Example:
cheo=‘x’ % one character pepe = ‘This is a character string’ % many characters
pepe is a 1x26 character array.
Strings are character arrays containing more than one character
41
Variable initialization
Three common ways to initialize a variable in MATLAB:
Assign data to the variable in an assignment statement
Input data into the variable from the keyboard (input function)
Read data from an external file
42
Initializing Variables with Keyboard input function>> x = input('Enter an input value = ') <E>
Output in the Command Window:>> Enter an input value = 5 <E>
x = 5Effect in Memory? x(1)=5
user writes 5 and <E>
43
Initializing Variables with Keyboard input function>>x = input('Enter an input value = ')
Output:>>Enter an input value = [1,2,3] <E> x = 1 2 3
Effect in Memory?x(1)=1; x(2)=2; x(3)=3
user writes [1,2,3] and <E>
44
Initializing Variables with Keyboard Input>>x = input('Enter an input value = ')<E>
Output in the Command Window:>> Enter an input value = [1 2; 3 4] <E>
x = 1 2 3 4
Effect in memory: 2x2 array with elements
x(1,1)=1 x(1,2)=2x(2,1)=3 x(2,2)=4
45
Initializing Variables with Keyboard Input>> x = input('Enter an input value = ')<E>
Output in the Command Window:>>Enter an input value = [1;2;3;4] <E>x = 1 2 3 4
Effect in memory: column vector with elements:
x(1)=1x(2)=2x(3)=3x(4)=4 Also could be a 4x1
2-D array with elements:
x(1,1)=1x(2,1)=2x(3,1)=3x(4,1)=4
46
Initializing Variables with Keyboard Input
>>x = input('Enter an input value = ') <E>
Output in the Command Window:>>Enter an input value = ‘Albert Einstein’<E>x =
Albert Einstein
Effect in memory: 15 elements with character values:
x(1)=’A’x(2)=’l’x(3)=’b’x(4)=’e’x(5)=’r’x(6)=’t’x(7)=’ ‘ (i.e., nada)x(8)=’E’x(9)=’i’x(10)=’n’x(11)=’s’x(12)=’t’x(13)=’e’x(14)=‘i’x(15)=’n’
You write this input
47
Initializing Variables with Keyboard Input The data type of the variable is decided
during the execution by typing a particular value: an scalar or an array within brackets, or a string within quotes and then <enter>
48
Initializing Variables with Keyboard Input ‘s’ (meaning string) as a second input parameter,
then the data returned is a character string. Note the difference in syntax with previous instruction:
>>x = input('Enter an input value = ', 's')
Output in the Command Window:>>Enter an input value = Albert Einstein <E> ( NO
quotes)x =
Albert Einstein
49
2D Arrays (Matrices)
Matrices are arrays with two or more dimensions Their size is specified by the number of rows
and columns (rows first) Number of elements =row x column Reference an array, two forms:
a(2,1) address an individual element, by identifying the row and column
a without parenthesis address the whole array
2D Arrays (matrices)
50
1 2 3
5 64
a(1,1) a(1,2) a(1,3)
a(2,1) a(2,2) a(2,3)
a= [1,2,3; 4, 5, 6]; a= [1,2,3; 4,5,6];
Two syntax methods to initialize:
a is a 2 x 3 array
Rows can be separated by semicolon or new lines
Example of operations:
>>a(1,2)*a(1,3)ans
6
>>a.*aans 1 4 9 16 25 36
51
Initialization Example The number of elements in every row of an
array must be the same:a= [1 2 3; 4 5] % produces error
a= 123 not allowed 45
[ ] is an empty array
52
Relational Operators
six operators:<, less than<=, less than or equal to>, greater than>=, greater than or equal to==, equal to~=, not equal to
two results: false (zero, 0) true (one, 1; in general any number different than
zero)
6 operators
53
a>b, example:
conditionalexpressions
true ≠0 (usually =1)
false=0
54
Example with scalars Let
a=5; b=3 ; c=6 ; d=8;
Find the value of a>b c>d
55
Relational Operators with Arrays comparison occurs on an element-by-element basis arrays being compared must have the same dimensions resulting array has the same dimensions as the operators
>> x=[6,3,9];>> y=[14,2,9]; % three conditions:>> z=(x<y) % x(1)<y(1)6<14z = % x(2)<y(2)3<2 1 0 0 % x(3)<y(3)9<9
• 3 results• set is a logical
array
Relational Operators with Arrays>> x=[6,3,9];>> y=[14,2,9];
>> z=(x>y)z = 0 1 0>> z=(x~=y)z = 1 1 0>> z=(x==y)z = 0 0 1
56
results are logical arrays
57
Relational Operators with Arrays
All the elements of an array can be compared to an scalar. Example:
>> x=[6,3,9];
>> z=(x>8)z = 0 0 1
58
Relational Operators with Arrays PrecedenceThe arithmetic operators +, -, *, /, and \ have precedence over the
relational operators
Exercise:Suppose that x =[-5, -4, 7, 8, 9] and y=[-3, -4, 9, 8, 7]. What is the
result of the following operations? Use MATLAB to check your answers.
z = (x < y)z = (x > y)z = (x ~= y)z = (x == y)z = (x > 8)z = 5 > 2 + 7z = 5 > (2+7)z = (5>2) +7
59
Logic OperatorsOperator Operation
& Logical AND
&& Logical AND with shortcut evaluation
| Logical OR
|| Logical OR with shortcut evaluation
xor() Logical Exclusive OR
~ Logical NOT
60
& True TableCond1 & Cond2 Result
T & T T
T & F
F & T
F & F
Expressions containing ‘and’ are true only if both conditions are true
Both scalar and array values
61
&& True TableCond1 Operator Cond2 Result
T && T T
T && F
F && T
F && F
Expressions containing ‘and’ are true only if both conditions are true
Scalar values ONLY, With shortcut evaluationIn 3rd and 4rd rows Cond2 is not evaluated
62
| True TableCond1 Operator Cond2 Result
F | F F
T | F
F | T
T | T
Statements containing ‘or’ are false when both conditions are false.
Both scalar and array values
63
|| True TableCond1 Operator Cond2 Result
F || F F
T || F
F || T
T || T
Statements containing ‘or’ are false when both conditions are false.
Scalar values only, Shortcut evaluation
64
xor() True TableCond1 Cond2 xor(cond1,cond2)
ResultF F F
T F T
F T T
T T F
Statements containing ‘xor’ are false when both conditions are true or false.
Scalar values only
65
~ True Table~ Cond result
~ T
~ F
66
Example with scalars Let
a=5; b=3; c=6; d=8;
Find the value of (a>b) & (c>d) ((5>3) and (6>8))
67
Example with scalars Let
a=5; b=3; c=6; d=8;
Find the value of (a>b) | (c>d) ((5>3) or (6>8))
68
Example with scalars Let
a=5; b=3; c=6; d=8; Find the value of
~( (a>b) && (c>d)) ~ ((5>3) and (6>8))
69
a<x<b MATLAB, two choices: x>a & x<b (common programming syntax) a<x<b
70
Logical Expressions:a=1, b=2, c=3, d=4
if b>a & d >bfprintf(‘Hello World’);
elsefprintf(‘sorry I am busy’);
end
a=1, b=2, c=3, d=4
if d>b >afprintf(‘Hello World’);
elsefprintf(‘sorry I am busy’);
end
71
Example with arrays
>> x=[6,3,9];>> y=[14,2,9];>> z=~xz = 0 0 0>> z=~x>yz = 0 0 0>> z=~(x>y)z = 1 0 1
72
Example with arrays Consider the following:x = [1, 2, 3, 4, 5];y = [-2, 0, 2, 4, 6];z = [8, 8, 8, 8, 8];
The statement: z>x & z>y (reads z is greater than x and z is greater than y) returns ans = 1 1 1 1 1 because z is greater than both x and y for every element. This
result should be interpreted to mean that the condition is true for all the elements.
73
Example: Consider the following: x = [1, 2, 3, 4, 5]; y = [-2, 0, 2, 4, 6]; z = [8, 8, 8, 8, 8];
The statement: x>y | x>z (reads x is greater than y or x is greater than z) returns ans = 1 1 1 0 0 This result should be interpreted to mean that the condition is
true for the first three elements and false for the last two.
74
Control Structures
Three fundamental control structures in computer programming:
Sequential Selection Repetition
75
SEQUENCIAL
In this structure each statement is executed only once, from top-to-bottom sequentially (i.e., the second statement goes after the first, the third after the second, and so on.)
The sequential structure does not require additional statements as we already covered it.
76
Selection Structure: MATLAB has three if structures
if conditionstatements
end
if condition-1stats-1elseif condition-2
stats-2…elseif condition-nstats-nelsestats-n+1end
% elseif is one word
if conditionstatements-1
elsestatements-2
end
Allows program flows to run into one of several choices
77
if Example
x = 5;if x>=5
x = x +1;
endfprintf(‘x=%d’,x); No semicolon
True or False?
What if x = 6?What if x = 1?
indentation
78
if Example
x=3;if x>=5 x = x+1;else x = x-1;endfprintf(‘ x = %d’, x);
one of these two is executed, but not both
79
%ng=numerical grade
ng=input(‘enter ng \n’);
if ng>=90 fprintf(‘student got A’); elseif ng>=80 fprintf(‘student got B’); elseif ng>=70 fprintf(‘student got C’); elseif ng>=60 fprintf (‘student got D’); else fprintf(‘student got F’); end
ExampleMultialternative if
first true condition is executed, the rest ignored
each false condition carries on information to the following conditions
80
Example
% ng = numeric grade */ ng=input(‘enter ng \n’);
if ng>=90 fprintf(‘student got an A’);endif ng<90 & ng>=80 fprintf(‘student got a B’);endif ng<80 & ng>=70 fprintf(‘student got a C’);endif ng<70 & ng>=60 fprintf (‘student got a D’);endif ng<60 fprintf(‘student got a F’);end
independent if statements
all true conditions are executed
The previous solutioncan be implemented w/ independent if statements
Each if-block doesn’t carry information to the next condition, therefore conditions need a range for each grade
81
com
pare
%ng=numerical gradeng=input(‘enter ng \n’);
if ng>=90 fprintf(‘student got A’); elseif ng>=80 fprintf(‘student got B’); elseif ng>=70 fprintf(‘student got C’); elseif ng>=60 fprintf (‘student got D’); else fprintf(‘student got F’); end
% ng = numeric grade ng=input(‘enter ng \n’);
if ng>=90 fprintf(‘student got an A’);endif ng<90 & ng>=80 fprintf(‘student got a B’);endif ng<80 & ng>=70 fprintf(‘student got a C’);endif ng<70 & ng>=60 fprintf (‘student got a D’);endif ng<60 fprintf(‘student got a F’);end
Discuss differences of the two solutions
82
Flow Charts
83
More examples with if statements: The Trapezoidal rule
)2...22()2/1( 1321 nn fffffhI
n = number of panels
84
Example(*), Trapezoidal ruleacc=0;for ii=1:1:n+1 if ii==1 c(ii)=1.0; elseif ii==n+1 c(ii)=1.0; else c(ii)=2.0; end fx(ii)=tanh(x(ii))^2;
term(ii)=c(ii)*fx(ii); acc=acc+term(ii);
end
This assumes that x(ii) has been computed before
(*) This assumes that the Trapezoidal rules was sent as computer project
85
Example Trapezoidal rule, version 2
acc=0;for ii=1:1:n+1 if ii==1| ii==n+1 % note the logical operators c(ii)=1.0; else c(ii)=2.0; end
fx(ii)=tanh(x(ii))^2; term(ii)=c(ii)*fx(ii);
acc=acc+term(ii);end
This assumes that x array has been computed before
86
More examples with if statements: Simpson 1/3 rule
1 2 3 4 1(1/ 3) ( 4 2 4 ... 4 )n nI h f f f f f f
87
Example, Simpson 1/3 ruleacc=0;for ii=1:1:n+1 if ii==1 | ii==n+1 c(ii)=1; elseif mod(ii,2)==0 c(ii)=4; else c(ii)=2; end
t(ii)=c(ii)*f(ii); acc=acc+t(ii);end
Assuming f has been previously computed