Lesson5

advertisement
LESSON 5
TOPIC 5. Functions.
M-files drastically simplify execution of complicated tasks. Meanwhile, they exhibit a couple of
disadvantages. Just look at the “magic” files – they can produce a result only if a variable called
d exists and has an integer value. Also, create and put in the general Matlab workspace too many
auxiliary variables. Such unwanted effects can be avoided on using functions. A User-Created
Function – M-function, is an M-file with specific properties to be gradually discussed below.
Unlike ordinary M-files – scripts of ready for execution Matlab commands, M-functions are
formal sets of instructions to be applied to a list of arguments when the latter will be specified.
Obviously, such instructions can be given independently from the arguments’ values.
Task 1. Create a function that takes a temperature value in Celsius and returns the
converted value in Fahrenheit.
1. Open a new M-file in “Matlab Editor / Debugger” and enter the following first statement:
function result = ctof(degree)
M-functions must start from the Matlab keyword function. In the same statement a variable
must be introduced that will keep the result computed by the function. The variable name can
be an arbitrary Matlab-valid name. From clear logical reasons we opt for the name result.
After a formal assignment operator – nothing is going to be assigned at this point, the
function name must be specified followed by a list of formal arguments in parenthesis.
This first statement can be read in the following way: the current M-file is the body of a
function called ctof that will require one argument, formally denoted as degree, and will
result in a value the variable result will have at the end of the M-file.
As you see, the Matlab statement is much shorter than the explanation, as usually.
2. The result-computing statement is trivial:
result = degree * 9 / 5 + 32;
3. Save the M-file. Its destination can be any folder, for example our favorite C:\Matlab, but its
name must necessarily repeat the function name – ctof.m in the current case.
4. Return to the “Matlab Command Window” and check how the newly created function works
– compute the Fahrenheit equivalent of 0oC. Do not forget to change the working directory:
» cd C:\Matlab
» ctof(0)
ans =
32
» who
Your variables are:
ans
Pay attention to the following important notes:
 The M-function does not require a variable called degree, even though such name is used
in its body. Instead, it substitutes that formal name with the value of its real argument,
and only then produces the result.
 The list of the general variables in the Matlab workspace contains neither degree nor
result – the former is not a variable at all, the latter is a variable created at the beginning
of the M-function and automatically deleted from the workspace at the function end.
ATTENTION: All variables created in an M-function are Local Variables – they exist only
during the execution of the function and removed from the workspace as soon as
the function completes its last statement.
Task 2. Create a function for the opposite conversion – from Fahrenheit to Celsius.
It is obvious that every single M-function must be implemented in a separate M-file. Therefore,
open a new M-file by pressing the “New” button on the toolbar of the “Matlab Editor /
Debugger” and enter the following statements:
function result = ftoc(degree)
result = (degree – 32) * 5 / 9;
Save the script in C:\Matlab under ftoc.m name. Test the function in the “Matlab Command
Window”.
Task 3. Create a function that computes the distance between two given points on the
Cartesian plane.
1. Each point on the plane is distinguished by a pair of Cartesian coordinates x and y. So, the
function will need four coordinate values. Open a new M-file and enter the following
statements:
function result = dist(x1, y1, x2, y2)
result = sqrt((x1 – x2) ^ 2 + (y1 – y2) ^ 2);
2. Save the M-function in C:\Matlab under dist.m name and switch to “Matlab Command
Window” to test it.
3. It is natural to declare the pair of points in an array:
» points = [10, 20, 13, 24]
points =
10
20
13
24
The first and the third elements represent the x coordinates, and the second and the last
elements – the y coordinates.
4. In order to compute the distance between these points, the following somewhat artificially
looking function call is required:
» dist(points(1), points(2), points(3), points(4))
ans =
5
Obviously, the use of this correct function is not convenient enough.
TOPIC 6. Complex Numbers.
Matlab deals with complex numbers as straightforwardly as with real ones. Below the
introduction to complex numbers is traced.
The notion of a number appeared at the very initial stages of the history for counting
purposes. It was limited to, so called, natural numbers – positive integer values 1, 2, 3 … From
arithmetic operations this infinite set supports summation and multiplication – the sum or
product of two natural numbers is another natural number. The subtraction, however, is not well
supported – there is no natural number the difference between a value and another larger value
would result in. Inclusion of 0 and negative integers resolves the issue. It is the set of integer
numbers – 0, 1, 2, 3 …Schematically, it is represented by the infinite numeric axis, on which
the integers are denoted by equidistant marks. One of them is chosen as 0, and all the marks to
the right denote positive values, while marks to the left – negative values.
This set is not quite good for division. For example, there is no integer value the division of
an odd integer by 2 would result in. Fortunately, there are many unused points on the numeric
axis between the integer marks. Expansion of the set over the points of type a / b, where both a
and b are integers, leads to the set of rational numbers and fully supports division. Obviously,
the set of integers is a subset of rational numbers, and there are infinite rational numbers between
two given integers.
Being infinitely many between infinite amounts of integers, rational numbers do not cover
the entire numeric axis at all. Even more, they occupy just negligible part of the latter. There are
many different cases that cannot be computed in rational numbers. For example, rising to a
rational power (rising to an integer power is well supported), calculation of the circumference
and area of a circle of unit diameter, etc. Therefore the incorporation of irrational numbers is
required. It can be shown that the union of rational and irrational numbers fully covers the
numeric axis. This union is called the set of real numbers, we where using in Matlab so far.
There still remains a room for dissatisfaction. The real numbers do not support rising into
rational powers of negative values. The famous trivial example – there is no real number the
square root of -1 would result in. If the single axis of real numbers is not enough, then nothing
prevents from consideration of the second axis, perpendicular to the first one, and, thus,
introduction of a numeric plane. By choosing their respective zeros to be at the crossing point
and establishing rules given below, we turn it into a special Cartesian plane:
1. Every number z consists of two real components (x, y) – its coordinates along the
horizontal and vertical axis respectively.
2. The sun of (difference between) two numbers z1 = (x1, y1) and z2 = (x2, y2) is a number z3
with components (x1  x2, y1  y2).
3. The product of two numbers z1 = (x1, y1) and z2 = (x2, y2) is a number z3 with components
(x1 x2 - y1 y2, x1 y2 + y1 x2).
Such two-component numbers are called complex numbers.1
According to the stated rules let’s show that the horizontal axis has all the properties of the
axis of real numbers. Consider two arbitrary points on this axis – z1 = (x1, 0) and z2 = (x2, 0).
Their sum is z3 = (x1 + x2, 0) – another number on the same axis, which satisfies the rule of
summation of real numbers. Also, their product is z4 = (x1 x2, 0) – a result that fully agrees with
the rule of multiplication of real numbers.
A complex number i = (0, 1) must be mentioned particularly. Its square results in i2 = (0, 1) *
(0, 1) = (-1, 0) – the negative real unit. By the way, the square of any number from the vertical
axis results in a negative real number. That is why this axis is called imaginary axis.
An alternative way complex numbers can be represented is z = (x, y) = x + i * y.
Instead of Cartesian coordinates every complex number z = (x, y) can be measured in polar
coordinates – the distance from the center z0 = (0, 0), which is abs(z) = (x2 + y2)1/2, and the angle
 = tg y/x. The corresponding representation is z = abs(z) ei = (x2 + y2)1/2 ei arctg y/x.
