Você está na página 1de 61

A introduction to MATLAB

Computational Mechanics

Civil Engineering master course


School of Engineering and Architecture
University of Bologna

A introduction to MATLAB 1 / 61
Outline I

1 Introduction
Key Features
Desktop Basics
2 Language Fundamentals
Matrices and Arrays
Expressions
Entering Commands
Indexing
Types of Arrays
3 Mathematics
Linear Algebra
Data Analysis
4 Graphics
Basic Plotting Functions
Mesh and Surface plots
A introduction to MATLAB 2 / 61
Outline II
5 Programming
Control Flow
Scripts and Functions

A introduction to MATLAB 3 / 61
Introduction Key Features

MATLAB Product description

The "MATrix LABoratory" software was created at the end of 70’s by


Cleve Moler, the director of the Department of Computer Science of
the New Mexico University. Since 1984 Mathworks distributes, sup-
ports and develops the software. Nowadays MATLAB counts millions
of user world wide from both academy and industry.

A introduction to MATLAB 4 / 61
Introduction Key Features

Key Features

High-level scripting language for numerical computation and


visualization.
Interactive environment for iterative exploration, design and
problem solving.
Mathematical functions for linear algebra, statistics, Fourier
analysis, optimization, numerical integration and ordinary
differential equations.
Built-in graphics for visualizing data and tools for creating custom
plots.
Tools for buildins applications with a custom user interface.
Functions for integrating MATLAB with external languages as C
and Java.

A introduction to MATLAB 5 / 61
Introduction Desktop Basics

Default Layout

Current Folder:
Access your files.
Command Window:
Enter commands (»).
Workspace: Explore
data (variables, arrays,
matrices, strings, ecc. )
Command History:
View or rerun
commands entered in
the command line.

A introduction to MATLAB 6 / 61
Introduction Desktop Basics

Ice Breaking: some dummy commands

a=1
b=2
c =a+b
d = sin(a)
e = c ∗ b;

Digit clear all to cancel all the workspace


Digit clc to clear the command window.
A introduction to MATLAB 7 / 61
Introduction Desktop Basics

Ice Breaking: file types

.m Files .mat Files .p Files

.m Files: files containing scripts and functions.


.mat Files: files containing variables of a workspace.
.p Files: protected files containing not editable code.

A introduction to MATLAB 8 / 61
Language Fundamentals

In this section...

Main Topics
Matrices and Arrays
Expressions
Entering Commands
Indexing
Types of Arrays

A introduction to MATLAB 9 / 61
Language Fundamentals Matrices and Arrays

Entering Matrices

In the MATLAB environment a matrix is a rectangular array of num-


bers. It is possible to enter a matrix in different ways:
Enter an explicit list of elements.
Load matrices from external data files.
Generate matrices from built-in functions.
Create matrices with your own functions.

A introduction to MATLAB 10 / 61
Language Fundamentals Matrices and Arrays

Enter an explicit list of elements

Once the user enters the


matrix, it is saved in the
workspace, so it is possi-
ble to refer it simply as "A".

A introduction to MATLAB 11 / 61
Language Fundamentals Matrices and Arrays

Sum, Transpose and Diag

sum(A) returns a row array


whose elements are the
sum of each column of the
matrix A.
sum(A,2) returns a row
array whose elements are
the sum of each row of the
matrix A.
A’ returns the transpose of
the matrix A.
diag returns a column array
whose elements are in the
diagonal of A.

A introduction to MATLAB 12 / 61
Language Fundamentals Matrices and Arrays

Generate Matrices

zeros(n,m) returns a nxm


matrix zero-filled.
ones(n,m) returns a nxm
matrix one-filled.
eye(n) returns the nxn
identity matrix.
randn(n,m) returns a nxn
matrix of random numbers
normally distributed.

A introduction to MATLAB 13 / 61
Language Fundamentals Expressions

Variables

MATLAB does not require


any type of declaration or
dimension statement. When
it encounters a variable
name, it automatically
creates the variable and
allocates the appropriate
amount of memory.
MATLAB is case sensitive.

A introduction to MATLAB 14 / 61
Language Fundamentals Expressions

Numbers

MATLAB uses conventional decimal notation. Scientific notation uses


th letter e to specify a power of ten factor. Imaginary numbers use
both i or j letter.
Numbers notation

MATLAB stores all numbers internally using the long format (15 sig-
nificant digits) and it is able to represent number from about 10−308 to
10+308 .
Numbers precision

A introduction to MATLAB 15 / 61
Language Fundamentals Expressions

Matrix & Arrays Operators

Matrices Arrays

A introduction to MATLAB 16 / 61
Language Fundamentals Expressions

Building tables

A introduction to MATLAB 17 / 61
Language Fundamentals Expressions

