matlab introduction

69
 Matlab

Upload: paulo-bruno

Post on 17-Jan-2016

9 views

Category:

Documents


0 download

DESCRIPTION

Matlab Introduction

TRANSCRIPT

Page 1: Matlab Introduction

   

Matlab

Page 2: Matlab Introduction

   

Overview

Matlab is a SW designed for the numerical calculation on scientific and engineering applications.

Web site http://www.mathworks.com/

The main Matlab functions are the following:

1) Plot 2D and 3D ; 2) Linear Algebra ; 3) Interpolation and approximation ; 4) ODE and PDE solution ;

Page 3: Matlab Introduction

   

How to run matlab on linux OS?

To run matlab in your linux/unix OS we have follow these steps:

1) Open a new terminal

2) type cd /home/Matlab_folder 3) type ./bin/matlab

After these 3 steps we should have a screenshot like the

following

Page 4: Matlab Introduction

   

Matlab Prompt

Page 5: Matlab Introduction

   

Help

To obtain information about Matlab commands select “help” in the main

menu as in the following screenshot:

Page 6: Matlab Introduction

   

Help

On search area you can enter the command that we need information and get syntax, parameters, input and / or output etc.. etc..

For example, writing the command '"plot" you will get information on that command. In particular, on the left column will be all the items of the manual where there is information about "plot", clicking on one of these items you will get the information about the selected item and the right column .

Page 7: Matlab Introduction

   

Help Matlab example

Page 8: Matlab Introduction

   

Variables

In general on Matlab we can define variables, functions and programs. The generic variable will be defined as follows: → variable_name = instruction ; where the output of the instruction is assigned to “ variable_name ”; Each variable must be identified with an alphanumeric string that can not start with a number and can not contain special characters (eg: var01 is a valid name 01 * var is not a invalid name). You have to pay attention to the fact that the variable name is case sensitive so you do not confuse the uppercase and lowercase.

Page 9: Matlab Introduction

   

Variables

On Matlab should not be defined the type and the size of the variable before use it (opposite in C, C++, Fortran);

To view and edit a variable is available in the graphical user interface the “Workspace”;

Each variable is added to the “Workspace” after the definition;

Each variable can be deleted from the workspace with the command “--> clear variable_name”;

The command "clear all" allows to delete all the variables created by a single user, however, it strongly discouraged the use of this command inside a script (with the exception of line 1) because it can destroy all the defined variables .

Page 10: Matlab Introduction

   

Variables and workspace

Page 11: Matlab Introduction

   

Variables examples

Example: Create a variable named "var" and assign it the value 2. Check the result using the “Workspace”.

Commands : → var=2; We create the variable and we assign it the value 2

The variable “var” will appear on the “Workspace” in the list of variables.

Page 12: Matlab Introduction

   

Variables examples

Page 13: Matlab Introduction

   

Format

In Matlab, we can choose the format in which numbers represent the variables values using the command "format". To use this command we must be respected the following syntax: → format type ; → format; Where:

format by itself specifies the default display type, format short (that is, 5-digit scaled, fixed-point values).

format type changes the format to the specified type.

Page 14: Matlab Introduction

   

Format

short (default) Scaled fixed-point format, with 4 digits after the decimal point. For example, 3.1416.

long Scaled fixed-point format with 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.141592653589793.

shortE Floating-point format, with 4 digits after the decimal point. For example, 3.1416e+000.

longE Floating-point format, with 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.141592653589793e+000.

For more information check Matlab Help

Page 15: Matlab Introduction

   

Costants

In Matlab, there are some constants that are always available in the workspace. To call these constants we must follow the following syntax: → costant_name Some constants available on Matlab are the following: 1) pi = 3.1415927... Costant π 2) i Imaginary unit 3) eps Floating-point relative accuracy

(releted to the machine used)

4) inf Infinity 5) nan NotANumber

Page 16: Matlab Introduction

   

Matrices and arrays

To define a matrix/array in Matlab we must follow the following syntax:

→ A=[a b c; d e f ; g h i ] Through this command we will get a 3x3 matrix where rows will be (a, b, c), (d, e, f) and (g,h,i). In general, to write an array/matrix we should follow the following rules :

1) The elements of a same row are separated by a comma or a space;

2) Each row, except the last, must end with a semicolon;

