Computer Lab Exercise-3
Computer Lab Exercise-3
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
Select New m-File from the File menu. A new edit window should appear.
Type the following lines into this file.
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
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));
>> 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.
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
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
A for Loop
A while loop
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): ');
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,
10
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.
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