Built-in Functions

Functions Constants

Special Values

A introduction to MATLAB 18 / 61
Language Fundamentals Entering Commands

The Format Function

The format function controls how the number are displayed, not how
they are computed.

A introduction to MATLAB 19 / 61
Language Fundamentals Entering Commands

Suppressing Output & Long Statements

Long Statements

Suppressing Output

A introduction to MATLAB 20 / 61
Language Fundamentals Indexing

Indices

The element in row i and column j of a matrix A is denoted by A(i, j).

A introduction to MATLAB 21 / 61
Language Fundamentals Indexing

The Colon Operator

The colon operator is widely used in MATLAB scripts.

start : step : end syntax Matrix slicing

A introduction to MATLAB 22 / 61
Language Fundamentals Indexing

Concatenation

The concatenation is the process of joining small matrices to make bigger ones.

A introduction to MATLAB 23 / 61
Language Fundamentals Indexing

Deleting Rows and Columns

Delete Columns Delete Rows

A introduction to MATLAB 24 / 61
Language Fundamentals Indexing

Scalar Expansion

Matrices and scalars can be combined in several ways. A scalar can be added to or
subtracted from a matrix, or assigned to a portion of it.

A introduction to MATLAB 25 / 61
Language Fundamentals Indexing

The Find Function

A introduction to MATLAB 26 / 61
Language Fundamentals Types of Arrays

Multidimensional Arrays

MATLAB allows to work with n-dimensional arrays.

In the case of a 3D array, the generic element of the matrix A is denoted by A(i, j, k ).

A introduction to MATLAB 27 / 61
Language Fundamentals Types of Arrays

Charaters and Text

MATLAB manages string as arrays of characters (’char’). A string is identified with


apices

s is a matrix 1x5 of
char .
’s’ is handled as
arrays of numbers.
It is possible to
concatenate strings
both horizontally or
vertically.
It is possible to
manipulate
multi-lines text

A introduction to MATLAB 28 / 61
Language Fundamentals Types of Arrays

Structures

Structures in MATLAB are multidimensional arrays with elements accessed by a tex-


tual field designator.

A introduction to MATLAB 29 / 61
Mathematics

In this section...

Main Topics
Linear Algebra
Data Analysis

A introduction to MATLAB 30 / 61
Mathematics Linear Algebra

A review of Matrices Products

MATLAB uses a sign ’*’ to


denote matrix multiplication.
If the multiplication can not
be done, MATLAB returns
an error ’Matrix dimensions
must agree’.

A introduction to MATLAB 31 / 61
Mathematics Linear Algebra

Inverses and Determinants

det(A) returns the


determinant of the square
matrix A.
If A is nonsingular, inv(A)
returns the inverse of the
square matrix A.

A introduction to MATLAB 32 / 61
Mathematics Linear Algebra

Cholesky Factorization

Matrix A has to be
symmetric and
positive definite.
AX = B Matrix R is upper
triangular.
The backslash
A = R0R
operator recognizes
triangular matrices,
therefore the
X = R(R 0 B)
system solution can
be easily obtained.

A introduction to MATLAB 33 / 61
Mathematics Linear Algebra

LU Factorization

AX = B A is a generic square
matrix.
P is a permutation
PA = LU matrix.
L is a lower triangular
matrix with ones on its
A = P −1 LU diagonal.
U is an upper triangular
matrix.
X = U(P −1 LB)

A introduction to MATLAB 34 / 61
Mathematics Linear Algebra

Systems of Linear Equations

Computational Cosiderations
Although it is not standard mathematical notation, MATLAB uses the
division terminology familiar in the scalar case to describe the solution
of a general system of equations.

Denotes the solution of the


X = B/A system XA = B

Denotes the solution of the


X = AB system AX = B

A introduction to MATLAB 35 / 61
Mathematics Linear Algebra

Systems of Linear Equations

The backslash in MATLAB is a "clever" operator that performs a check


on the matrix and solve the system by using the most suitable algo-
rithm.

Square Matrices
If A is symmetric and has real, positive diagonal element,
MATLAB performs a Cholesky factorization.
If A is upper Hessemberg, MATLAB uses Gaussian elimination.
In general, MATLAB uses the LU factorization algorithm.

A introduction to MATLAB 36 / 61
Mathematics Linear Algebra

Eigenvalues and Eigenvectors

A is a square
matrix.

Av = λv V is the matrix
whose columns are
the eigenvectors.
A = V ΛV −1 Λ is the matrix
containing
eigenvalues on its
diagonal.

A introduction to MATLAB 37 / 61
Graphics

In this section...

Main Topics
Basic Plotting Functions
Mesh and Surface Plots