3) The array elements must be enclosed in “ [ ] ”;

4) Pay attention to the size of rows and columns pointing out that the insertion is done by rows.

Page 17: Matlab Introduction

   

Matrices and arrays

Example: Define the matrix A in Matlab and extract the element a11, the second row and the third column

A=[1 6 915 22 6617 4 1 ]

Page 18: Matlab Introduction

   

Matrices and arrays

To define the array we will use the following instructions:

A=[1 6 9; 15 22 66 ; 17 4 1]

A(1)

A(2,:)

A(:,3)

The results are as follows.

Page 19: Matlab Introduction

   

Matrices and arrays

Page 20: Matlab Introduction

   

Matrices and arrays

An array of size "n" can be seen as a matrix composed of a single row, then to define an array we can follow this syntax:

→ a=[a,b,c,d,e,.........,n];

In Matlab there are some commands that allow the insertion of special matrices such as: 1) eye(n,n) ; Identity Matrix nxn 2) zeros(n,m); Matrix nxm all elements equal to zero 3) ones(n,m); Matrix nxm all elements equal to one. 4) triu(X,k); Upper triangular part of matrix part of matrix X k = 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal 5) tril(X,k); Lower triangular part of matrix X

Page 21: Matlab Introduction

   

Matrices and arrays

To get the elements of a matrix we must use the following instructions: → A=[ a,b,c ; d,e,f ; g,h,i ]; Generic matrix 3x3 → b=A(i,j); The variable b will be equal to aij

In general it may be necessary get a row, a column or a part of them, in this case we will have to use the symbol “ : “ as follow: → A(: ,1); We get the first column of the matrix A → A(1, :); We get the first row of the matrix A → A(1: 2,1); We get the column array containing the first two elements of the first column of the matrix A

Page 22: Matlab Introduction

   

Matrices and arrays

A useful command is the command "diag ()" it means you get a column array containing the elements of the main diagonal of a square matrix. Through this command you can build a square diagonal matrix following the instructions: → b=[a,b,c]; → C=diag(b); C will be a 3x3 diagonal matrix where the elements of the main diagonal are the elements of the array b

To perform the inverse of a square matrix we can use the command “ inv( A )” , whereas to get the transposed matrix we can use the command “A' “.

Page 23: Matlab Introduction

   

Matrices and arrays

The sum of two matrices of the same size can be obtained through the following statement: → A+B;

The product of two matrices of appropriate dimensions, is obtained by the following statement:

→ A*B;

The exponential of a matrix A is obtained by the following statement:

→ expm( A ) ;

This statement must not be confused with exp (A) which perform the exponential of the individual elements of the matrix.

Page 24: Matlab Introduction

   

Matrices and arrays

The determinant of a matrix A is obtained using the following command: → det(A);

The rank of a matrix A can be calculated using the following command: → rank(A);

Given two matrices A and B may be necessary to carry out the multiplication (or division) 'element by element' in this context we must use the commands ' .* ' , ' ./ ' e ' .^ ' (The last command performs an element-by-element esponential).

Page 25: Matlab Introduction

   

Matrices and arrays

Example: define the matrix B in matlab and calculate:

1) Determinant;

2) Rank;

3) Exponential matrix;

4) Esponential element-by- element;

5) Then extract the first row and the second column.

B=[1 0 00 4 00 0 6 ]

Page 26: Matlab Introduction

   

Matrices and arrays

We will use the following commands:

d=[1,4,6]

B=diag(d)

det(B)

rank(B)

expm(B)

exp(B)

B(1,:)

B(:,2)

Note that expm (B) and exp (B) do not provide in general the same results.

Page 27: Matlab Introduction

   

Matrices and arrays

The instruction expm(A) will perform the calculation of the following series :

In the case of diagonal matrices the series is equal to the following matrix:

e A=∑k=0

Ak

k !

expm A=e A=[ea11 0 00 ea22 00 0 ea33]

Page 28: Matlab Introduction

   

Matrices and arrays

The instruction exp(A) performs the exponential “element-by-element” on the matrix A, for a diagonal matrix we obtain this result:

exp A=[ea11 e0 e0

e0 ea22 e0

e0 e0 ea33 ]=[ea11 1 11 ea22 11 1 ea33]

Page 29: Matlab Introduction

   

