Sunteți pe pagina 1din 9

050626/Thomas Munther

Halmstad University
School of Information Science, Computer and Electrical Engineering

Laboratory 8
Length about 2 hours with supervision.
Regardless if you completed the whole Lab-PM during these 2 hours you should try
to find the time to work through this Lab-PM thoroughly afterward.
The last page contains hand-in assignments. You should try to solve them within a
week to be able to follow the pace in the course.
Everything that follows after >> is written in the Matlab Command Window and
indicate what you as a user should write. The % is intended as a comment to a
specific command.
In every assignment we will face problems that need to be solved and then we use m-files
to solve them for us, but if we stand before more complex problems, it is often a better
strategy to divide the problem in smaller parts. One of the parts could be the main
program ( m-file )and other could be focused in problem solving. These are so called
function m-files.
In many programming languages this is nothing else than subroutines.
Communication between the function m-files is performed with input or output
parameters. A function m-file can have 0,1 or several input and output parameters.
The same function can also be called with a different number of input arguments from
time to time.
Like the m-file plot in Matlab.
nargin
A function that returns the number
arguments used in the function call.
nargout
Returns the number of output arguments
in a function call.
inputname(x)
Gives the name of the variable at position
x in the function call. Must be within the
function m-file to be used.
Error_string=nargchk(min,max,number)
Checks the number of input arguments to a
function. Min and max gives the smallest
and largest number of input arguments.
Number gives the actual number of
parameters. If number lies outside the
interval, then Error_string is given.
Error_string=nargoutchk(min,max,number) Checks the number of output arguments to
a function. Min and max gives the smallest
and largest number of output arguments.
Number gives the actual number of
parameters. If number lies outside the
interval, then Error_string is given.

We create a function m-file random.


--------------------------------------------function A=random(a,b,c)
if nargin==0, v=0;
elseif nargin==1,v=1;
elseif nargin==2, v=2;
else ,v=3;
end
A=v;
-----------------------------------------------The following will happen when we call the function random.
>> random(1,3)
ans =
2
>> random(1,3,4)
ans =
3
What happens if we call the function with 4 arguments instead ?
It would be nice if we could call the function with arbitrary many input arguments as well
as output arguments without any risk of error.
This is of course also possible to do.
varargin
A cell array with variable length. Can store
arbitrary many input arguments.
varargout
A cell array with variable length. Can store
arbitrary many output arguments.
The cells in a cell array do not need to be of the same datatype.
Below follows an example of a function calculating mean value, median value and
standard deviation for every input vector.

function [varargout]=statistics(varargin)
for i=1:length(varargin)

% Finds out how many input vectors we have.

x=varargin{i};
y.mean_val=mean(x);
% Stores the result in a structure y.
y.median_val=median(x);
y.std_val=std(x);
varargout{i}=y;
% The structure y is put in a output vector.
end
Let us test our function file by calling it, but first we create some vectors of variable
length.
>> a=1:4; b=2:10; c=3:5;

Run the m-file !


[a_res,b_res,c_res]=statistics(a,b,c)
a_res =
mean_val: 2.5000
median_val: 2.5000
std_val: 1.2910
b_res =
mean_val: 6
median_val: 6
std_val: 2.7386
c_res =
mean_val: 4
median_val: 4
std_val: 1
The result can be seen above,since I did not know how many input vectors I wanted to
use from the start. It seemed like a good idea to use varargin and varargout.
One can also use ordinary input and output arguments together with varargin and
varargout, but then the latter ones must be at the end.
function [y,varargout]=statistics[x,varargin]
One function file can use one input argument and return one output argument, but can as
well be called with 10 input arguments and return only 5.
This can be very useful.
Function as a parameter
Assume that we write a function m-file, but the input argument is also function.
This can also be implemented in Matlab. Remember that the input parameter is a
function handle.
Use the command feval to evaluate the function handle.
Commands dealing with function handles.
fh=@fcn
Creates a function handle fh to the function fcn.
str2func(fcn)
Returns a function handle to the function fcn.
func2str(fh)
Returns the function name to the function handle fh.
functions(fh)
Returns a structure with information about the function handle fh.
feval(fh,x1,..xn) Evaluates the function fcn, which is given by the function handle
fh.The function is calculated in x1,.........., xn
Let us see how the handle looks for the previously defined function statistics:

>> fh=@statistics;
Create a vector X=[ 1 2 3 4 5 6];
Evaluate the function in X with:
>> feval(fh,X)
ans =
mean_val: 3.5000
median_val: 3.500
std_val: 1.8708
Here comes yet another example of how we can use handles, but in this case you might
recognize the example. Look upon it as an repetition example.
>> feval(statistics,X)

% The same as feval(fh,X).

----------------------------------function y=func(x)
y=x.^2;
---------------------------------Run the file from the command window, but first make a function handle.
>> Fh=@func;

% function handle Fh to the function.

Evaluate the function with the help of the function handle.


An advantage is that we do not need to focus on which variable we are using in the
function.
Write:
>> feval(Fh,[ 1 2 3 4])

% feval('func',[ 1 2 3 4]) , also works.

The result becomes :


ans =
1 4 9 16
Instead of defining our own function m-files. Use Matlab functions. Let us rewrite our
function m-file func. This is done below:
----------------------------------------------------------------------------------------% func.m
fun=input(What function do you want ? :,s); % Choose between : sin,cos,log10, exp !
x=1:4;
y=feval(fun,x);
% Calls the function m-file fun and evaluates it for x.
disp( x
y)
disp([x y])
------------------------------------------------------------------------------------------

>> func
What function do you want ? : log10
% I chose 10-logarithm.
x
y
1.0000
0
2.0000 0.3010
3.0000 0.4771
4.0000 0.6021
Range of a variable
A function m-file containing variables can only rely on that these are known within this
function. As soon as the execution of the function m-file is finished the variables will be
forgotten.
If you want the variable to keep its value to the next execution you must make a
declaration and use the word persistent.
persistent variable_1
Even with the declaration in the function m-file above, the variable remain to be
unknown outside the m-file. If you want to make variable_1 known in the workspace or
in other m-files, it must be declared as a global variable in all these m-files.
global variable_1
Note that a variable_1 existing in an m-file fun and not globally declared is not equal to
a variable with the same name, used in workspace.
The variables may have the same name, but are nevertheless unknown to each other.
To examplify this. Create a function m-file fun.
---------------------------------------------------------------function y=fun(x)
global a_ b_
y=a_+b_*x;
----------------------------------------------------------------Then create an m-file plot_fun that invokes the function m-file fun.
The variables a_ and b_ are global and must be declared in both m-files.
Our main program will then look like:
--------------------------------------% plot_fun.m
global a_ b_
x=0:0.1:10;
y=fun(x);
% Call of the function fun with input parameter x.
plot(x,y),grid
title(The function y= a+b*x)
-------------------------------------Call the main program plot_fun. To see the result look in figure 1 !

First define a_ and b_ !


>> a_=1, b_=2;
>> plot_fun

The function y= a+b*x


25

20

15

10

10

Figure 1

More about m-files


When matlab executes a function it results in a compiled version that is used
at every call of the function. Every m-file that we have written so far can also be
displayed in the command window ( normally we enter the edit window ) by a simple
request.
If we write type filename then the content will be seen.
>> type plot_fun
------------------------------------------------------------------------% plot_fun.m
global a_ b_
a_=1;
b_=2;
x=0:0.1:10;
y=fun(x);
% Call of the function fun with input parameter x.
plot(x,y),grid
title('The function y= a+b*x')
-------------------------------------------------------------------------There is also a possibility to save the compiled version in a p-file.
This p-file can be used more or less the same way as the m-file, but there is one
significant difference. You can not display it. The type command can not operate on it.
We know that our m-file plot_fun use a function m-file fun.
Now let us convert this m-file, fun into a p-file.
>> pcode fun % The conversion is complete.