A introduction to MATLAB 38 / 61
Graphics Basic Plotting Functions

A simple plot

It is possible to save
figures and to plot them.
Commands below the
menu bar allow the user to
zoom and pan the view.

A introduction to MATLAB 39 / 61
Graphics Basic Plotting Functions

Multiple plots

A introduction to MATLAB 40 / 61
Graphics Basic Plotting Functions

Line Styles and Markers

MATLAB allows the user to specify the line style and the marker shape.

A introduction to MATLAB 41 / 61
Graphics Basic Plotting Functions

Adding Plots to an Existing Graph

The hold command enables the user to add plots on the active figure.

A introduction to MATLAB 42 / 61
Graphics Basic Plotting Functions

Figures

Graphic functions (like plot) automatically create a new figure. If different figures are
open, MATLAB plots on the last one (i.e. the active figure).

Open and Reset Figures


To make the desired figure active, just type:

figure(n)

where ’n’ is the number of the figure to make active.


To clear a figure and restore defaults properties, make it active and type:

clf reset

A introduction to MATLAB 43 / 61
Graphics Basic Plotting Functions

Subplotting

The subplot command enables


the user to display multiple plots
in the same window (figure).
The plots are numbered along
rows.

A introduction to MATLAB 44 / 61
Graphics Basic Plotting Functions

Setting Axes Limits and their Aspect Ratio

Limits
The axis command allow the user to specify custom plotting limits.

axis([xmin xmax ymin ymax])

To restore automatic axes dimensions, digit:

axis auto

Aspect Ratio
The command:

axis square

makes x and y axis of the same length, while:

axis equal

makes the increments of the same length.


A introduction to MATLAB 45 / 61
Graphics Basic Plotting Functions

Setting Axes Visibility and the Grid

Axes Visibility
The command

axis off

makes axes invisible. To turn they


on, digit axis on.

Grid
The command:

grid on

turns on the grid. To turn it off,


digit grid off.

A introduction to MATLAB 46 / 61
Graphics Mesh and Surface plots

Mesh and Surface Plots

Mesh Command
The mesh command produces a wireframe that color only the lines
connecting the points.

Surf Command
The surf command displays both connecting lines and faces of the
surface in color.

A introduction to MATLAB 47 / 61
Graphics Mesh and Surface plots

Visualizing Functions of 2 Variables

A introduction to MATLAB 48 / 61
Graphics Mesh and Surface plots

Meshgrid

A introduction to MATLAB 49 / 61
Graphics Mesh and Surface plots

Transparent Surfaces

A introduction to MATLAB 50 / 61
Graphics Mesh and Surface plots

Illuminating Surface Plots with Lights

A introduction to MATLAB 51 / 61
Programming Control Flow

The editor

The text editor of MATLAB is the tool used for coding. To open it, digit edit in the com-
mand window. Differently from the command window, the editor environment is not
interactive. Therefore the user can write some lines of code and then execute them by
clicking the run button.

A introduction to MATLAB 52 / 61
Programming Control Flow

Conditional Controls: if - else

The conditional statements work also with arrays and matrices.


A introduction to MATLAB 53 / 61
Programming Control Flow

Conditional Controls: switch

A introduction to MATLAB 54 / 61
Programming Control Flow

Loop Controls: for

A introduction to MATLAB 55 / 61
Programming Control Flow

Loop Controls: while

The simple script below find a root of the equation x 3 − 2x − 5 with the bisection
method.

A introduction to MATLAB 56 / 61
Programming Control Flow

Loop Controls: continue, while, return

Continue
The continue statement passes control to the next iteration inside a
for or a while loop, skipping everything appears in the lines below it.

Break
The break statement exit from the loop. In nested loops, it exit form
the inner loop only.

Return
The return statement terminates the sequence of commands.
Everything after is not executed.

A introduction to MATLAB 57 / 61
Programming Scripts and Functions

Scripts and Functions

Scripts
Scripts program do not accept input arguments and do not return
anything. They operate in data present in the workspace.

Functions
Functions accept input arguments and return output arguments.
Internal variables are local, therefore they are not stored in the
workspace.

A introduction to MATLAB 58 / 61
Programming Scripts and Functions

Functions

The simple function below write a ’.txt’ file containing values from a matrix.

A introduction to MATLAB 59 / 61
Programming Scripts and Functions

Functions

Once the function is saved in the working directory with its name in a ’.m’ file, it is
callable from another functions/scripts or from the command window.

A introduction to MATLAB 60 / 61
Programming Scripts and Functions

Functions

When using functions, the user has to pay attention to the


arguments order and their type.
It is worth to notice that the variables employed only internally are
not stored in the workspace.

A introduction to MATLAB 61 / 61

Você também pode gostar