Matrices and arrays

Page 30: Matlab Introduction

   

Matrices and arrays

The use of the command inv(A) can be dangerous when the matrix has determinant close to zero. Below we report an example:

Using the command det(A) we get:

>>det(A)= 6.6613e-16

we can observe as det(A) is close to zero then the command inv(A) could provide bad results.

A=[1 2 34 5 67 8 9]

Page 31: Matlab Introduction

   

Matrices and arrays

Exercize: define the matrix A and calculate the product A*inv(A).

We will get in this case after using the command B = inv (A) the following results for the product A * B (theoretically equal to the identity matrix I):

This result is completely differenty from the theoretical so we have to be very careful when we use the command inv (A)

A∗B=[0,25 1 −0,25−2 4 −1

−4,25 7 −1,75 ]

Page 32: Matlab Introduction

   

Polynomial

The command "poly" is used to define a polynomial from its roots. : Assuming that "a" and "b" are the roots of a generic second-order polynomial, using the "poly" you will get the corresponding polynomial →polynomial_name= poly( [a b]);

To calculate the roots of a polynomial, we can use the following command: → roots( polynomial_name );

Page 33: Matlab Introduction

   

Mathematical Functions

round(x) Round to nearest integer. Positive elements with a fractional part of 0.5 round up to the nearest positive integer. Negative elements with a fractional part of -0.5 round down to the nearest negative integer. For complex X, the imaginary and real parts are rounded independently.

fix(x) Rounds the elements of x toward zero, resulting in an array of integers. For complex x, the imaginary and real parts are rounded independently.

floor(x) Rounds the elements of x to the nearest integers less than or equal to x. For complex x, the imaginary and real parts are rounded independently.

ceil(x) Rounds the elements of A to the nearest integers greater than or equal to A. For complex A, the imaginary and real parts are rounded independently.

sign(x) Returns an array Y the same size as X, where each element of Y is:

1 if the corresponding element of X is greater than zero 0 if the corresponding element of X equals zero -1 if the corresponding element of X is less than zero

Page 34: Matlab Introduction

   

Matematical Functions

x=[-1.8 -0.1 3.4 5.6 7.0]

round(x) >> ans = -2 0 3 6 7

fix(x) >> ans = -1 0 3 5 7

floor(x) >> ans = -2 -1 3 5 7

ceil(x) >> ans = -1 0 4 6 7

Page 35: Matlab Introduction

   

Mathematical Functions

abs(x) returns an array Y such that each element of Y is the absolute value of the corresponding element of X.

sqrt(x) square root of x

exp(x) exponential function

log(x) (or log10(x) logaritm in base e , 10 and 2 or log2(x))

Page 36: Matlab Introduction

   

Matehmatical Functions

sin(x) Sine of argument in radians

cos(x) Cosine of argument in radians

tan(x) Tangent of argument in radians

cot(x) Cotangent of argument in radians

asin(x) Inverse sine; result in radians

acos(x) Inverse cosine; result in radians

atan(x) Inverse tangent; result in radians

acot(x) Inverse cotangent; result in radians

sinh(x) Hyperbolic sine of argument in radians

cosh(x) Hyperbolic cosine of argument in radians

tanh(x) Hyperbolic tangent of argument in radians

Page 37: Matlab Introduction

   

For and While

In Matlab, we can define cycles For and While using the following instructions: → for variable=values → statements 1; → ....................; Sintax for instruction → statements n; → end → while expression → comando 1; → ..................; Sintax while instruction → comando n; → end

Page 38: Matlab Introduction

   

If-Elseif-Else

The syntax for the instruction If-Elseif-Else is:

→ if expression 1 → statemen 1; → ..................; → statement n; → elseif expression 2 Sintax If-Elseif-Else instruction → statement a; → ..................; → statement z; → else → statement xa; → ...................; → statement xz; → end; You can also use nested instructions If-Elseif-Else.

Page 39: Matlab Introduction

   

Case

The syntax for the instruction Case is the following:

→ switch switch_expression → case case_expression → statement 1; → ................. ; → statement n; → case case_expression Sintax Case instruction → statement a; → ..................; → statement z; → otherwise → statement; → end

Page 40: Matlab Introduction

   

Plot 2D and 3D