Clear the m-file fun from our work directory and run our m-file plot_fun once again.
The output from the execution is the same as previously.
Try also:
>> type fun % Show fun.p !
No information about the p-file is displayed.
M-file control
With the command echo you can echo the command lines of an m-file during execution.
This could be useful in order to view the command lines as we execute. For instance for
debugging or demonstration purposes.
pause
Execution of an m-file is paused
until a keyboard button is pressed.
pause(n)
Stops the execution for n seconds
and then continues.
echo function_name on
Turns echo on in function_name.m
echo function_name off Turns echo off in function_name.m
return
Return to invoking function it also
terminates the keyboard mode.
keyboard
Stops execution of the file
and gives control to the user's
keyboard. The special status is
indicated by a K appearing before
the prompt.
To leave this mode, write return
after the prompt.
error(message)
Displays the error message in the
string MESSAGE and exits from the
m-file.
break
Interrupts for- and while-loops, but
if these are nested only the
innermost loop.
We will now try to illustrate the command keyboard. Modify the m-filen plot_fun.
--------------------------------------% plot_fun.m
global a_ b_
a_=1;
b_=2;
keyboard
% PLEASE NOTICE !
x=0:0.1:10;
y=fun(x);
% Call of the function fun with input parameter x.
plot(x,y),grid
title('The function y= a+b*x')
-------------------------------------When I try to run the program. The control of the m-file is given to the keyboard.
Write !
>> echo on % Turns on echoing of commands inside m-files.

>> plot_fun
global a_ b_
a_=1;
b_=2;
keyboard
K>>
% Everything is now controlled from the keyboard.
Change the values of the global parameters !
K>> a_=0,b_=10
a_ =
0
b_ =
10
Continue the execution. Write return in the command window after the prompter K>> !
x=0:0.1:10;
y=fun(x);
% Invoke the function fun with parameter x.
plot(x,y),grid
title('The function y= a+b*x')
The function y= a+b*x
100

90

80

70

60

50

40

30

20

10

10

Figure 2
In the figure 2 we can see the result of the m-file plot_fun execution.
Write !
>> echo off

% Turns off echoing.

PLEASE NOTICE !
THE ENGLISH VERSION OF LABORATORY 8 IS SOMEWHAT SHORTER THAN
THE SWEDISH VERSION, BUT THE MISSING 3 PAGES ARE NOT NEEDED TO
DO THE HOME ASSIGNMENTS.
I WILL TRY TO TRANSLATE THESE AS SOON AS POSSIBLE !
8

Home assignments laboratory 8


1. Create an m-file that asks you as a user what operation is to be performed on a vector
x=[ 1 2 3 4 5 ] . These operations are stored in 3 different function files: Fun1, Fun2 or
Fun3. The functions should be invoked from the m-file. Fun1 should take the square of
x , Fun2 the square root of x and finally Fun3 third root of x.
Use the command feval. The output as a result of the execution should be a nice table and
title.
2. Make a function file with 5 input parameters. The first four are two pairs of x- and ycoordinates (x1, y1, x2, y2 ) and the fifth, a single x-value. The first four are two dots in a
y-x plot. Connect these with a line and the fifth value is also a dot on the same line, but
you should find out the corresponding y-value and present everything in a plot.
Of course the five parameters must be chosen to be arbitrary.
3. Create a function file that can be called with variable number of input arguments.
It could be 1,2 or 3 arguments. They are the sides in a triangle with a 90 degree
angle. The order is always ( if they are given ): long side, side1 and side2.
You must check that these sides are valid for a triangle.
If the sides are possible then the following should be done:
All sides should be presented and calculated ( if not given) together with all the angles.
And also make a plot of the suggested triangle.
There should be a pause between the displayed result in the command window and the
plot. The pause should be 5 seconds.
Your m-file should of course cope with error inputs without any crash. It could look
like:
>> Triangle(3,2,1)
% This of course impossible values.
The m-file should then request new values.
If you enter only one agument, then suggest only one possible triangle
Hint: use the command gplot to plot the triangle.
The following must be done in order to pass the laboratory.
You must hand in a m-file for each problem. The m-file should begin with 2 comment
lines where it is stated when this file is created and by whom. Mail the the m-files to me.
I prefer if you send them in a compressed format like zip.files.

S-ar putea să vă placă și