Task 4. Create an improved version of dist() function, where the points are represented as
complex numbers.
1. Unlike the previous version, here we assume that the points are given in an array. Therefore,
the first statement in a new M-file will be
function result = distance(points)
were the single argument points represents the array of points.
2. For the beginning, let’s imagine the array points has just two complex elements. The
distance between them will be the absolute value of their difference. So, the corresponding
statement appears as
result = abs(diff(points));
diff(array) – computes the differences between successive elements of the row-vector array.
For example, is array is a four-element vector, then diff(array) results in [array(2)
– array(1), array(3) – array(2), array(4) – array(3)].
1
The presented sets of numbers and their properties are introduced and discussed in, for example, W. Rudin,
Principles of Mathematical Analysis, McGraw-Hill Book Company, 1964 [translation: Ó. Ðóäèí, Îñíîâû
ìàòåìàòè÷åñêîãî àíàëèçà, “Ìèð” Ìîñêâà, 1976].
3. Save the M-function in C:\Matlab under distance.m name and switch to “Matlab Command
Window” to test it.
4. The array of the same points from the Task 3 will look like
» points = [10 + i * 20, 13 + i * 24]
points =
10.0000 + 20.0000i
13.0000 + 24.0000i
The distance between them, now, is to be computed as easily as
» distance(points)
ans =
5
5. Actually, we have just created a tool of more capabilities than we dreamed of initially.
Suppose, there is a polygon – a unit-side square, for simplicity. What is its perimeter? The
corners of the square are collected in the following array:
» square = [0, 1, 1 + i, i, 0]
square =
0
1.0000
1.0000 + 1.0000i
0 + 1.0000i
0
The perimeter is the sum of the distances between successive points, or the elements of the
array square in this particular example. This statement literally repeats the definition of the
function diff(), which is the engine of distance M-function. So, the perimeter is to be readily
computed as:
» perim = sum(distance(square))
perim =
4
TOPIC 7. IF statement. Relational and Logical Operators.
Task 5. Combine both temperature-converting functions in one.
1. Start a new M-function face2 as following:
function result = face(degree, mode)
There are two possible conversions. The second argument will control which one to run.
2. Before learning the conversion mode, let the function to prepare both possible answers and
put them in an array:
temp = [degree * 9 / 5 + 32, (degree – 32) * 5 / 9];
result = temp;
3. Save the M-function and test it, for example, for 50 degrees:
» face(50, 2)
ans =
122
10
In the current state the function produces an array, rather than a single value. The first
element is the temperature in Fahrenheit, if the argument degree is assumed to be in Celsius,
while the second – the temperature in Celsius, if assumed opposite. The value of the second
argument mode is absolutely unimportant, as it does not participate in calculations yet.
4. The same test can be executed with one argument as
» face(50)
ans =
2
The acronym face stands for “FAhrenheit and CElsius”.
122
10
ATTENTION: A Matlab function can be executed with different amount of arguments, but not
greater than specified in the first statement of its M-file. For example, the
function face can be executed with one – degree, or two – degree and mode,
arguments. It cannot be called with three or more arguments, which will
contradict with its definition. Meantime, it cannot be called without any
argument, because the value of degree will stay undefined.
All the M-functions have internal standard variables, called nargin and nargout3. The first
one automatically shows the amount of arguments the function was called with. The second
variable shows the amount of variables the function’s result was assigned to.
5. The value of nargin can be conveniently used in face() function in the following way: if only
degree argument is supplied, then the entire two-element array of possible conversions is
returned; otherwise, the first element is returned, if mode equals to 1, and the second – if
mode equals to 2.
Return to the M-file, improve the function as shown below and save the changes:
function result = face(degree, mode)
temp = [degree * 9 / 5 + 32, (degree – 32) * 5 / 9];
if nargin == 1
result = temp;
else
result = temp(mode);
end
if … else … end – runs one of two alternative sets of commands depending on the value of a
condition. Has five-component rigid structure. The first line starts with if
Matlab keyword and continues with the condition. All the commands the
come after the first line will be executed only when the condition results in
true. After this block of commands a line with lone else keyword is required.
All the commands that come after else from the new line will be executed
only when the condition results in false. This block must be closed with lone
end keyword in the last line.
if … end – is equivalent to if…else…end statement, when the block of the else command is
empty. Use this shorter version, if there are commands to be executed, when the
condition is true, and there is nothing to do otherwise.
REMINDER: Matlab keywords are reserved words that cannot be used as variable, function or
M-file names. In the “Matlab Editor / Debugger” these words appear in blue.
Relational Operators
A Simple Condition is a Matlab statement where the left-hand side is compared with the
right-hand side by one of the following Matlab logical operators:
 < – less than. Returns true if its left-hand side operand is less than the right-hand side one,
