Sei sulla pagina 1di 11

Prof. Dr. K.

nl; ENVE 404; METU

Computer Lab Exercise-3


Introduction to Basics of Matlab Part 2
PROGRAMMING WITH MATLAB
Two different types of m.files are distinguished by MATLAB:
-

script files: all variables are global


function files: all variables are local;

m.files
-

The commands are written in a text editor and saved with the ending .m
The commands are written like in the command line
All commands available in the command line can be used
(for loops if else, etc.. + self programmed functions)
All commands are processed line by line

Creating, saving and executing a Script File:


A script File is a user-created file with a sequence of MATLAB commands in it. The file must
be saved with a .m extension to its name, thereby, making it an m-file. A script file is
executed by typing its name (without the .m extension) at the command prompt.
We will create a script file to describe the exponential growth in a bacterial community with
an initial biomass X0 = 2 mg /L and a specific growth rate = 1 day-1.

exponential growth model:


This equation can be integrated to yield: X t X (t ) X o e t

Select New m-File from the File menu. A new edit window should appear.
Type the following lines into this file.

%this is a script m-file for ENVE 404 recitation example


% describes the exponential growth of biomass by X=Xo*exp(mu*t)
% where X is biomass concentration in mg/L
% mu is exponential growth rate in day-1
% t is time in day
Xo=2;
mu=1.0;
t=0:0.1:10;
X=Xo*exp(-mu*t);
plot(t,X);
xlabel('time (days)');
ylabel('Biomass,X (mg/L)');

Prof. Dr. K. nl; ENVE 404; METU

Select Save As from the File menu. A dialog box should appear. Type the name
of the document as growth.m. Make sure the file is being saved in the folder you
want it to be in (the current working folder/directory of MATLAB). Click to Save to
save the file.
Now get back to MATLAB and type the following commands in the command
window to execute the script file.

>> growth
If you want to use a different and/or different time, you can edit growth.m and execute
the script without re-writing all the steps!
Creating, saving and executing a Function File:
A function file is also a m-file, like a script file, except that the variables in a function file are
all local. A function file begins with a function definition line, which has a well-defined list of
inputs and outputs. Without this line, the file becomes a script file. The syntax of the
function definition line is as follows:
function[output variables]=function name(input variables);
where the function name must be the same as the filename (without the .m extension) in
which the function is written.
Example: The area, A, of a triangle with sides of length a, b and c is given by:
where

Write a Matlab function that will accept the values a, b and c as inputs and return the value
of A as output.
The main steps to follow when definig a Matlab function are:
Decide on a name for the function, making sure that it does not conflict with a name
that is already used by MATLAB. In this example the name of the function is to be area, so its
definition will be saved in a file called area.m
The first line of the file must have the format:
function [list of outputs]= function name(list of inputs)
For our example, the output area (A) is a function of the three variables (inputs) a, b and c so
the first line should read :
function [A] = area(a,b,c)
Document the function. That is, describe briefly the purpose of the function and how
it can be used. These lines should be preceded by % which signifies that they are
comment lines that will be ignored when the function is evaluated.
2

Prof. Dr. K. nl; ENVE 404; METU

Finally include the code that defines the function. This should be interspersed with
sufficient comments to enable another user to understand the processes involved.
The complete file might look like:
function [A] = area(a,b,c)
% Compute the area of a triangle whose sides have length a, b and c.
% Inputs: a,b,c: Lengths of sides
% Output: A: area of triangle
s = (a+b+c)/2;
A = sqrt(s*(s-a)*(s-b)*(s-c));

To execute the function file with a=10, b=15; c=20


>> A = area(10,15,20)
A=
72.6184
where the result of the computation is assigned to the variable area, A. The variable sused
in the definition of the function above is a local variable": its value is local to the function
and cannot be used outside (i.e. used only in the function named area to calculate A)
Exercise :
Write a function that outputs a conversion-table for Celsius and Fahrenheit temperatures.
The input of the function should be two numbers: Ti and Tf, specifying the lower and upper
range of the table in Celcius. The output should be a two column matrix: the first column
showing the temperature in Celcius from Ti to Tf in the increments of 1oC and the second
column showing the corresponding numbers in Fahrenheit. To do the following steps:

Create a column vector C from Ti to Tf with command C=[Ti:1:Tf]


Calculate the corresponding numbers in Fahrenheit using the formula F=9/5*C+32
Take transpose of C and F to get column vector C F
Concatenate C and F vectors to get final matrix with first column showing Celsius
degree and second column showing Fahrenheit degree

Function written as below:


% This function is written to convert Celsius to Fahrenheit temperature
function temptable=tempconvert(tinitial,tfinal);
% temptable is output which is a conversion-table for temperatures in
Celsius and Fahrenheit
% tinitial is input argument to specify the lower temperature in Celsius
% tfinal is input argument to specify the upper temperature in Celsius
C=[tinitial:10:tfinal];% creates row vector showing the temperature
% in Celsius from tinitial to tfinal in the increments of 10 degree Celsius
%On the Celsius scale, the freezing point of water is 0 degree Celsius
%and the boiling point 100 degree Celsius
%On the Fahrenheit scale, the freezing point of water is 32 degrees

