Vous êtes sur la page 1sur 10

2.

3 Operators, expressions and statements


MATLAB has been described as an expression based language. It interprets and
evaluates typed expressions that are constructed from a variety of elements, such as
numbers, variables, and operators.
2.3.1 Numbers
Numbers can be represented in MATLAB in the usual decimal form (fixed point), with an
optional decimal point, e.g. 1.2345 -123 .0001
A number may also be represented in scientific notation, e.g. 1.2345109 may be
represented in MATLAB as 1.2345e9 also called floating point notation. The number has
two parts: the mantissa, which may have an optional decimal point (1.2345 in this
example) and the exponent (9), which must be an integer (signed or unsigned). Mantissa
and exponent must be separated by the letter e (or E). The mantissa is multiplied by the
power of 10 indicated by the exponent.
2.3.2 Arithmetic operators and Precedence of operators
The evaluation of expressions is achieved by means of arithmetic operators.
The arithmetic operations on two scalar constants or variables are shown in Table 2.1
Table 2.1 Arithmetic operations between two scalars
Operation Algebraic form MATLAB
Addition a+b a+b
Subtraction ab a-b
Multiplication ab a*b
Right division a/b a/b
Left division b/a a\b
Power ab ab

Several operations may be combined in one expression, e.g. g * t 2.


MATLAB has strict rules about which operations are performed first in such cases; these
are called precedence rules. The precedence rules for the operators in Table 2.1 are shown
in Table 2.2. Note that parentheses (round brackets) have the highest precedence.
When operators in an expression have the same precedence the operations are carried out
from left to right. So a / b * c is evaluated as (a / b) * c and not as a / (b * c).
Table 2.2 Precedence of arithmetic operations
Precedence Operator
1 Parentheses (round brackets)
2 Power, left to right
3 Multiplication and division, left
to right
4 Addition and subtraction, left to
right
NOTE:
* The colon operator has a lower precedence than + as the following shows: 1+1:5
The addition is carried out first, and then a vector with elements 2, , 5 is initialized.
* The transpose operator () has the highest precedence and exponentiation has a higher
precedence than multiplication.

2.3.3. Expressions and Statements


An expression is a formula consisting of variables, numbers, operators, and function
names. It is evaluated when you enter it at the MATLAB prompt, e.g. evaluate 2 as
follows: 2 * pi
MATLABs response is:
ans =
6.2832
Statement is a combination of a variable and an expression.
MATLAB statements are frequently of the form variable = expression e.g.
s = u * t - g / 2 * t . 2;
Basically any line that you enter in the Command Window or in a program, which
MATLAB accepts, is a statement, so a statement could be an assignment, a command, or
simply an expression, e.g.
x = 29; % assignment
clear % command
pi/2 % expression
However, the MATLAB documentation tends to refer to all of these as functions.
Statements on the same line may be separated by commas (output not suppressed) or
semicolons (output suppressed), e.g.
a = 2; b = 3, c = 4;
Note that the commas and semicolons are not technically part of the statements; they are
separators.
Statements may involve array operations, in which case the variable on the left-hand side
may become a vector or matrix.
The distinction between MATLAB statements, commands and functions can be a little
fuzzy, since all can be entered on the command line. However, it is helpful to think of
commands as changing the general environment in some way, e.g. load, save, and clear.
Statements do the sort of thing we usually associate with programming, such as evaluating
expressions and carrying out assignments, making decisions (if), and repeating (for).
Functions return with calculated values or perform some operation on data, e.g. sin, plot.

2.3.4 Vectorization of formulae


MATLAB has four further arithmetic operations sometimes called array operations, or
element-by-element operations. With array operations you can easily evaluate a formula
repeatedly for a large set of data.
This is one of MATLABs most useful and powerful features. E.g. An amount of money A
invested over a period of n years with an annual interest rate of r grows to an amount
A(1+r)n. Suppose we want to calculate final balances for investments of 750, 1000, 3000,
5000 and 11 999, over 10 years, with an interest rate of 9 percent.
The following program uses array operations on a vector of initial investments to do this.
>>format bank
A = [750 1000 3000 5000 11999];
r = 0.09;
n = 10;
B = A * (1 + r) n;
disp( [A B] )
Output:
750.00 1775.52
1000.00 2367.36
3000.00 7102.09
5000.00 11836.82
11999.00 28406.00
2.4 Output and format
There are two straightforward ways of getting output from MATLAB:
1. by entering a variable name, assignment or expression on the command line, without a
semicolon;
2. with the disp statement, e.g. disp( x ).
You can also use disp to display a message enclosed in single quotes (called a string).
Single quotes which are part of the message must be repeated, e.g. disp( Pilate said,
What is truth? );
To display a message and a numeric value on the same line use the following trick:
>>x = 2;
Disp ( [The answer is , num2str(x)] );
MATLAB has the following two basic output rules:
1). It always attempts to display integers (whole numbers) exactly. However, if the integer
is too large, it is displayed in scientific notation with five significant digits, e.g.
1234567890 is displayed as 1.2346e+009 (i.e. 1.2346109). Check this
by first entering 123456789 at the command line, and then 1234567890.
2). Numbers with decimal parts are displayed with four significant digits. If the value x is
in the range 0.001<x 1000 it is displayed in fixed point form, otherwise scientific
(floating point) notation is used, in which case the mantissa is between 1 and 9.9999, e.g.
1000.1 is displayed as 1.0001e+003. This is what is called the default format.
If you want values displayed in scientific notation (floating point form) whatever their size,
enter the command format short e. All output from subsequent disp statements will be in
scientific notation with four significant digits, until the next format command is issued. E.g
>> format short e
>> 0.0123456
ans =
1.2346e-002
The command format long e also gives scientific notation, but with 15 significant digits.
E.g
>> format long e
>> 1/7
ans =
1.428571428571429e-001
And you use format long to get fixed point notation with 15 significant digits, e.g.
>> format long
>> pi
ans =
3.141592653589793
Use format bank for financial calculations; you get fixed point with two decimal digits (for
the cents). E.g.
>> format bank
>> 10000/7
ans =
1428.57

2.5. Relational operators


In analyses, you may be call to test conditions.
A condition is usually a logical expression, i.e. an expression containing a relational
operator, and which is either true or false. MATLAB allows you to use an arithmetic
expression for condition.
If the expression evaluates to 0 it is regarded as false; any other value is true.
If condition is true, statement is executed, but if condition is false, nothing happens.
condition may be a vector or matrix, in which case it is true only if all its elements are
non-zero. A single zero element in a vector or matrix renders it false.
Here are some examples of logical expressions involving relational operators, with their
meanings in brackets:
b2 < 4*a*c (b2 <4ac)
x >= 0 (x 0)
a = 0 (a 0)
b2 == 4*a*c (b2 = 4ac)
The relational operators are shown in Table 2.3.
Relational Meaning
operator
< less than
<= less than or equal
== equal
= not equal
> greater than
>= greater than or equal

2.6. Functions
In MATLAB you will use bothbuilt-in functions as well as functions that you create
yourself.
Built-in Functions
MATLAB has many built-in functions. These include sqrt, cos, sin, tan, log, exp, and atan
(for arctan) as well as more specialized mathematical functions such as gamma. MATLAB
also has several built-in constants, including pi. As examples consider:
1) >> log(exp(3))
ans =
3
The function log is the natural logarithm, called ln in many texts.
2) >> sin(2*pi/3)
ans =
0.8660
User-Defined Functions
In this section we will show how to use inline to define your own functions.
Heres how to define the polynomial function f (x) = x2 + x + 1:
>> f = inline(x2 + x + 1, x)
f=
Inline function:
f(x) = x^2 + x + 1
The first argument to inline is a string containing the expression defining the function. The
second argument is a string specifying the independent variable.
Once the function is defined, you can evaluate it:
>> f(4)
ans =
21
MATLAB functions can operate on vectors as well as scalars. To make an inline function
that can act on vectors, we useMATLABs vectorize function.
Here is the vectorized version of f (x) = x2 + x + 1:
>> f1 = inline(vectorize(x2 + x + 1), x)
f1 =
Inline function:
f1(x) = x.^2 + x + 1
Note that ^ has been replaced by .^. Now you can evaluate f1 on a vector e.g:
>> f1(1:5)
ans =
3 7 13 21 31
As remark, one can also define functions of two or more variables:
>> g = inline(u2 + v2, u, v)
g=
Inline function:
g(u,v) = u^2+v^2
2.7. Loops
A loop specifies that a command or group of commands should be repeated several times.
The easiest way to create a loop is to use a for statement.
The loop begins with the for statement and ends with the end statement.
For example, to generate a list of n factorial where n! = 1 2 3 . . . (n 1) n.
Here is a simple example that computes and displays 10! = 10 9 8 2 1
>> f = 1;
for n = 2:10
f = f*n;
end
f
f=
3628800
The command between those statements is executed a total of nine times, once for each
value of n from 2 to 10. We used a semicolon to suppress intermediate output within the
loop.
2.8 Complex numbers
MATLAB does most of its computations using complex numbers, that is, numbers of the
form a + bi, where a and b are real numbers. In Matlab, the special values i and j stand
for 1 . Although you may never have occasion to enter a complex number in a
MATLAB session, MATLAB often produces an answer involving a complex number. For
example, many polynomials with real coefficients have complex roots as well as some
common functions return complex values for certain values of the argument. For example,
>> log(-1)
ans =
0 + 3.1416i
The symbol i may be used to assign complex values, e.g.
z = 2 + 3*i represents the complex number 2+3i (real part 2, imaginary part 3).
NB: in response to the input prompt (remember, no semicolon).
The imaginary part of a complex number may also be entered without an asterisk, e.g. 3i.
All the arithmetic operators (and most functions) work with complex numbers, e.g. sqrt(2
+ 3*i), exp(i*pi).
There are some functions that are specific to complex numbers. If z is a complex number
real(z), imag(z), conj(z) and abs(z) all have the obvious meanings. A complex number may
be represented in polar coordinates, i.e. z = rei. angle(z) returns between and .
abs(z) returns the magnitude r.
For complex matrices, the operations and . behave differently.
The operator is the complex conjugate transpose, meaning rows and columns are
interchanged, and signs of imaginary parts are changed.
The . operator, on the other hand, does a pure transpose without taking the complex
conjugate. E.g, consider the complex matrix a with the statement
a = [1+i 2+2i; 3+3i 4+4i]
which results in
a=
1.0000 + 1.0000i 2.0000 + 2.0000i
3.0000 + 3.0000i 4.0000 + 4.0000i
The statement
a
then results in the complex conjugate transpose
ans =
1.0000 - 1.0000i 3.0000 - 3.0000i
2.0000 - 2.0000i 4.0000 - 4.0000i
whereas the statement
a.
results in the pure transpose
ans =
1.0000 + 1.0000i 3.0000 + 3.0000i
2.0000 + 2.0000i 4.0000 + 4.0000i

4. Compute to 15 digits:
(a) cosh(0.1).
(b) ln(2). (Hint: The natural logarithm in MATLAB is called log, not ln.)
(c) arctan(1/2). (Hint: The inverse tangent function inMATLABis called atan, not arctan.)
5) Solve the system of linear equations
3x + 4y + 5z = 2
2x 3y + 7z= 1
x 6y + z = 3.
Check your answer using matrix multiplication .
6) What are the values of x and a after the following statements have been executed?
Z=3.5-1.25i;
a= -2i;
R=z-a/3;
Y=cos(R-i);
Conj (y);
y;
P=R^a;

Vous aimerez peut-être aussi