Lab of COMP 406
1
Teaching Assistant: Pei-Yuan Zhou
Contact: [email protected]
Lab 3: 26 Sep., 2014
Introduction of Matlab (III)
Programming and Scripts
• Find the Matlab under the folder
• 1. Y:\Win32\Matlab\R2012a
• 2. Double click it and open Matlab
2
Open Matlab 2012a
• 2-D Plots
>> plot(x, y)
>> xlabel(‘x’); ylabel(‘y’)
>> legend(‘x’, ‘y’) ; title (‘title’)
>> bar(x,y); stairs(x,y);errorbar(x,y,e);stem(x,y)
• 3-D Plots
>> meshgrid; mesh(x,y,z);surf(x,y,z)
>> peaks(N); colormap(hsv)
• Subplots
>> subplot(row,col,num);
3
Review
Lecture and Lab Notes
• http://www4.comp.polyu.edu.hk/~csyliu/course/co
mp406/main.html
4
Character String
Script
Functions
5
Outline
Programming and Scripts
Character String
Script
Functions
6
Outline
Programming and Scripts
Character String
• A character string is a sequence of any number of characters enclosed in single quotes. You can assign a string to a variable.
Text1 = 'Hello, world';
• If the text includes a single quote, use two single quoteswithin the definition.
>>Text2 = 'You''re right'
Text2 =
You're right
• Text1 and Text2 are arrays, like all MATLAB variables. Their class or data type is char, which is short for character. (whos)
7
Character String
• You can concatenate strings with square brackets, just as you
concatenate numeric arrays.
>>Text3 = [Text1,' - ', Text2]
Text3 =
Hello, world - You're right
• To convert numeric values to strings, use functions, such as num2str
or int2str.
f = 71; %fahrenheit degree
c = (f-32)/1.8; % centi degree
tempText = ['Temperature is ',num2str(c),'C']
tempText =
Temperature is 21.6667C
8
Character String
Script
Functions
9
Outline
Programming and Scripts
There are two types of *.m file, Scripts and
Functions
The simplest type of MATLAB program is called a
script.
A script is a file with a “.m” extension that contains
multiple sequential lines of MATLAB commands
and function calls.
10
Script
To create a script, use the edit command. This
opens a blank file named newscript.m.
>>edit newscript
Go to
File->New->Script
Give a name to script
11
Script - Creation
12
Script - Building
Typing the sentences in newscript.mPrint the value of each elements in the vector x and shows
whether they are positive or negative.
13
Script - Saving
For saving the script, just go to File->Save
14
Script - Run
>> newscriptx(1) = 1 is positive
x(2) = 4 is positive
x(3) = -2 is negative or zero
x(4) = 3 is positive
x(5) = -1 is negative or zero
x(6) = -5 is negative or zero
If you want to run it,
typing >> newscript
Then you can see the
output in command
window like right figure
shows.
15
Script - Run
>> newscriptx(1) = 1 is positive
x(2) = 4 is positive
x(3) = -2 is negative or zero
x(4) = 3 is positive
x(5) = -1 is negative or zero
x(6) = -5 is negative or zero
If you want to run it,
typing >> newscript
And all generated
variables are listed in
workspace
16
Script - Comments
• Whenever you write code, it is a good practice to add comments that
describe the code. Comments allow others to understand your code, and
can refresh your memory when you return to it later. Add comments using
the percentage (%) symbol.
n = 50; % 50 data points
r = rand(n,1);
plot(r) % Draw a line from (0,m) to (n,m)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')
Ex1
• Create a script, named as “myscript.m”
• The script can draw the plot of function y=sin(x)
when x is in [0,2pi]
• Save your script
• Run the script
17
Ex1
• >>edit myscript.m
• The content of script
• Save myscript.m
• myscript
18
x=0:0.1:2*pi;
y = sin(x);
plot(x,y);
Script
• Advantage:
• Better for Simple but High Repeatability code
• All generated variables can be stored in workspace – easy
for viewing
• Disadvantage:
• Not support “Input/ Output Arguments”
• The variables stored in workspace, which may be
covered with each other
19
“Function” can
improve it
Character String
Script
Functions
20
Outline
Programming and Scripts
21
Function
• A function is a black box that gets some input andproduces some output. We do not care about the innerworkings of a function.
• Functions provide reusable code.
• Functions simplify debugging.
• Functions have private workspaces:
• The only variables in the calling program that can be seenby the function are those in the input list.
• The only variables in the function that can be seen by thecalling program are those in the output list.
22
• The black box consists of two parts: the definition of the interfaceby which the user passes data items to and from the function; and the code block that produces the results required by that interface.
Param 2
Param 1
Param n
. . .
Result
Function- Black Box View
23
Param 2
Param 1
Param n
. . .
Result
• A function definition consists of the following components:
• A name that follows the same syntactic rules as a variable name;
• A set of 0 or more parameters provided to the function;
• Zero or more results to be returned to the called of the function.
Function- Black Box View
25
Function – Template
1. The <return info> section for most functions involves providing
the name(s) of the results returned followed by an = sign. If more
than one result is to be returned, they are defined in a vector like
container. If nothing is to be returned from this function, both the
result list and the = sign are omitted.
2. The <function name> is a name with the same syntactic rules as
a variable name, and will be used to invoke the code body.
function <return info> <function name> (<parameters>)
<documentation>
<code body> % must return the results
26
Function – Template
function <return info> <function name> (<parameters>)
<documentation>
<code body> % must return the results
3. The <parameters> section is a comma-separated list of the names of
the data to be provided to the function.
4. The <documentation> section is one or more lines of comments that
describe what the function does and how to call it
• All the documentation lines up to the first non-document line are printed
in the command window when you type the following:
>> help <function name>
• The first line is listed next to the file name in the current directory listing
27
• Line1: the Matlab function definition is introduced by the key word function,
followed by the name of the return variable (if any) and the = sign.
• Line2: all comments written immediately after the function header are
available to the command window when you enter:
>> help cylinder
1. function volume = cylinder(height, radius)
2. % function to compute the volume of a cylinder
3. % volume = cylinder(height, radius)
4. base = pi * radius^2;
5. volume = base * height;
Function –An Example
28
1. function volume = cylinder(height, radius)
2. % function to compute the volume of a cylinder
3. % volume = cylinder(height, radius)
4. base = pi * radius^2;
5. volume = base * height;
Function –An Example
• Line3: it is a good idea to include in the comments a copy of the function
header line to remind a user exactly how to use this function.
• Line5: you must make at least one assignment to the result variable.
• The function definition needs no end statement. The code body
terminates automatically at the end of the file.
29
Function –An Examplefunction p = factorial(n)%FACTORIAL Factorial function.% FACTORIAL(N) is the product of all the integers from 1 to N,% i.e. prod(1:N). Since double precision numbers only have about% 15 digits, the answer is only accurate for N <= 21. For larger N,% the answer will have the right magnitude, and is accurate for % the first 15 digits.%% See also PROD.
% Copyright 1984-2001 The MathWorks, Inc. % $Revision: 1.5 $
if (length(n)~=1) | (fix(n) ~= n) | (n < 0)error('N must be a positive integer');
end
p = prod(1:n);
output argument
name of function
input argument
H1 comment line
other comment lines
executable code
• 1. >> edit function1 % create a function1.m file
• 2. type the code in the file
• function average = function1(vector)
• average = sum(vector)/length(vector);
• 3. save file “function1.m”
• 4. View your function code : >>type function1.m
• 5. call the function:
• >>vector = [1 5 3]
• >>ave = function1(vector)30
Function – Create A Function
• 6. Adding Help & Comments for function
31
Function – Create A Function
function average = function1(vector)% FUNCTION1: A simple function with a single help line.%% Usage of this function:% output = function1(input)% "output" is the average of the input vector "input".
% Pei-Yuan, 2014/09/26.
average = sum(vector)/length(vector); % calculate average
• After creating function, the comments (starting from percent (%) symbol) are the content of help
• Type “help + function name”, you can see the help documentation you added
• >> help function1
FUNCTION1: A simple function with a single help line.
Usage of this function:
output = function1(input)
"output" is the average of the input vector "input".
32
Function – Create A Function
• 1. The maximum identifier length is 63.
• len = namelengthmax => returns the maximum length allowed for MATLAB identifiers.
• The maximum identifier length is different for different version of MATLAB
• 2. The name of function can be different from name of M-file. (It is better to use the same name)
• The name of M-file is used for calling function
33
Function – *Maximum identifier Length
Function – Input and Output
• A function can have multiple inputs and outputs
• The following func2 has two inputs and two outputs
• Run func3.m
• >> [a,b] = func3 ([1 2 3], [4 5 6 7 8])
34
function [ave1, ave2] = func2(vector1, vector2);ave1 = sum(vector1)/length(vector1);ave2 = sum(vector2)/length(vector2);
Function – Input and Output
• nargin and nargout can be used to control the number
of inputs and outputs.
• nargin: returns the number of input arguments that were
used to call the function.
• nargout: returns the number of output arguments that
were used to call the function
35
• Then you can change the func2.m into func3.m
36
Function – Input and Output
function [ave1, ave2] = func4(vector1, vector2)
if nargin == 1, % only one inputave1 = sum(vector1)/length(vector1);
end
if nargout == 2, % two outputsave1 = sum(vector1)/length(vector1);ave2 = sum(vector2)/length(vector2);
end
• Then you can change the func2.m into func3.m
37
Function – Input and Output
>> [a, b] = func4([1 2 3], [4 5 6 7 8])
a = 2
b = 6
>> c = func4([1 3 5 7 9])
c = 5
The output is different based on
different calling method
Function – Nested Function
function out = func4(x)
r = reciproc(x);
out = sum(r);
% Definition for subfunctions
function output = reciproc(input)
output = 1./input;
38
>> func4([1 2 3])
ans = 1.8333
Calculate the sum of reciprocal of all elements in vector
Ex1
Problem: write a function called strsearch that takes a string s and a character c, and returns the number of occurrences of c in s and the index of the first occurrence.
Hint & Pseudo code:
Function [cnt, pos] = strsearch( s, c)
For each character of s in reverse order
If character is equal to c
increment the counter
save the index39
function [ cnt, pos ] = strsearch( s, c )
%STRSEARCH find the number of occurrences of a character in a
string
pos = 0;
cnt = 0;
n = length(s);
for i = n:-1:1, % from n to 1, and minus 1 for each loop
if ( s(i) == c ),
cnt = cnt + 1;
pos = i;
end
end 40
Ex1 - answer
Ex1 - answer
[ a, b ] = strsearch( 'abccdecfac', 'c' )
a =4
b =3
a = strsearch( 'abccdecfac', 'c' )
a =4
strsearch( 'abccdecfac', 'c' )
ans =4
41
Ex2 – Nested Function
Problem: write a function called mystats that find mean and median with internal functions.
Hint:
Creation: function [avg, med] = mystats(u)
The functions you can use:
avg = mean(u,n) % u is the vector, n is the length of u
med = median (u,n)
42
43
function [avg, med] = mystats(u)%MYSTATS Find mean and median with internal functions.n = length(u);avg = mean(u,n);med = median(u,n);function a = mean(v,n) % Subfunction to calculate average.
a = sum(v)/n;function m = median(v,n) % Subfunction to calculate median.
w = sort(v);if rem(n,2) == 1
m = w((n+1)/2);else
m = (w(n/2)+w(n/2+1))/2;end
Ex2 - answer
• >> [a,m]=newscript([1 2 3 4 11 12 13])
a =
6.5714
m =
4
• >> [a,m]=newscript([1 2 3 4 12 13])
a =
5.8333
m =
3.500044
Ex2 - answer
Summary
45
• Both scripts and functions are saved as m-files.
• Functions are special m-files that receive data through input
arguments and return results through output arguments.
• Scripts are just a collection of MATLAB statements.
• Functions are defined by the function statement in the first
line.
• Scripts use the global workspace but functions have their own
local independent workspaces.