Graphics Programs Reference
In-Depth Information
MATLAB uses two kinds of M-fi les, scripts and functions . Whereas
scripts are series of commands that operate on data contained in the work-
space, functions are true algorithms with input and output variables. The
advantages and disadvantages of both M-fi les will now be illustrated by
means of an example. First we start the Text Editor by typing
edit
This opens a new window named untitled . First we are generating a simple
MATLAB script. We type a series of commands calculating the average of
the elements of a data vector x .
[m,n] = size(x);
if m == 1
m = n;
end
sum(x)/m
The fi rst line returns the dimension of the variable x using the command
size . In our example, x should be either a column vector with dimension
(m,1) or a row vector with dimension (1,n) . We need the length of the
vector for dividing the sum of the elements, which is either m or n . The
if statement evaluates a logical expression and executes a group of com-
mands when this expression is true. The end keyword terminates the last
group of commands. In the example, the if loop picks either m or n de-
pending on if m==1 is false or true The last line computes the average by
dividing the sum of all elements by the number of elements m or n . We do
not use a semicolon here to enable the output of the result. We save our new
M-fi le as average.m and type
x = [3 6 2 -3 8];
in the Command Window to defi ne an example vector x . Then we type
average
without the extension .m to run our script. We obtain the average of the ele-
ments of the vector x as output.
ans =
3.2000
After typing
whos
we see that the workspace now contains
Search WWH ::




Custom Search