Prof. Dr. K. nl; ENVE 404; METU

%Fahrenheit and the boiling point 212 degrees Fahrenheit


%therefore to convert Celsius to Fahrenheit use Fahrenheit=9/5*Celsius+32
F=9/5*C+32;% equation to convert Celsius to Fahrenheit
%To create conversion table showing the temperature in Celsius in the first
%column and the corresponding temperatures in Fahrenheit in the second
%column use transpose of C and F and then concatenate them.
temptable=[C' F'];

>> temptable=tempconvert(0,100)
temptable =
0
10
20
30
40
50
60
70
80
90
100

32
50
68
86
104
122
140
158
176
194
212

FLOW CONTROL
In M-files quite often commands or sequences of commands need to be executed under
certain conditions only. This can be easily programmed using the flow control keywords such
as if-end bloc, if-elseif-end bloc, for loop and while loop, that are available in matlab as in all
programming languages.
An if-end block basically consists of an if statement, a sequel part, and an end statement
categorizing the block. An if statement, having a condition usually based on the
relational/logical operator, is used to control the program flowthat is, to adjust the order
in which statements are executed according to whether or not the condition is met, mostly
depending on unpredictable situations. The sequel part consisting of one or more
statements may contain else or elseif statements, possibly in a nested structure containing
another if statement inside it.
IF:The general form of a simple if statement is
if relation
statements
end
The if-elseif-end block might replace a multiple if-elseif-..-end statement in a neat manner.

Prof. Dr. K. nl; ENVE 404; METU

