You are on page 1of 25

ESG

111
Numerical Methods for
Chemical Engineering Analysis
WEEK 3
Introduction to MATLAB Programming


Maya K Endoh

Lab Exercise (recommended)


Friday 11:45am 12:45pm
Old Engineering Building, room 236A
Supplement Session (C, C++)
Friday: 10:30am 11:30am
Old Engineering Building, room 236A
Oce Hour (TA)
Monday 3:00 pm 4:00 pm
Heavy Engineering Building, room 150
Tuesday 10:00 am 11:20 am
Old Engineering Building, room 236A
Adrian Hurtado: adrian.hurtado@stonybrook.edu
Mengna Zho: mengnan.zou@stonybrook.edu
Kuangyi Xu: kuangyi.xu@stonybrook.edu

Algorithms
An algorithm is the sequence of steps needed to
solve a problem
Modular program: Top-down design approach
to programming
break a soluRon into steps, then further rene each
one

Generic algorithm for many programs:


1. Get the input
2. Calculate result(s)
3. Display the result(s)

A modular program would consist of funcRons


that implement each step

How the Computer Program runs?


Compile
high-level language
(English, etc)

Source code


Interpret

high-level language
(English, etc)

Executed File

compiler

machine language
(FORTRAN, C, etc)


Translate from the source
code to object code

interpreter

Translate each command
line-by-line

Object Code

command and
operation

Script File

Scripts
Scripts are les in MATLAB that contain a sequence of
MATLAB instrucRons, implemenRng an algorithm
Scripts are interpreted (rather than compiled), and are
stored in M-les (les with the extension .m)
To create a script, click on New Script under the HOME
tab; this opens the Editor
Once a script has been created and saved, it is executed
by entering its name at the prompt
>>script1

Just enter the script name to run!

the type command can be used to display a script in


the Command Window
>>type script1

It shows the contents of the script le,


but wont execute the le

DocumentaRon
Scripts should always be documented using
comments, %
Comments are used to describe what the script does,
and how it accomplishes its task
Comments are ignored by MATLAB
Comments are anything from a % to the end of that
line; longer comment blocks are contained in
between %{ and %}
In parRcular, the rst comment line in a script is
called the H1 line; it is what is displayed with help

Help command Rp
If you comment in 2 lines,
block comment with %{ and %} will be displayed in
help command
If there is a blank line between the 2 lines, the only 1st
line will be displayed as H1 line
Script A

Script B

1
%This script is to demonstrate
2
%How the script file is executed
3 - radius=5
4 - area=pi*(radius^2)

1
%This script is to demonstrate
2
3
%How the script file is executed
4 - radius=5
5 - area=pi*(radius^2)

EX) H1 line
Script C

1 %{
2 This script is to demonstrate
3 How the script file is
executed
4 %}
5- radius=5
6- area=pi*(radius^2)

>> help scriptA


This script is to demonstrate
How the script file is executed

>> help scriptC


{

>> help scriptB


This script is to demonstrate

Input FuncRon
The input funcRon does two things: prompts
the user, and reads in a value
General form for reading in a number:
variablename = input(prompt string:_)

General form for reading a character or string:


variablename = input(prompt string:_, s)

Must have separate input funcRons, if more


than one input is desired!
input(prompt string:_)
prompt string,colon,space comma,s
will be added to read the characters

EX)

Input funcRon can be used to enter a vector,


>> vec=input('Enter a vector: ')


Enter a vector: [3 7 9 -1 13]
vec =
3 7 9 -1 13
>> vec=input('Enter a vector: ')
Enter a vector: 4:-2:-10
vec =
4 2 0 -2 -4 -6 -8 -10

Try it!

Input matrix

>> mat=input('this is your matrix: ')


this is your matrix: [1:3;4 7 2;7:-1:5]
mat =
1 2 3
4 7 2
7 6 5

Output FuncRon
There are two basic output funcRons:
disp, which is a quick way to display things
fprin4, which allows formalng
The fprin4 funcRon uses format strings which include place
holders; these have conversion characters:
%d integers
Species where the value of the
%f oats (real numbers)
expression that is aper the string is to be
printed
%c single characters
%s strings
Use %#x where # is an integer and x is the conversion character
to specify the eld width of #
%#.#f species a eld width of # and the number of decimal
places of #
%.#x species just the number of decimal places (or characters in
a string); the eld width will be expanded as necessary

Formalng Output
Other formalng:

\n : newline character

(the output which follows aper \n moves down to the next line)

\t : tab character
lep jusRfy with - e.g. %-5d
to print one slash: \\
to print one single quote: (two single quotes)

\n should be wriren at the end of an fprin;


statement, otherwise the next prompt would be
displayed in the same line as the output
PrinRng vectors and matrices: usually easier with
disp

Examples of fprin4
Expressions aper the format string ll in for the place
holders, in sequence
>> fprintf('The numbers are %4d and %.1f\n', 3, 24.59)
The numbers are
3 and 24.6

It is not the case that every fprin4 statement prints a


separate line; lines are controlled by prinRng \n; e.g.
from a script:
fprintf('Hello and')
fprintf(' how \n\n are you?\n')

would print:
Hello and how
are you?
>>

In Command Window

>> fprins('Hello and')


Hello and>> fprins(' how \n\n are you?\n')
how

