Sie sind auf Seite 1von 24

A.Y.

2016/2017

Mathematical Methods for Engineering


MATLAB introduction Lecture I

October 13, 2016

Aurelio Giancarlo Mauri


aureliogiancarlo.mauri@polimi.it

MME - Lecture 1 - Aurelio Giancarlo Mauri


MATLAB

MATLAB (MATrix LABoratory) is an interactive software system for:


scientific computing
statistical analysis
vector and matrix computations
graphics
symbolic computation

MME - Lecture 1 - Aurelio Giancarlo Mauri


Documentation

1 >> ver
2 --------------------- ver shows the Matlab version we
3 MATLAB Version: 8.0.0.783 (R2012b)
4 MATLAB License Number: 722761 are working on.
5 ....

1 >> help sqrt help shows how to use a


2 SQRT Square root . function and doc displays online
3 ... documentation about a
4 >> doc sqrt
command.

1 >> pwd
pwd returns the name of the current
2 C :\ Programmi \ MATLAB \ R2006b \ work directory (in this example it is the
3 >> ls default directory)
4 . etc license . txt simulink ls returns the list of the files in the
5 .. extern notebook
current directory.

MME - Lecture 1 - Aurelio Giancarlo Mauri


Default variables and mathematical functions

1 >> pi
2 ans =3.1416
Some real constants are allocated by 3 >> i
default: 4 ans =0+1 i
5 >> inf
6 ans = Inf

Default mathematical functions Matlab provides a


Function Meaning large number of
standard elementary
sin, cos, tan sine, cosine, tangent mathematical
asin, acos, atan arcsine, arccosine, arctangent functions. To have
exp exponential more information,
log, log2, log10 natural logarithm, base 2, base 10 type the command
sqrt square root help elfun
abs absolute value

MME - Lecture 1 - Aurelio Giancarlo Mauri


Elementary operations
By considering the previous values assigned to the variables a e b, we can
compute:
1 >>a = 5 ;
2 >>b = 3 ;
3 >> a + b addition
4 ans =8
5 >> a - b subtraction
6 ans =2
7 >> a / b division
8 ans =1.667
9 >> a * b mu ltiplica tion
10 ans =15
11 >> a ^ b ex ponentia tion
12 ans =125

We can compute more complicated expressions, by paying attention to the correct


use of the brackets (only round brackets!):
1 >> (((2* a - b ) ^2 -3) *( b ^3) ) /2
2 ans =621

MME - Lecture 1 - Aurelio Giancarlo Mauri


Floating-point arithmetic

Computing environments use floating-point arithmetic, which involves a finite set


of numbers with finite precision. Given a real number x the typical
floating-point implementation represents its identifier x in the normalized form:

x = (1)s (0.a1 a2 ...at ) e = (1)s m et

where
s is the sign: 0 (+) or 1 (-) ;
is the base system ;
e is the exponent : e [L, U], L < 0, U > 0 ;
m = a1 a2 ...at is the mantissa or fractional part.

MME - Lecture 1 - Aurelio Giancarlo Mauri


Single and double precision

Let N be the number of available memory allocation for the number x

Single precision N = 32, t = 23, e = N t 1


1 bit for s
8 bits for e
23 bits for m

Double precision N = 64, t = 52, e = N t 1


1 bit for s
11 bits for e
52 bits for m

To avoid multiple representations of a number: a1 6= 0

MME - Lecture 1 - Aurelio Giancarlo Mauri


Floating point set in MATLAB double precision: N = 64
Let be F(, t, L, U) = {0} {x R : x = (1)s m e t}.
In MATLAB we will use the set F(2, 53, 1021, 1024) following the standard IEEE
754.
Some consequences derive from this choice:
there exits an upper limit for the machine: (1 2t ) 2U = 1.7977 10308 )
there exits an lower limit for the machine: 2L1 = 2.2251 10308 )
Let be x R and in the range of F. Let be fl(x) the representation of x in F:
its relative error is given by:
x fl(x) 1 1
Erel (x) = m = 2.2204e 16
|x| 2 2
In MATALB you can obtain these numbers with:
1 >> realmax maximum floating point number
2 >> realmin minimum floating point number
3 >> eps the minimum number if added to 1 , gives the result
greater than 1.

MME - Lecture 1 - Aurelio Giancarlo Mauri


Number format

It is convenient to change the default format used by MATLAB to represent the


number. Variables visualization can be changed by using the command format as
following:
format short
fixed coma with 5 digits (default format): pi = 3.1416
format long
fixed coma with 15 digits: pi = 3.14159265358979
format short e
mobile coma with 5 digits: pi = 3.1416e + 00
format long e
mobile coma with 15 digits: pi = 3.141592653589793e + 00

MME - Lecture 1 - Aurelio Giancarlo Mauri


Vectors and matrices
A vector is defined as follows
1 >> v =[1 2 3]
2 v= 1 2 3
row vector

A matrix is defined as follows


1 >> M =[ 1 2 ; 3 4]
2 M= 1 2 2 2 matrix (the ; is used to start a
3 3 4 new line)
4 >> v1 =[10; 20]
5 v1 =10
6 20 column vector

Transposition, denoted by a prime after the vector variable, transforms a row


vector into the corresponding column vector and viceversa:
1 >> v2 =v
2 v2 =1
3 2
4 3

MME - Lecture 1 - Aurelio Giancarlo Mauri


When we define a matrix, the dimensions of rows and columns must agree:
1 >> M1 =[1 2; 3]
2 ??? Error using == > vertcat
3 CAT arguments dimensions are not consistent .

Some default matrices are:


zeros(m, n): m n matrix with null elements
ones(m, n): m n matrix with all elements equal to 1
eye(m, n): m n matrix with 1s on the diagonal and 0s elsewhere
rand(m, n): m n matrix of random numbers

1 >> eye (3 ,3)


2 ans = 1 0 0
3 0 1 0
4 0 0 1

MME - Lecture 1 - Aurelio Giancarlo Mauri


The command size returns the dimensions of a matrix or vector:
1 >> a =1;
2 >> size ( a )
a scalar is composed by 1 row
3 ans =1 1 and 1 column

1 >> size ( v ) the vector v is composed by 1


2 ans =1 3 row and 3 columns
In this case we can use the command length
1 >> length ( v )
2 ans =3

1 >> size ( M ) matrix M is composed by 2 rows


2 ans =2 2 and 2 columns

MME - Lecture 1 - Aurelio Giancarlo Mauri


Using the command : we select a whole row or column of a matrix:

1 >> M (2 ,:) indicates the second row of M


2 ans =3 4 (: selects all the columns)
To select one element of a matrix, we must indicate the position of such an
element: M(i,j) = element located in the i-th row and j-th column.
1 >> M (2 ,1)
2 ans =3
3 >> v1 (2)
4 ans =20

1 >> A =[1 3;5 7;9 11];


2 >> A ( end ,2)
3 ans =11
A(end,i): element located in the last row
4 >> A ( end ,1) and in the i-th column.
5 ans =9

MME - Lecture 1 - Aurelio Giancarlo Mauri


1 >> A (2:3 ,2) A(i:j,k): selects the elements in the k-th column
2 ans = 7
3 11 from row i to row j

1 >> A (: ,2) =[1; 1; 1]


2 ans = 1 1 A(i,:)=[..] assigns new values to row i
3 5 1 A(:,j)=[..] assigns new values to column j
4 9 1

1 >> A (3 ,:) =[]


2 ans = 1 1 A(i,:)=[] deletes the i-th row
3 5 1

MME - Lecture 1 - Aurelio Giancarlo Mauri


Operations with matrices and vectors

Product of a vector/matrix with a scalar k


k x: multiplies entries of x by k
Sum of vectors/matrices
x + y: sums vectors/matrices componentwise
Difference of vectors/matrices
x y: subtracts vectors/matrices componentwise
Products of vectors/matrices
x. y multiplies vectors/matrices componentwise
Division of vectors/matrices
x./y: divides vectors/matrices componentwise
Products of a matrix with a vector
A x: performs the row by column product (the dimensions of the factors
must agree)

MME - Lecture 1 - Aurelio Giancarlo Mauri


if, for and while
Conditional instructions: if
1 if logical statement The first instruction is executed if the logical
2 instruction #1
3 else statement is true, otherwise the second
4 instruction #2 instruction is performed.
5 end

for loop while loop


1 for variable = start : step : finish 1 while condition
2 instructions 2 instructions
3 end 3 end

The for loop repeats the instructions while the variable (counter) runs its values.
start and finish represent the first and the last values assumed by the counter,
step is the increment on the counter value at each repetition of the loop.
The while loop repeats the instructions while the logical condition is true.
If you unwillingly create an infinite loop (a loop that never ends on its own), stop
execution of the loop by pressing Ctrl + C.

MME - Lecture 1 - Aurelio Giancarlo Mauri


Examples

1 >> for i =1:2


1 >> A =[1 2 3;4 5 10;7 8 9]; 2 for j =1:2
2 >> if ( A (2 ,3)=6) 3 B (i , j ) = i * j ;
3 A (2 ,3) =6; 4 end
4 end 5 end
5 >> A (2 ,3) 6 >> B
6 ans =6 7 ans =1 2
8 2 4

Matlab logical operators


< , <= less than , less or equal than
> , >= greater than , grater or equal than on italian
== equal keyboards
= different from
Activate BlocNum, then
&& logical end
Alt+126.
|| logical or
logical not

MME - Lecture 1 - Aurelio Giancarlo Mauri


Function

The function is an interactive tool since it requires the specification of a number


of input arguments and produces a number of output variables. The functions are
defined within a text files named with extension .m. An m-file must be saved in
the same directory where it has to be executed, or in a directory whose path is
included in the list of paths automatically accessed by MATLAB.
1 function [ output values ]= function_name ( input values )
2 % comments

The file name where the function is saved must be equal to that of the function:
function name.m.
The function comments are displayed upon typing
1 >> help function_name
2 comments

The variables defined internally to a function are deleted after the function
execution is returned to the main program (local variables) and only the output
variables are still defined.
MME - Lecture 1 - Aurelio Giancarlo Mauri
Example

1 function [ Sum , Prod , Diff , Div ]= operations (x , y )


2 % f u n c t i o n [ sum , prod , diff , div ]= o p e r a t i o n s (x , y )
3
4 % d e s c r i b e the o p e r a t i o n + ,* , - ,/ between
5 % two scalars x and y
6 Sum = x + y ;
7 Prod = x * y ;
8 Diff =x - y ;
9 Div = x / y ;

The function runs by typing, for example:


1 >> [a ,b ,c , d ]= operations (5 ,3) ;
2 >> c
3 c =2

MME - Lecture 1 - Aurelio Giancarlo Mauri


Graphics: cartesian axes
The cartesian axes are generated by defining a sequence of points x and the
sequence y of the values of the function at each point x.
A sequence of real numbers can be generated in 2 ways:
1 >> x = x1 : step : xn ;

produces values between x1 and xn with the increment given by step (same
syntax as the for loop);
1 >> y = linspace ( x1 , xn , N )

produces N uniform intervals between x1 and xn.


Examples:

1 >> x =(1:0.1:4) 1 >> y = linspace (1 ,4 ,400)


2 x = 1.0000 2 x = 1.0000
3 1.1000 3 1.0075
4 1.2000 4 1.0150
5 ... 5 ...

MME - Lecture 1 - Aurelio Giancarlo Mauri


Example: plot the function x sin(x)

construct the x-axis 1 >> x = linspace (0 , pi ,100) ;

compute the function at each point and 1 >> y = x .* sin ( x ) ;


plot the pairs (x,y) 2 >> plot (x , y )

Main graphics options:

Line type - : ...


Line color b g r ...
Marker type . x ...
Marker size
Line width

Example:
1 >> plot (x ,y , -- go , Markersize ,3 , Linewidth ,2)

MME - Lecture 1 - Aurelio Giancarlo Mauri


Exercises

Exercise 1.1
Let x=10. Compute:

exp(sin(x 2 )) + cos(x)
y=
2 x + 5 log(x)

Given a vector x with positive, negative and null entries, replace all negative
entries with zero.
Generate a magic square (M = magic(n), n being integer greater than 0) and
calculate the row and column sums.

MME - Lecture 1 - Aurelio Giancarlo Mauri


Exercise 1.2 - Flow Control
Write a for loop to find the mean of 3 random numbers 20 times and store
the result in a vector A.
Write a program to calculate the sum 1+2+3+...+N, where N is a given
positive integer. Display the computed sum and check if the result is a
multiple of 20.
Write a function to calculate N! (N factorial), where N is a non-negative
integer. Note that 0! is defined to be 1.
Make a function file divide.m. This function must divide a number N by 5
till the new obtained number M is smaller than 10. Display the number M
and the number that represents how many times the number N is divided by
5.

MME - Lecture 1 - Aurelio Giancarlo Mauri


Exercise 1.3 - Plot
Try to plot some graphs:
a) Generate a vector X with values from 1 to 100
b) Generate a vector Y containing X 2 .

c) Generate a vector Z containing 11X
d) Plot Y against X, using a red line with stars at each data point. (type
help plot if you need to)
e) On the same graph, plot Z against X using a green line with squares at each
point ( use hold on command)

MME - Lecture 1 - Aurelio Giancarlo Mauri

Das könnte Ihnen auch gefallen