In Matlab to plot graphs must first open a graphics window, this is done using the following command: → figure(num); where the string 'num' is the number of the graphics window to be opened and must be a natural number.

To clean the graphics window in use we must use the following command: → clf(num);

Page 41: Matlab Introduction

   

Plot 2D and 3D

Page 42: Matlab Introduction

   

Plot 2D and 3D

To draw a 2D graph we can use the command 'plot', an example of the use of this command is: → figure(1); → x=-1:0.1:1; → y=exp(x); → plot(x,y,'r'); grid → title(' Exponential function'); → xlabel('x'); → ylabel('y=exp(x)');

In particular, with these instructions we will get the graph of the exponential function for x values between -1 and 1. The parameter 'r' allows as to choose the color of the graph of the function (in this case red), whereas the command 'grid' draws a grid on the graph. Finally, the command 'title', 'xlabel' and 'ylabel' allows us to put a title for the graph and labels on x and y axes.

Page 43: Matlab Introduction

   

Plot 2D and 3D

Page 44: Matlab Introduction

   

Plot 2D and 3D

To choice the graphics colors we can follow the following table: k Black b Blu g Green r Red c Cyan m Magenta w White y Yellow Be careful avoid the use of white to draw a white line on a white background ( invisible)

Page 45: Matlab Introduction

   

Plot 2D and 3D

Line Style Specifiers :

'-' Solid line (default) '–' Dashed line

':' Dotted line '-.' Dash-dot line

'none' No line

Marker Specifiers :

'+' Plus sign 'o' Circle

'^' Upward-pointing triangle '.' Point

'x' Cross '*' Asterisk (not Asterix)

(see matlab Help for more informations)

Page 46: Matlab Introduction

   

Plot 2D and 3D

plot(x,y,':*g'); grid

Page 47: Matlab Introduction

   

Plot 2D and 3D

Syntax to plot more functions in the same graph:

plot(x1,y1,'r*', x2,y2,'b-',........,xn,yn,'y');

Exercize: plot in the same graph the functions y=3*sin(pi*x) and y=exp(-0.5*x) with x in [0,5]. Complete the graph with title, axes labels and grid.

clear all;

x=0:0.1:5;

y=3*sin(pi*x);

plot(x,y,'r'), xlable('x'), ylabel('y');grid

hold on

y1=exp(-0.5*x);

plot(x,y1,'g');

gtext('x1'); gtext('x2');gtext('x3'); gtext('x4');gtext('x5');gtext('x6'); Mouse placement of text in 2-D view

title('intersection graph functions y=3*sin(pi*x) and y1=exp(-0.5*x) ');

hold off

Page 48: Matlab Introduction

   

Plot 2D and 3D

Page 49: Matlab Introduction

   

Plot 2D and 3D

ezplot(fun) plots the expression fun(x,y) over the default domain -2π < x < 2π , -2π < y < 2π where fun(x,y) is an implicit function.

Example:

clear all

clc

figure(1)

ezplot('x.^2-y.^4-1',[-4 4 -4 4]); grid

figure(2)

ezplot('cos(t)','sin(t)'); grid

Page 50: Matlab Introduction

   

Plot 2D and 3D

Page 51: Matlab Introduction

   

Plot 2D and 3D

Page 52: Matlab Introduction

   

Plot 2D and 3D

subplot(m,n,p) divides the current figure into rectangular panes that are numbered rowwise. Where m number of rows ,n number of columns ,p position inside the matrix.

Example: plot in the same figure but in different panes the functions:

y=x, y=x^2, y=sin(x), y=exp(x), y=log(x) and y=cos(x).

x=0.1:0.1:2;

subplot(2,3,1) , plot(x,x,'r');grid

title('y=x');xlabel('x'); ylabel('y');

subplot(2,3,2), plot(x, x.^2,'b');grid

title('y=x^2');xlabel('x'); ylabel('y');

subplot(2,3,3), plot(x,sin(x),'y');grid

title('y=sin(x)');xlabel('x'); ylabel('y');

subplot(2,3,4), plot(x,exp(x),'m');grid

title('y=exp(x)');xlabel('x'); ylabel('y');

subplot(2,3,5), plot(x,log(x),'g');grid

title('y=log(x)');xlabel('x'); ylabel('y');

subplot(2,3,6), plot(x,cos(x),'c');grid

