% Author: Spike
% Date: 22/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function
tempPlot(temps)
%%%%%%%%%%%%%%%%%%%%
% Generate the hours
%%%%%%%%%%%%%%%%%%%%
hours=1:size(temps,2);
%%%%%%%%%%%%%%%%%%%%%%%%
% Plot & label
the graph
%%%%%%%%%%%%%%%%%%%%%%%%
plot(hours,temps);
xlabel('Hour of the
Day');
ylabel('Temperature
(Celcius)');
title('Daily
Temperature Plot');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Highlight the
value at mid-day
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if hours(end)>=12
text(12,temps(12),'*');
end;
24.22 Review
• Motivation for
function use
• calling functions
• design principles
for functions
• function
declaration syntax
• comments &
functions
• top-down &
bottom-up views of functions
• black-box paradigm
• parameters
• returned values
25 FURTHER MATLAB FUNCTIONS
• Functions are a
vital part of all procedural languages
- issues of re-use, cohesion,
& coupling
• Much of Matlab’s
power focuses on the built-in functions
• Matlab allows
users to write and employ their own functions
- encourages modularity &
re-use
• Lecture is the 2nd
in a series of two concerning functions in Matlab. Topics covered include:
- formal vs. actual parameters
& outputs
- workspaces & scope of variables
- stack & run-time support for
function calls
- functions with variable numbers
of inputs & outputs
- efficiency & encapsulation
issues
References: For Engineers (Ch. 1, 5)
Student
(Ch. 12, 24)
Mastering
(Ch.14, Appendix A)
25.1 Formal vs. Actual Parameters &
Outputs
• In order to
minimise coupling a function should not know unnecessary details about the
caller
- no knowledge of larger task of
the caller
- no knowledge of the variables of
the caller
• However,
communication of values is till necessary
- inputs (arguments) for the
function to work upon
- outputs (returned values) for
the function to communicate results
• The apparent
conflict of goals can be resolved by allowing the function to employ its own
name for arguments & returned value independent of whatever they are
named by the caller:
- names employed by the function
are known as formal parameters & outputs
- names employed (values supplied)
by caller are known as actual parameters & outputs
- must be a 1-1 mapping between
them
25.2 Parameter Association
• A 1-1 mapping
between parameters (& outputs) of the caller (actual) and function
(formal) is needed
• Mapping
(association) is based simply on order:
- first actual parameters is
mapped to 1st formal parameter, 2nd actual parameters is mapped to 2nd formal
parameter…etc.
|
- 1st actual output is mapped to
1st formal output…etc.
|
• Consider a
function declared with formal parameters fp1…fpm and outputs fo1…fon that is
called with actual parameters p1…pm
25.3 Parameter Association Example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sumProdDiff - SUM,
PRODUCT & DIFFERENCE OF TWO ARRAYS
%
% [s p d] =
sumProdDiff(a,b)
% Return the scalar operator sum
(s), product
% (p) and difference (d) of two
arrays a and b.
|
%
% A simple function constructed to
illustrate
% parameter association (formal vs.
actual).
|
% Author: Spike
% Date: 24/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [s, p, d] =
sumProdDiff(a,b)
if size(a)~=size(b)
warning('Arrays are different sizes');
s=[], p=[], d=[];
end;
s=a+b;
p=a.*b;
d=a-b;
>> vec1=[1 2 3
4 5 6];
>> vec2=[7 6 5
4 3 2];
>> [sum
product difference]=sumProdDiff(vec1,vec2)
sum =
8
8 8 8
8 8
product =
7
12 15 16
15 12
difference =
-6
-4 -2 0
2 4
Mapping
vec1<->a,
vec2<->b
sum<->s,
product<->p, difference<->d
Parameter Assoc.
Example (Cont.)
>> [add
multiply subtract]=sumProdDiff([1 2],[3 4])
add =
4
6
multiply =
3
8
subtract =
-2
-2
Mapping
[1 2]<->a, [3
4]<->b
add<->s,
multiply<->p, subtract<->d
>>
sumProdDiff([1 2],[3 4])
ans =
4
6
Mapping
[1 2]<->a, [3
4]<->b
ans<->s
>> [sum
prod]=sumProdDiff([1 2],[3 4])
sum =
4
6
prod =
3
8
Mapping
[1 2]<->a, [3
4]<->b
sum<->s,
prod<->p
25.4 Pass by Value & Pass by Reference
• Matlab functions
are provided copies of the arguments being passed:
- this is called pass by value
• The implications
are that:
- the function may alter the value
of its copy of what was passed to it
- any changes made to arguments do
not propagate back to the caller
• The complement of
pass by value is that known as pass by reference
- not supported by Matlab
- many (most?) 3rd generation
procedural languages support both methods of passing
- function/procedure is provided a
pointer (reference) to the actual passed value
- if function/procedure makes
change to a parameter then that change propagates back to the caller
25.5 Pass by Value Example
% try2Change - TRY
TO CHANGE THE ARGUMENT
%
% y=try2Change(x)
% A simple fn. that return x+1 but
% also tries to increment x itself
% by 1.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com |
% Used as an example of the pass by
% value paradigm of Matlab.
|
% Author: Spike
% Date: 24/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y =
try2Change(x)
x=x+1;
fprintf('Inside
Function, x=%g\n',x);
y=x;
>> num=7
num =
7
>>
returned=try2Change(num)
Inside Function, x=8
returned =
8
>> num
num =
7
>> x=0
x =
0
>>
try2Change(x)
Inside Function, x=1
ans =
1
>> x
x =
0
25.6 Scope Rules & Workspaces
• Each function has
its own workspace:
- area for its own variables,
parameters, outputs
- functions can only see (access
and alter) variables in their own workspace
• In practice this
means:
- functions can’t access the
variables in other functions
- functions can’t access the
values of their caller’s variables (except those explicitly passed to them)
nor of the base workspace
• The workspace of a
function only exists while the function is running
- before the function executes its
variables do not exist
- after the function terminates
its variables do not exist
• The scope of a
variable is simply that part of a program in which the variable exists (can
be seen)
• Script M-files are
not functions, they run in the workspace of their caller
25.7 Scope Example
% scopeExample -
EXAMPLE OF VARIABLE SCOPE
%
% z=scopeExample(x,y)
% What variables can
and can't be seen.
|
% Author: Spike
% Date: 24/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z =
scopeExample(x,y)
z=x+y;
fprintf('In
function: x=%g, y=%g, z=%g\n',x,y,z);
>> a=10; b=20;
c=30;
>> fprintf('Before
Call, a=%g, b=%g, c=%g\n',a,b,c);
Before Call, a=10,
b=20, c=30
>>
fprintf('Before Call, x=%g, y=%g,
z=%g\n',x,y,z);
??? Undefined
function or variable 'x'.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com >> a=scopeExample(b,c);
In function: x=20,
y=30, z=50
>>
fprintf('After Return, a=%g, b=%g, c=%g\n',a,b,c);
After Return, a=50,
b=20, c=30
>>
fprintf('After Return, x=%g, y=%g, z=%g\n',x,y,z);
??? Undefined function
or variable 'x'.
|
>> x=40
x =
40
>>
fprintf('Before Call, a=%g, b=%g, c=%g, x=%g\n',a,b,c,x);
Before Call, a=50,
b=20, c=30, x=40
>>
x=scopeExample(a,x);
In function: x=50,
y=40, z=90
>>
fprintf('After Return, a=%g, b=%g, c=%g, x=%g\n',a,b,c,x);
After Return, a=50,
b=20, c=30, x=90
25.8 Run-Time Structure & the Stack
• Dynamic allocation
(function starts) and de-allocation (function terminates) of workspaces
requires a dynamic data structure
- functions can call other
functions which call yet others or call themselves etc.
|
• A stack is
employed to support function/procedure calls in programming languages
- like a physical stack of items
(LIFO)
- as functions start their
workspaces are added (pushed) to the stack (space in memory is allocated to
them)
- as functions terminate their
workspaces are removed (popped) from the stack (the memory is freed)
25.9 Return, Error & Warning
• By default
functions terminate (return) after the last statement in the function M-file
• User’s can alter
this behaviour
return Terminate execution of the function at
this point and return to caller
:
if
evalFinished(x,y,z) # are we
done?
return;
else
[x
y z]=update(x,y,z);
end;
error Print an error message and terminate all
execution, returning to base workspace
:
if abs(y)<eps
error(‘Divide
by zero error’);
else
z=x/y;
end;
• Functions may also
report a warning but continue execution. Differs from simply using using
disp() because user can turn on and off with warning on and warning off
:
if abs(y)<eps
warning(‘Div
0 Error. Z set to 0’);
z=0;
else
z=x/y;
end;
25.10 nargin & Variable Inputs
• Function calls may
be made with less arguments than declared in the function
- not a syntax error (in Matlab)
- can be useful if arguments
represent options or for which clear defaults exist
• Function needs a
mechanism to detect how many arguments it has received
- each function can call the
function nargin to determine the number of arguments received
- hopefully do something appropriate
if less than desired number received
function result =
narginEx(arg1,arg2,arg3)
if nargin==3
fprintf(‘Received all three arguments’);
elseif nargin==2
disp(‘3rd argument missing’);
elseif nargin==1
disp(‘Received only one of three args’);
else
disp(‘No arguments received.’);
end;
25.11 nargout & Variable Outputs
• It is also
possible for the caller of a function not to save all the values that the
function returns
- by default the additional values
are ignored
- if the caller does not save any
values then the first returned value is always placed in ans
• However it is
possible for a function to detect how many of its outputs are being saved by
the caller
- use the function call nargout
- function might modify its
behaviour based on number of values caller wants
function [o1,o2]
nargoutEx(arg1,arg2,arg3)
res1=arg1.*arg2-arg3;
res2=arg2.*arg3+arg1;
if nargout==2
o1=res1;
o2=res2;
elseif nargout==1
o1=[res1 res2];
else
fprintf(‘%f’,[res1 res2]);
end;
25.12 nargin & nargout Example
A function to
measure the performance of a single set or commands or contrast the
performance of two sets of commands.
|
Performance can be
measured solely as CPU time, or CPU time plus User time.
|
For a single command
the CPU time and User time should be returned. For two commands the ratio of
times should be returned.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com
Useful for
contrasting two alternate implementations of the same problem.
|
% perfMeasure -
MEASURE THE TIME PERFORMANCE OF A FUNCTION
%
% [cpu user]=perfMeasure(commands)
% Return the cpu and user time taken
to
% complete
"commands".
|
%
% cpu=perMeasure(commands)
% As above but only the cputime
%
% perMeasure(commands)
% As above but prints a message to
the screen
% concerning the CPU time.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com %
% [cpu
user]=perMeasure(commands1,commands2)
% Returns the ratio of cpu time and
user time
% as taken by commands1 contrasted with
% commands2
perfMeasure (Cont)
% cpu=perMeasure(commands1,commands2)
% As above but only the ratio of CPU
times is
% returned.
|
%
% perMeasure(commands1,commands2)
% Prints a message about the
relative CPU times
% to the display.
|
%
% For example:
% shell1Time=perfMeasure('shell1');
% grabs the cpu time for running the
M-file
% shell1.
|
%
% Written to illustrate nargin and
nargout.
|
% A couple of points:
%
* eval is used to run the list of commands
%
passed by the caller.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com % * The timing calls are placed in with the
% string to be eval-ed so that the
% overhead of calling eval is not added
to
% the times.
|
%
* For some reason Matlab seems to hate
% expressions of the form
% value=eval(string); Hence I've
%
been reduced to calling eval and allowing
% the returned values to be stored in the
% default ans. I then access them from
% there. I can see no reason why the
above
% syntax is disallowed but it stores the
% value in ans.
|
% Author: Spike
% Date: 25/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
perfMeasure (Cont)
function [cpu, user]
= perfMeasure(comm1,comm2)
%%%%%%%%%%%%%%%%%%%%%%%%%%
% No commands to
run. Quit.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com %%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin==0
error('Must have at least one command list
to process');
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Know that there is
at least one set of
% commands to run.
However the timing
% information
required depends on the number of
% outputs the user
has requested. If two
% outputs then we
want both cpu & user.
% Otherwise only
cpu.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargout==2
evalString=['ctime=cputime; tic;' comm1 ';
utime=toc; [cputime-ctime utime];'];
eval(evalString);
ctime1=ans(1); % Cpu time for comm1
utime1=ans(2); % User time for comm1
else
evalString=['ctime=cputime;' comm1
';cputime-ctime;'];
eval(evalString);
ctime1=ans;
end;
perfMeasure (Cont)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If there is a 2nd
set of commands to run then
% repeat the above
operations.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin==2
if nargout==2
evalString=['ctime=cputime; tic;' comm2
'; utime=toc; [cputime-ctime utime];'];
eval(evalString);
ctime2=ans(1);
utime2=ans(2);
else
evalString=['ctime=cputime;' comm2
';cputime-ctime;'];
eval(evalString);
ctime2=ans;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now all the work
has been done determine the
% form of output
required. If no returned value
% then print a
message. If only 1 returned
% value then its the
cpu time. Otherwise (2)
% then both cpu and
user time.
|
% In all cases it is
an absolute measure of
% time if only 1
command was to be run, and a
% ratio if two
commands were run.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargout==0 % Output to Screen
if nargin==1
fprintf('CPU time taken: %6.2f
seconds\n',ctime1);
else
fprintf('Ratio of CPU times:
%5.2f\n',ctime1/ctime2);
end;
perfMeasure (Cont)
elseif nargout==1 % Only CPU time
if nargin==1
cpu=ctime1;
else
cpu=ctime1/ctime2;
end;
else % CPU
& User time
if nargin==1
cpu=ctime1;
user=utime1;
else
cpu=ctime1/ctime2;
user=utime1/utime2;
end;
end;
>>
perfMeasure('shell2','shell3');
% <Outputs of shell2 &
shell3 deleted>
Ratio of CPU times:
89.00
>>
perfMeasure('shell3');
% <Outputs of shell3
deleted>
CPU time taken: 0.02 seconds
>> [cpu
user]=perfMeasure('shell2')
% <Outputs of shell2
deleted>
cpu =
1.8100
user =
1.8191
25.13 Global Variables
• It is possible in
Matlab to access variables outside the workspace of a function
- it is generally very bad
programming practice: anything a function needs should be explicitly passed
to it and anything the caller needs should be explicitly returned
- The methods are shown here
merely for completeness
• One approach is
the global operator
- syntax: global
<variable-name>
- allows user access to the
variable <variable-name> in the special “global” workspace
- TIC & TOC are implemented
this way (see text)
In function1
:
global specialValue;
% specialValue now in
: “global”
workspace
In function2
:
global specialValue
% Can now access the
: %
variable specialValue
%
stored in the global
%
workspace % created by fn1
• Other options are
evalin and assignin
25.14 Efficiency Issues
• Number of
efficiency issues concerning functions of which users should be aware
• 1st time a
function is invoked (called) in a session it must be loaded in:
- must be “compiled” into an
internal (to Matlab) micro-code
- micro-code version of function
is available to Matlab throughout rest of session
- hence first invocation of a
function is somewhat slower than all subsequent
• The micro-code
(pcode) version of a function can be saved to disk
- use pcode <functionName>
command
- creates a file
<functionName>.p
- loaded in deference to the .m
file
- a means of distributing
functions/scripts without letting users see the code
• Arguments to
Matlab functions are not copied until the function modifies the argument
- performance implications for
large arrays
25.15 varargin & varargout
• It is possible for
functions to be written to accept any number of inputs (examples include
Matlab’s max()) and produce any number of outputs
• Based on the
special argument varargin and special output varargout
- cell arrays (not covered in
lectures) that contain the individual elements specified by the caller
% mult - MULTIPLY AN
ARBITARY NUMBER OF ARRAYS
%
% y=mult(a1,a2,...)
% Uses vector/scalar multiplication
to
% multiply an arbitrary number of
inputs.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com |
KURSUS MATLAB ONLINE Skripsi, Tesis, DISERTASI 081219449060
Selasa, 13 Januari 2015
KURSUS MATLAB ONLINE Skripsi, Tesis, DISERTASI 081219449060 - MULTIPLY AN ARBITARY NUMBER OF ARRAYS AND function tempPlot(temps)
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar