CHE 374 – Lec # 4 Introduction to MATLAB
MATLAB Basics
• Statements and Variables
CHE 374 Computational Methods • Matrices
in Engineering • Graphics
• Control of Flow
INTRODUCTION TO MATLAB
• Scripts and Functions
Why MATLAB MATLAB Interface – Look & Feel
• Combines numerics, graphics and programming
– Powerful
– Ease of use
• MATLAB toolboxes provides access to hundreds
of useful routines.
• Widespread use in engineering education
• Many subjects at UofA use MATLAB.
• The latest MATLAB provides powerful
programming features such as data structures
and cell arrays.
3 4
Computational Methods in Engineering 1
CHE 374 – Lec # 4 Introduction to MATLAB
Statements and Variables
Statements and Variables
Entering and displaying a matrix A
>> A =[1 3; 7 9]
A=
1 3
7 9
Semicolon suppresses output:
>> A=[1 3; 7 9];
>> A=[1 3; 7 9]
A=
1 3
7 9
>>
5 6
Vector representation Statements and Variables
MATLAB operators
• A vector can be >> vecrow = [1 2 3 4]
+ addition
represented as a row or vecrow =
- subtraction
column. Space or * multiplication
1 2 3 4
comma makes a row, / division
semicolon makes a >> vecol = [1;2;3;4]
^ power
columns [ ] vecol = You can use MATLAB as a calculator:
• A row vector can be
changed to column 1 >> 19.2/8.5
2 To obtain help on arithmetic operation, type
vector by transpose, >> help arith
3 ans=
and vice versa. 4 2.2588
>>
If no assignment is made, the result is placed in the variable ans
7 8
Computational Methods in Engineering 2
CHE 374 – Lec # 4 Introduction to MATLAB
Variable names Predefined variables
pi inf i
MATLAB variables begin with a letter
The rest of the characters can be letters, digits,
>> z = 1 + 5*i
or underscore.
z=
This is the maximum length of a 1.0000+ 5.0000i
variable name allowed by
MATLAB >> inf
>> namelengthmax
ans =
ans=
Inf
63
>> 0/0
MATLAB is case sensitive.
Warning: Divide by zero
>> M = [1 3];
ans=
>> m = [5 7 9];
NaN
M and m are not the same
9
>> 10
Managing your workspace
Built-in elementary functions The function who lists the variables in the workspace.
>> who
Your variables are:
A M ans m z
The function whos lists the size and memory allocation of your
variables
>> whos
Name Size Bytes Class Attribute
A 2x2 32 double
M 1x2 16 double
ans 1x1 8 double
m 1x3 24 double
z 1x1 16 double complex
11 12
Computational Methods in Engineering 3
CHE 374 – Lec # 4 Introduction to MATLAB
Managing your workplace
The command clear can be used to remove variables from the Keeping track of your work session
workspace
>> clear A
>> who
Your variables are:
M ans m z
>>
Clear with no arguments deletes all your variables
>> clear
>> who
Your variables are:
>>
13 14
Output formats
The function format changes the precision of the output Output formats
Command Description Example Command Description Example
format short Fixed-point with 4>> 355/113 format short g Best of 5-digit fixed or >> 355/113
decimal digits ans = floating point ans =
3.1416 3.1416
format long Fixed-point with 15 >> 355/113 format long g Best of 15-digit fixed or >> 355/113
decimal digits ans = floating point ans =
3.141592920353983 3.14159292035398
format short e Scientific notation >> 355/113 format bank Two decimal digits >> 355/113
with 4 decimal ans = ans = 3.14
digits 3.1416e+000 format rat Rational >> pi
format long e Scientific notation >> 355/113 ans = 355/113
with 15 decimal ans =
digits 3.141592920353983e+00015 16
Computational Methods in Engineering 4
CHE 374 – Lec # 4 Introduction to MATLAB
Output formats Matrix Operations
>> help format >> A=[1 4; 6 6]; B=[3 -6; 9 0];
>> A+B
FORMAT Set output format. ans =
FORMAT with no inputs sets the output format to the default appropriate 4 -2
for the class of the variable. For float variables, the default is FORMAT 15 6
SHORT.
>> A*B
FORMAT does not affect how MATLAB computations are done. ans =
Computations on float variables, namely single or double, are done in
appropriate floating point precision, no matter how those variables are 39 -6
displayed. 72 -36
Computations on integer variables are done natively in integer. Integer >> b=[2;7];
variables are always displayed to the appropriate number of digits for the >> A*b
class, for example, 3 digits to display the INT8 range -128:127. ans =
30
54
FORMAT SHORT and LONG do not affect the display of integer variables.
……
17 18
Element-by-element array operation Colon notation :
correct To create a vector x with initial value xi, increment dx, and final
.* multiplication value xf, use the colon notation:
>> A.*B
./ division
.^ power x=[xi: dx : xf];
ans = Examples
-5
>> A=[1;2;3]; B=[-5;8;10]; 16
>> A*B >> n=1:6
30 n=
??? Error using ==> mtimes
Inner matrix dimensions must agree. >> A.^2 1 2 3 4 5 6
ans =
>> x=0:2:10
1 x=
4 0 2 4 6 8 10
9
19 Understanding the colon notation is essential.
20
Computational Methods in Engineering 5
CHE 374 – Lec # 4 Introduction to MATLAB
Graphics Line types and colours
Different line types, plot symbols and colours may be obtained
with PLOT (X,Y S) where S, is a 1, 2 or 3 character string made
from the following characters:
• Basic Plotting commands
y yellow . point
m magenta o circle
• Line attributes: line types and colours
c cyan x x-mark
r red + plus
• Plot enhancements
g green - solid line
b blue * star
• Using hold and subplot
w white : dotted line
k black -. dashdot
• Setting the axis limits: axis and zoom
line
-- dashed line
s square
21
d diamond 22
Plot example Adding tittle and axes labels
For example, the following makes a plot of x vs y using red stars
>> x=[0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0];
>> y=[0 4.91 7.97 9.89 11.08 11.83 12.30 12.59 12.78 12.89 13.01];
>> title (‘text’) add title
>> plot (x,y,'r*-')
14
12
>> xlabel (‘text’) add xlabel
The side graph is nice, 10
but not useful. It >> ylabel (‘text’) add ylabel
8
doesn’t tell us
anything. We can 6 >> text(p1, p2, ‘text’, ‘sc’) puts ‘text’ at
make it more (p1,p2) in screen coordinates where (0.0, 0.0) is the
4
presentable by adding lower left corner and (1.0, 1.0) is the upper right
titles and labels
2
corner of the screen.
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
23 24
Computational Methods in Engineering 6
CHE 374 – Lec # 4 Introduction to MATLAB
Adding tittle and axes labels Axis changes, subplots, gridlines, hold and zoom
>> subplot divides the plot window
>> title ('This is my first graph')
>> xlabel ('time, seconds')
This is my first graph
>> ylabel ('velocity, m/s') 14 >> axis change axes
12
>> axis (‘equal’) equal aspect ratio
10
velocity, m/s
8
>> grid adds grid lines
6
4
>> hold allows you to make multiple plots
on the same subplot
2
>> zoom enables zoom (using the mouse)
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
time, seconds
NOTE: grid, hold and zoom operate like a “toggle” (successive
calls turn the property on or off)
25 26
Example of a simple plot
>> exact1 = @(t) 13.1*(1-exp(-
This is my first graph 0.75*t))
15
Approximate Solution
exact1 =
10 In the previous plot, we included a plot of a function
v e lo c ity , m /s
Exact Solution
@(t)13.1*(1-exp(-0.75*t))
5
>> hold on
% define an anonymous function
0
0 1 2 3 4 5 >> fplot (exact1, [0 5]) >> exact1 = @(t) 13.1*(1-exp(-0.75*t))
time, seconds
>> grid on >> fplot (@exact1, [0 5] ) % plot from t=0 to 5
>> title ('This is my first graph') >> grid on
>> xlabel ('time, seconds')
>> ylabel ('velocity, m/s')
>> gtext('Exact Solution')
>> gtext('Approximate Solution')
27 28
Computational Methods in Engineering 7
CHE 374 – Lec # 4 Introduction to MATLAB
Use of subplot Subplots
plot of (x-2)*sin(2*x)*exp(-0.2*x) vs x
>> x=0:1:10; 2
>> y =@(x) (x-2)*sin(2*x)*exp(-0.2*x); 1
>> y2=@(x) sin(2*x)*exp(-0.2*x);
0
y
>> subplot (2,1,1)
>> plot(x,y); -1
>> xlabel('x'); ylabel('y');grid; -2
0 1 2 3 4 5 6 7 8 9 10
>> title('plot of (x-2)*sin(2*x)*exp(-0.2*x) vs x'); x
plot of y/(x-2) vs x
>> subplot(2,1,2) 1
>> plot(x,y2); 0.5
>> xlabel('x'); ylabel ('y'); grid;
0
y
>> title('plot of y/(x-2) vs x');
-0.5
>>
-1
0 1 2 3 4 5 6 7 8 9 10
x
29 30
Flow Control – decisions If, elseif, end
31 32
Computational Methods in Engineering 8
CHE 374 – Lec # 4 Introduction to MATLAB
Flow control – Loops Flow control – Loops
Commands for loops
for and while
Examples : factorial >> %compute with while loop
>> % compute with for loop >> n=1;
>> Num=20; >> factorial = 1;
>> factorial=1; >> while (n < 20)
>> for n=1:Num n=n+1;
factorial = factorial * n; factorial = factorial * n;
end end
>> factorial >> factorial
factorial = factorial =
2.4329e+018 2.4329e+018
33 34
Scripts and Functions Script g=9.81;
MATLAB scripts and functions are called m-files because they have m=input(' mass (g): ');
MATLAB Script to implement k=0.015;
a suffix “.m” the algorithm for computing ti=0; tf=5; dt=0.5;
the velocity of a falling sphere vi=0;
Scripts are text files that contain a sequence of MATLAB commands
m = m/1000;
Functions are m-files that return values t = ti;
v = vi;
The biggest difference between scripts and functions is that h = dt;
variables created in functions are local variables, whereas variables while ( t <= tf)
created in scripts are global slope = g - (k / m ) * v;
v = v + slope * h
MATLAB toolboxes are a collection of useful m-files. t = t + h;
end
Writing scripts and functions makes easier and more efficient to disp(‘Velocity (m/s):’)
use MATLAB. disp (v)
35 36
Computational Methods in Engineering 9
CHE 374 – Lec # 4 Introduction to MATLAB
function
Following is a function which does the same thing as the script.
Miscellaneous commands
function vel = fun(dt,ti,tf,vi,m,k) To run the script,
g = 9.81; %gravitational const. type at the
t = ti; %set t to start time command prompt
v = vi; %set v to initial
h = dt; %set the time steps >> m=20e-3;
while (t <= tf) % loop until t> tf >> k=0.015;
slope = g -(k/m) * v; >> ti=0;
v = v + slope * h; >> tf=3.0;
t = t + h; >> vi=0;
end >> dt=0.1;
vel = v; >> fun(dt,ti,tf,vi,m,k)
end
37 38
Appendix1: MATLAB special characters
39
Computational Methods in Engineering 10