Geoscience Reference
In-Depth Information
help average
which displays the i rst block of contiguous comment lines. h e i rst
executable statement (or blank line in our example) ef ectively ends the help
section and therefore the output of help . Now we are independent of the
variable names used in our function. h e workspace can now be cleared and
a new data vector dei ned.
clear
data = [3 6 2 -3 8];
Our function can then be run by the statement
Movie
2.4
result = average(data);
h is clearly illustrates the advantages of functions compared to scripts.
Typing
whos
results in
Name Size Bytes Class Attributes
data 1x5 40 double
result 1x1 8 double
revealing that all variables used in the function do not appear in the
workspace. Only the input and output as dei ned by the user are stored in
the workspace. h e M-i les can therefore be applied to data as if they were
real functions, whereas scripts contain sequences of commands that are
applied to the variables in the workspace. If we want variables such as m and
n to also appear in the memory they must be dei ned as global variables in
both the function and the workspace, otherwise they are considered to be
local variables. We therefore add one line to the function average with the
command global :
function y = average(x)
%AVERAGE Average value.
% AVERAGE(X) is the average of the elements in the array X.
% By Martin Trauth, June 27, 2014
global m n
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
Search WWH ::




Custom Search