title('y=cos(x)');xlabel('x'); ylabel('y');

Page 53: Matlab Introduction

   

Plot 2D and 3D

Page 54: Matlab Introduction

   

Plot 2D and 3D

To draw 3D graphs we can use the command 'surf' as follow:

→ figure(1); → x=-1:0.1:1; → y=x; → [X Y]=meshgrid(x,y); → Z=sin(X.^2+Y.^2); → surf(x,y,Z); grid → title(' Funzione Z=sin(X^2+Y^2)'); → xlabel(); → ylabel(); → colorbar;

In particular, the command 'meshgrid' calculates all the possible combinations for the values of the arrays x and y to evaluate the function Z. The command 'surf' deaws the graph for function Z giving different colors to the chart depending on the value of the function.

Page 55: Matlab Introduction

   

Plot 2D and 3D

Page 56: Matlab Introduction

   

Plot 2D and 3D

Exercize 1: plot the function

y=exp(x)*sin(x) x=-1:0.1:1

blu line, ':' and marker 'o' title axes and general title;

Exercize 2: plot the function

Z=(X^2+Y^2)*exp(X)

x=y=-1:0.1:1

with colorbar, asex labels and title

Page 57: Matlab Introduction

   

Functions and Scripts

In Matlab we can write functions and scripts. SCRIPT : To make a script we can use any editor and we have to save the file with an extension of type '.m'. However, there is on Matlab an editor that can be activated by clicking the 'EDITOR' (notepad with pencil at the top left). To run a script you would type the following statement: → file_name.m ;

A script can also be performed using ' Run under Debug menu ' on Matlab Editor.

Page 58: Matlab Introduction

   

Functions and Scripts

Page 59: Matlab Introduction

   

Functions and Scripts

FUNCTION: To create a function in Matlab, we can use a procedure similar to that used in the script. The function must also follow the following structure: function[out1,........,outn]=function_name(input 1,.....,input n)

statement 1; ............... ; statement n;

endfunction

Page 60: Matlab Introduction

   

Exercize Script

Exercize: write a script in Matlab to plot the graph of the function z=y+exp(x) wher x = y are in the interval [-2, 2].

Complete the graph with title, axes labels and grid.

Page 61: Matlab Introduction

   

Exercize Script

After opening the matlab editor will insert the following instructions:

clear all;

clc;

x=-2:0.1:2;

y=x;

[X Y]=meshgrid(x,y);

Z=X+exp(Y);

figure(1)

surf(X,Y,Z); xgrid

title(' Z=X+exp(Y)');

xlabel('x');

ylabel('y');

Select “File”after “Save as” and insert “graf3.m” and “Save”.

Page 62: Matlab Introduction

   

Exercize Script

Page 63: Matlab Introduction

   

Exercize Script

Select Debug → Run from Matlab editor and wait results.

Page 64: Matlab Introduction

   

Exercize Script

Exercise: Write a Matlab script to calculate:

1) roots for the function y=x^2+3x-2.

2) plot the graph of the function y=x^2+3x-2 taking care to be able to view the points of intersection with the x-axis.

Complete the graph with title, axes labels and grid.

Page 65: Matlab Introduction

   

Exercize Script

clear all;

clc;

coef=[1,3,-2];

roots(coef)

x=-5:0.1:5;

y=x^2+3*x-2;

figure(1);

plot(x,y,'r');grid

title('Function y=x^2+3*x-2');

xlabel('x');

ylabel('y');

Page 66: Matlab Introduction

   

Esempi script Roots x1= 0,5615528 x2= -3,5615528

Page 67: Matlab Introduction

   

Exercize Function

Exercise: Write a Matlab function able to calcuate the sum of the elements of an array and save it as sum_d.m. Then write a script test_sum.m able to evaluate the correct operation of the function sum_d.m and do the sum of the array elements for:

x=[1,3, 4,8, 2]

Page 68: Matlab Introduction

   

Eexrcize Function file sum.m

function [total]=sum_d(x)

[n]=size(x);

total=0;

for i=1:n(2)

total=total+x(i);

end

end

Page 69: Matlab Introduction

   

Exercize Function file sum_test.m

clear all;

clc;

x=[1,3,4,8,2];

total=sum_d(x)

And the result will be:

>>total=18

When you use the functions pay attention to the current folder !!!