A for loop makes a block of statements executed repeatedly for a specified number of times,
with its loop index increasing from i_0 to a number not greater than i_last by a specified step
(increment) or by 1 if not specified. The loop iteration normally ends when the loop index
reaches i_last, but it can be stopped by a break statement inside the for loop. The for loop
with a positive/negative increment will never be iterated if the last value (i_last) of the index
is smaller/greater than the starting value (i_0).
A while loop will be iterated as long as its predefined condition is satisfied and a break
statement is not encountered inside the loop.
WHILE. The general form of a while loop is
while relation
statements
end
The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching
case is executed. There must always be an end to match the switch.
The general form of the SWITCH statement is:
SWITCH switch_expr
CASE case_expr,
statement, ..., statement
CASE {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
OTHERWISE,
statement, ..., statement
END
Some examples of flow control statements are given below.
A simple if-else-end block

Prof. Dr. K. nl; ENVE 404; METU

%example of if-end block


t = 0;
if t > 0
sgnt = 1;
else
sgnt = -1;
end

A simple if-elseif-end block

%example of if-elseif-end block


if t > 0
sgnt = 1
elseif t < 0
sgnt = -1
end

An if-elseif-else-end block
% example of if-elseif-else-end block
if t > 0, sgnt = 1
elseif t<0, sgnt = -1
else sgnt = 0
end

An if-elseif-elseif-..-else-end block
% example of if-elseif-elseif-else-end block
point = 85;
if point >= 90, grade = 'A'
elseif point >= 80, grade = 'B'
elseif point >= 70, grade = 'C'
elseif point >= 60, grade = 'D'
else grade = 'F'
end

A switch-case-end block
% example of switch-case-end block
point = 85;
switch floor(point/10) %floor(x): integer less than or equal to x
case 9, grade = 'A'
case 8, grade = 'B'
case 7, grade = 'C'
case 6, grade = 'D'
otherwise grade = 'F'
end

Prof. Dr. K. nl; ENVE 404; METU

A for Loop

% example of for loop


point = [76 85 91 65 87];
for n = 1:length(point)
if point(n) >= 80, pf(n,:) = 'pass';
elseif point(n) >= 0, pf(n,:) = 'fail';
else %if point(n)< 0
pf(n,:) = '????';
fprintf('\n\a Something wrong with the data??\n');
break;
end
end
pf

A while loop

% example of while loop


r = 1;
while r < 10
r = input('\nType radius (or nonpositive number to stop):');
if r <= 0, break, end %isempty(r)| r <= 0, break, end
v = 4/3*pi*r*r*r;
fprintf('The volume of a sphere with radius %3.1f = %8.2f\n',r,v);
end

Prof. Dr. K. nl; ENVE 404; METU

INPUT-OUTPUT in .m FILES
Information is passed into the function via the argument list and is output via the functions
name. Another function input function provide a ways to enter input information and two
other functions display and fprintf functions display information directly using the
command window.
input Function
This function allows you to prompt the user for values directly from the command window.
Its syntax is
n = input('promptstring')
The function displays the promptstring, waits for keyboard input, and then returns the
value from the keyboard. For example,
>> m = input('Mass (kg): ')
When this line is executed, the user is prompted with the message
Mass (kg):
If the user enters a value, it would then be assigned to the variable m.
The input function can also return user input as a string. To do this, an 's' is appended to the
functions argument list. For example,
>> name = input('Enter your name: ','s')
When this line is executed, the user is prompted with the message
Enter your name:
display Function
This function provides a handy way to display a value. Its syntax is
disp(value)
where value = the value you would like to display. It can be a numeric constant or variable,
or a string message enclosed in hyphens. Its application is illustrated in the following
example. Write the following statements in the file editor
d = input('Distance (m): ');
t = input('Time (day): ');

Prof. Dr. K. nl; ENVE 404; METU

disp(' ')
disp('Velocity (m/day):', d/t)
disp (d/t)
Save the file as displayff.m. To invoke the function, return to the command window and type
>> displayff
Distance (m): 100
Time (day): 3
Velocity (m/day):
33.3333
fprintf Function
This function provides additional control over the display of information. A simple
representation of its syntax is
fprintf('format', x, ...)
where format is a string specifying how you want the value of the variable x to be displayed.
The operation of this function is best illustrated by examples. A simple example would be to
display a value along with a message. For instance, as in the previous example, suppose that
the variable velocity has a value of 33.3333. To display the value using eight digits with four
digits to the right of the decimal point along with a message, the statement along with the
resulting output would be
>> fprintf('The velocity is %8.4f m/s\n', d/t)
The velocity is 33.3333 m/s
Commonly used format and control codes employed with the fprintf function are given as
follows
Format Code
%d
%e
%E
%f
%g
Control Code
\n
\t

Description
Integer format
Scientific format with lowercase e
Scientific format with uppercase E
Decimal format
The more compact of %e or %f
Description
Start new line
Tab

The fprintf function can also be used to display several values per line with different formats.
For example,

Prof. Dr. K. nl; ENVE 404; METU

>> fprintf('%5d %10.3f %8.5e\n',100,2*pi,pi);


100 6.283 3.14159e+000
It can also be used to display vectors and matrices.
DEBUGGING M-FILES
Debugging is the process by which you isolate and fix problems with your code. Debugging
helps to correct two kinds of errors:
1. Syntax Errors: For example, misspelling a function name or omitting a parenthesis.
2. Run-time Errors: These errors are usually algorithmic in nature. For example, you
might modify the wrong variable or code a calculation incorrectly. Run-time errors
can be difficult to track down because the local workspace of a function is lost when
errors force a return to the MATLAB base workspace.
The MATLAB Editor can help you to discover many syntax errors, as you type. For example,
strings missing a delimiter () are colored red, while closed strings turn the color purple. The
Editor also finds mismatched parentheses.
If a program or an M-file does not work as intended, if there is still at least one erroneous
statement, it is convenient to stop the program execution at a certain point and watch the
execution of the following steps in detail. For such tasks several tools are available in the
MATLAB Editor in the Debug submenu.
Breakpoints are specific lines of code where you would like MATLAB to stop execution and
hold everything that is, keep all active function workspace open and accessible.
There are three basic types of breakpoints:
A standard breakpoint, which stops at a specified line.
A conditional breakpoint, which stops at a specified line only under specific
conditions.
An error breakpoint, which stops when an M-file produces the specified type of
warning, error, or NaN or infinite value.
To set a standard breakpoint using the Editor, click on a dash in the breakpoint alley next to
line number of an executable line of code. The dash turns into a red dot. The breakpoint is
disabled (gray) if there is a syntax error or if you have not saved to a directory on the path.
To remove the breakpoint, click on the dot.
Conditional and error breakpoints can be set by choosing one of the Debug -> Set/Modify
Conditional Breakpoint or Debug -> Stop if Errors/Warnings. Both choices open a dialog box
to specify the particulars.

10

Prof. Dr. K. nl; ENVE 404; METU

After setting a breakpoint, run the M-file. The prompt changes to K>>, indicating that
MATLAB has entered debug mode. The program pauses at the first breakpoint, and that line
will be executed when you continue to the next breakpoint (
program one line at a time (
the right of the breakpoint.

) or step through the

). The pause is indicated in the Editor by a green arrow just to

ENDING DEBUGGING
While debugging, you can change the value of a variable in the current workspace to see if a
new value produces the expected results. While the program is paused, assign a new value
to the variable in the Command Window, Workspace browser, or Array Editor, then continue
running or stepping through the program. If the new value does not produce the expected
results, the program has another problem.
After identifying a problem, end the debugging session. You must end a debugging session if
you want to change and save an M-file to correct a problem, or if you want to run other
functions in MATLAB.
To end debugging, click the Exit Debug Mode button or select Exit Debug Mode from the
Debug menu. After quitting debugging, the pause arrows in the editor display no longer
appear, and the normal prompt >> reappears in the Command Window.

11

Potrebbero piacerti anche