are you?
>>

PrinRng Vectors and Matrices


The conversion character and the newline
character are in the format string, the vector will
be printed in a column and the matrix will be
unwound column by column
Without \n, it would print in a row, but >> will appear
on the same line
Separate \n can be entered in script in order to
display the vector in a row

disp funcRon is berer to display in a


straighsorward manner

EX) fprins vs disp


>> fprintf('%.1f', mat)
9.61.69.79.64.98.01.44.29.2>>
>> fprintf('%.1f ', mat)
9.6 1.6 9.7 9.6 4.9 8.0 1.4 4.2 9.2 >>
>> fprintf('%.1f\n', mat)
9.6
1.6
9.7
9.6
4.9
8.0
1.4
4.2
9.2

>> fprintf('%.1f %.1f %.1f\n', mat)


9.6 1.6 9.7
9.6 4.9 8.0
1.4 4.2 9.2
>> disp(mat)
9.6489 9.5717
1.5761 4.8538
9.7059 8.0028

1.4189
4.2176
9.1574

>> mat
mat =
9.6489
1.5761
9.7059

1.4189
4.2176
9.1574

9.5717
4.8538
8.0028

Scripts with I/O


General outline of a script with I/O:
1. Prompt the user for the input (suppress the output with ;)
*Rp* Use semicolons so that you control exactly what the execuRon
of the script looks like

2. Calculate values based on the input (suppress the output)


3. Print everything in a formared way using fprin4
(Normally, print both the input and the calculated values)

EX) Users target heart rate


Write the script that ask user to input the age
and output the target heart rate by using the
following equaRon;
target heart rate = (220-age) * 0.6

-Input assignment
-CalculaRon assignment
-Output assignment

Example SoluRon
thrscript.m

% Calculates a person's target heart rate


age = input('Please enter your age in years: ');
thr = (220-age) * 0.6;
fprintf('For a person %d years old,\n', age)
fprintf('the target heart rate is %.1f.\n', thr)
Note
Input result and the tusks (assignment statements) should be
suppressed by ;
The format of the output is controlled by the fprin4
statements.

Simple Plots
Simple plots of data points can be created using plot
To start, create variables to store the data (can store one or more point
but must be the same length); vectors named x and y would be common
or, if x is to be 1,2,3,etc. it can be omired
plot(x,y) or just plot(y)
The default is that the individual points are plored with straight line
segments between them, but other opRons can be specied in an
addiRonal argument which is a string
opRons can include color (e.g. b for blue, g for greeen, k for black,
r for red, etc.)
can include plot symbols or markers (e.g. o for circle, +, *)
can also include line types (e.g. -- for dashed)
For example, plot(x,y, g*--)

line types, plot symbols and colors


plot(x,y,s)
x: value at x-axis
y: value at y-axis
s: character string
If no color is specied,
makes automaRc use of
color order, which starts
with blue
If no maker type is
specied, plot uses no
marker.
If no line style is
specied, plot uses a
solid line.
EX) plot(x,y,'c+:')
plots a cyan dored line with a plus
at each data point

color

symbol (maker)

line type

blue

point

solid

green

circle

dored

red

x-mark

-.

dashdot

cyan

plus

--

dashed

magenta

star

(none)

no line

yellow

square

black

diamond

white

triangle(down)

triangle(up)

<

triangle(lep)

>

triangle(right)

pentagram

hexagram

Labeling the Plot


By default, there are no labels on the axes or Rtle on the plot
Pass the desired strings to these funcRons:
xlabel(string)
ylabel(string)
Rtle(string)

The axes are created by default by using the minimum and


maximum values in the x and y data vectors. To specify dierent
ranges for the axes, use the axis funcRon:
axis([xmin xmax ymin ymax])

Other Plot FuncRons


clf clears the gure window
gure creates a new gure window (can # e.g.
gure(2))
hold is a toggle; keeps the current graph in the
gure window
legend displays strings in a legend
grid displays grid lines
bar bar chart
Note: make sure to use enough points to get a
smooth graph

EX)
Plot the following (x, y) points in one graph
(1,1) (2,5) (3,3) (4,9) (5, 11) (6, 8)
In the Command Window, you may type
>> x=1:6;
>> y=[1 5 3 9 11 8];
>> plot(x,y)
>> plot(x,y,'r*')
>> plot(x,y,'r*-')
>> xlabel('x')
>> ylabel('y')
>> title('x and y plot')

Try to write the script to plot the above graph

Exercise
Write the script that creates two separate Figure Windows
and plot two separate y1, y2 vector values of y1=[2 11 6 9 3]
and y2=[4 5 8 6 2] against x=[1 2 3 4 5 6].
First, it clears the Figure Window
Then it creates x, y1, and y2 vectors.
In the rst Figure Window, just plot x vs y1 in bar graph
and add label for x, y axis and Rtle of x, y bar plot.
In the second Figure Window, plot y1 values as black lines
and plot y2 values as red circles. Add label for x, y axis,
legend and grid. Add the Rtle of x vs y1 & y2.

Exercise
Write a script that will calculate the volume of
a hollow sphere,
4
V
=
(r r )

3
Where ri is the inner radius and ro is the outer
radius. Assign a value to a variable for the inner
and outer radius
3
o

You might also like