and false – otherwise.
 > – greater than. Returns true if its left-hand side operand is greater than the right-hand side
one, and false – otherwise.
 == – equal. Returns true if both operands are equal to each other, and false – otherwise.
ATTENTION: In order to compare two values, use the equality operator ‘==’, and never the
assignment operator ‘=’. The difference between them is that the latter changes
the value of the left-hand side operand, while the former only checks the equality
of the operands without modification of their respective values. Matlab generates
3
nargin stands for “Number of ARGuments of Input”. nargout stands for “Number of ARGuments of OUTput”.
‘Missing variable or function’ error, if the assignment operator is used in a
condition.
 ~= – not equal. Opposite to ==, returns true if the operands are not equal to each other, and
false – otherwise.
 <= – less than or equal. Returns true if its left-hand side operand is less than or equal to the
right-hand side one, and false – otherwise.
 >= – greater than or equal. Returns true if its left-hand side operand is greater than or equal
to the right-hand side one, and false – otherwise.
Note that except the first pair, all other operators are made up by two characters, and there
must not be a space between them.
6. Save the M-function and conduct the following testing in the “Matlab Command Window”:
» face(50)
ans =
122
10
» face(50, 1)
ans =
122
» face(50, 2)
ans =
10
» face(50, 3)
ans =
122
10
7. The function perfectly works in case of a single argument, as well as when the value of the
second one is either 1 or 2. Other values understandably lead to the “” error in temp array. In
order to eliminate such failure, let the function print out some warning message and return
the unconverted degree. In other words, the else block will include another nested if
statement for checking the correctness of the value of mode:
function result = face(degree, mode)
temp = [degree * 9 / 5 + 32, (degree – 32) * 5 / 9];
if nargin == 1
result = temp;
else
if mode == 1 | mode == 2
result = temp(mode);
else
‘ERROR: Out of modes’
result = degree;
end
end
Pay special attention to the way strings are specified in Matlab. Unlike many other
applications, here they must be written between single quotes. The strings appear in brown in
the “Matlab Editor / Debugger”.
8. Note that the nested if is controlled by a compound condition that is true when mode is
either 1 or 2.
Logical Operators
A Compound Condition consists of several simple conditions connected by one or more
Matlab logical operators:
 & (“Shift” + “8”) – and. Returns true if its left-hand side and right-hand side conditions
both result in true, and false – otherwise.
 | (“Shift” + “\”) – or. Returns true if at least one of its operands results in true, and false –
otherwise.
 ~| – nor. Returns true if both its operands are false, and false – if at least one of them is true.
 ~ – not. Alters the outcome of its lone operand. Returns true if the operand is false, and false
– otherwise.
size(array) – returns a two-element vector, if array is two-dimensional. The first element shows
how many rows are in array, the second element – how many columns. For
example, if array = [1 2; 3 4; 5 6], then size(array) = [3 2].
size(array, dimension) – returns the number of rows in array, if dimension equals to 1, and the
number of columns – if dimension is 2. It is a familiar story now, isn’t
it?
Download