You are on page 1of 128

Introduction to

MATLAB
Fiorella Sgallari
University of Bologna, Italy
School of Engineering and Architecture
Department of Mathematics - CIRAM

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

Tutorials
MATHWORKS web site:
http://it.mathworks.com/

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

Overview
Introduction and Overview
Matrix manipulations and common functions
M Files: Script-Function
Programming
Plots in MATLAB
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

History
 The name is derived from MATrix LABoratory
 MATLAB was originally written by Dr. Cleve Moler, Chief Scientistat of
the Computer Science Dep. at the University of New Mexico, to provide
easy access to matrix software developed in the LINPACK and EISPACK
projects. The very first version was written in the late 1970s for use in
courses in matrix theory, linear algebra, and numerical analysis. MATLAB
is therefore fundamentally built upon a foundation of sophisticated matrix
software, in which the basic data element is a matrix that does not require
predimensioning.
 It soon spread to other universities and found a strong audience within the
applied mathematics community. Jack Little, an engineer, was exposed to it
during a visit Moler made to Stanford University in 1983. Recognizing its
commercial potential, he joined with Moler and Steve Bangert. They rewrote
MATLAB in C and founded The MathWorks in 1984 to continue its
development. These rewritten libraries were known as JACKPAC. In 2000,
MATLAB was rewritten to use a newer set of libraries for matrix
manipulation, LAPACK.
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

Foundation of Matlab
MATLAB is a case sensitive language (a variable named c is
different than another one called C)
MATLAB is an interactive system whose basic data element is
an array that does not require dimensioning. Even scalars are
treated as 1x1 matrices.
 MATLAB has a number of competitors.
 There are free open source alternatives to MATLAB, in
particular GNU Octave, FreeMat, and Scilab which are
intended to be mostly compatible with the MATLAB language
(but not the MATLAB desktop environment).
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

Matlab allows to solve many technical computing problems, examples of which


include:





Matrix manipulation
Finding the roots of polynomials
Digital signal processing applications
Plotting: x-y and polar, 3D graphics

Particularly helpful for:








Algorithm development,
Modeling, simulation, and prototyping,
Data acquisition
Data analysis, exploration, and visualization,
Application development, including graphical user interface building.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

MATLAB is an interpreted language, errors are easier to fix


but it is very slow. (An interpreted language is a programming
language whose programs are translated to machine code at the
time of execution).

An interpreted language is a programming language for which


most of its implementations execute instructions directly, without
previously compiling a program into machine-language
instructions. The interpreter executes the program directly,
translating each statement into a sequence of one or more
subroutines already compiled into machine code.
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

MATLAB is an interpreted language, errors are easier to fix


but it is very slow. (An interpreted language is a programming
language whose programs are translated to machine code at the
time of execution).
 2-D and 3-D graphics functions for
visualizing data.
 Tools for building custom graphical
user interfaces.
 Functions for integrating MATLAB
based algorithms with external
applications and languages, such as
C, C++, Fortran, Java, COM, and
Microsoft Excel.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

MATLAB Toolbox: some


Mapping Toolbox provides a comprehensive set of functions and graphical user interfaces for
performing interactive geographic computations, data fusion, map projection display, generation
of presentation graphics, and accessing external geographic data. In addition, the toolbox ships
with several, widely used atlas data sets for global and regional displays.

MATLAB Compiler serves for two primary user groups: - Developers looking to deploy
MATLAB applications to standalone C/C++ applications and - users who want to compile their
MATLAB algorithms to improve code performance by converting them to C. The MATLAB
Compiler automatically converts M-files into C and C++ source code.

Partial Differential Equation (PDE) Toolbox contains tools for the study and solution of
PDEs in two space dimensions (2-D) and time, using the finite element method (FEM). Its
command line functions and graphical user interface can be used for mathematical modeling of
PDEs in a broad range of engineering and science applications, including structural mechanics,
electromagnetics, heat transfer, and diffusion.

Symbolic/Extended Math Toolbox integrates symbolic mathematics and variable precision


computation into MATLAB. The toolbox incorporates the computational kernel of Maple V
release 5, developed by Waterloo Maple Software. Extended Symbolic Math adds support for full
Maple programming and Maple's specialized libraries.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

Starting and Quitting MATLAB


Starting MATLAB
On Windows platforms, to start MATLAB,
double-click the MATLAB shortcut icon on your
Windows desktop.
Quitting MATLAB
To end your MATLAB session, select Exit
MATLAB from the File menu in the desktop, or
type quit in the Command Window.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

10

The Matlab Environment

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

11

The Matlab Environment

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

12

The Matlab Environment

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

13

The Matlab Environment

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

14

The Matlab Environment


Use the Set Path dialog box to view and modify the MATLAB search path.
Equivalent functions are documented for each feature of the Set Path dialog box.
Select Set Path from the File menu, or type pathtool at the Command Window
prompt. The Set Path dialog box opens.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

15

The Matlab Environment


Use the Set Path dialog box to view and modify the MATLAB search path.
Equivalent functions are documented for each feature of the Set Path dialog box.
Select Set Path from the File menu, or type pathtool at the Command Window
prompt. The Set Path dialog box opens.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

16

MATLAB has the following basic window components:

 Work-space
Displays all the defined variables.

 Command Window
To execute commands in the MATLAB environment

 Command History
Displays record of the commands used

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

17

Matlab Workspace
Workspace of Matlab
shows all the defined
variables along with
their order, memory
space they occupy and
the class to which they
belong
Here are shown a few
such variables

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

18

Command Window

Command window

>> 39*4.4+5
ans =
176.6000
Command window

The MATLAB command

The result.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

19

Command Window
The command window allows you to interact with
MATLAB just as if you type things in a calculator
Cut and paste operations ease the repetition of tasks
Use up-arrow key

to repeat commands

(command history)

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

20

Command History
Statements you enter in the Command Window are logged in the
Command History. From the Command History, you can view and
search for previously run statements, as well as copy and execute
selected statements. You can also create an M-file from selected
statements.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

21

Current Directory
Provides quick access to all
files available in your Path
Provides a brief description
(when files are commented
out) of each M-file

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

22

Different Views

The Matlab environment could be


viewed in various ways.
This could be accomplished by the
VIEW pull-down menu as shown
in the previous slide.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

23

Matlab Help
Matlab Help is an extremely powerful assistance to learn Matlab.
The Help not only contains the theoretical background but also
shows the demos for implementation
The Matlab Help could be opened by using the HELP pull-down
menu

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

24

Matlab Help

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

25

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

26

Matlab Programming
Two Approaches
Coding in Command Window
Good for short programs
Commands must be re-entered each time you run a
simulation

Coding with .m-files: script


Good for long programs
Allows users to save all the commands written in
the .m-files

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

27

Command Window Interface

Write your
commands here

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

28

(1) Creating .m-files


File  New  M-File
(2) Opening .m-files
File  Open  select
the .m-file

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

29

(1) Creating .m-files


File  New  M-File
(2) Opening .m-files
File  Open  select
the .m-file

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

30

.m-file Interface

Write your
commands here

To run the program, digit the name of script


or choose run in menu Debug
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

31

Editor

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

32

Basics: Basic Operations


Symbol
^
*
/
\
+
-

Operation

MATLAB

exponentiation: ab

a^b

multiplication: ab

a*b

right division: a/b =

a
b

a/b

left division: a\b = ba

a\b

addition: a + b

a+b

subtraction: a-b

a-b

1/4=4\1=0.25
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

33

Relational operators -Logical operations

>

Greater than

>=

Greater than or equal

<

Less than

<=

Less than or equal

==

equal

~=

Not equal

(for ~ in an italian keyboard press ALT and digit 126 on the numeric keyboard)
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

34

Relational operators -Logical operations

&

AND

OR

NOT

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

35

Type

Data type

Memory

Double

Real numbers
in [10-37,1037]

8 byte

Complex
double

Complex numbers

16 byte

Logical
double

Result of a
logical operation
(1=true, 0=false)

1 byte

Char

Character

2 byte

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

36

Examples
a = sqrt(3);

Double

c = -2+i*8.2

Complex double

t = a<1

Logical double

q = 'k'

Char

'

var_txt = This string is assigned to the variable


Char array

var_txt'
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

37

Basics: Variables
Variable is a symbol used to contain a value
MATLAB has some rules to name variables
Variables names are case sensitive
BOB, Bob, bob, BoB  all different!
Variables names can contain up to 31 characters. Any
additional characters are ignored
Variable names must start with a letter, followed by any
number of letters, digits or underscores (no blank).
Punctuation characters are not allowed, because most of them
have a special meaning in MATLAB
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

38

Basics: Variables


Some names cannot be used for variables: for, end, if,


while, function, return, elseif, case, otherwise, switch,
continue, else, global, break ..

If you try to use any of these reserved words as a


variable, MATLAB will report an error

Of course, you can use words similar by capitalizing one


or more letters

Also, MATLAB has a number of special variables and


constants

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

39

Basics: Special Variables and Constants


Name

Description

ans

Default variable name used for results

eps

specifies accuracy of f.p. precision

i,j

imaginary unit, sqrt(-1)

Inf

infinity

NaN

undefined numerical result

pi

realmax

largest real f.p. # on THIS computer

realmin

smallest real f.p. # on THIS computer

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

40

Basic Syntax
Assignment of Variables
Syntax: Variable = Expression
Example: A = 1;

Use of semi-colons
With semi-colon suppress output
Without semi-colon displays output in command
window

Adding comments
Add %

before command line

Example: % This is a demo


Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

41

Row vector
The square braces are
used to define a matrix

X=[2,3 7 ]
X=
2 3

Numerical Methods

Space or comma are used


to separate elements in the
same row

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

42
42

Column vector
The square braces are
used to define a matrix

X=[2;3 ; 7 ]

semicolon are used to end a


row.

X=
2
3
7

You can also use ENTER to end


a row

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

43
43

MATLAB Statements
MATLAB Statement

Remarks

C=5.66

C is a scalar

C=[5.66]

An alternative way

X=[3.5 6.3, 33]

X is a 1X3 matrix with elements 3.5 , 6.3


and 33. Commas or space are used to
separate the elements in a row

Y=[1
4]

Y is a 2X1 matrix whose elements are 1


and 4.

Y = [ 1 ; 4]

Semicolon are used to indicate the end of


the row.

A=1:5

Equivalent to A=[1 2 3 4 5]

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

44
44

MATLAB Statements
MATLAB
Statement
V=[ 2 3 5
3 3 8]
C=[1:3:11]
Z=4\8
Y=eye(2)
W = zeros(2,3)

Numerical Methods

Remarks
2 3 5
V =

3 3 8
C=[1 4 7

10]

Z=2

1 0
V =

0 1

0 0 0
V =

0 0 0

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

45

45

Generating Vectors and the Colon Operator


( Helpful for generating time vectors. )
>> x = [ 0 : 0.2 : 1 ]
x=
0 0.20 0.40 0.60

% 0 to 1 in increments of 0.2
0.80 1.00

>> x = linspace(0, 1, 6)
% 6 points from 0 to 1 on a linear scale
x=
0 0.20 0.40 0.60 0.80 1.00
% 6 points from 100 to 101 on a log scale
>> x = logspace(0,1,6)
x=
1.0000 1.5849
2.5119
3.9811 6.3096 10.0000

Numerical Methods

46

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

46

Generating Matrices
>> B = [ 1 2 ; 8 9 ]
ans =
1 2
8 9
>> ones(2,2)
ans =
1 1
1 1

% generates an all ones 2 x 2 matrix

>> zeros(2,3)
ans =
0 0 0
0 0 0

% generates an all zero 2 x 3 matrix

>> rand(3,3)
% generates a random 3 x 3 matrix
ans =
0.4447 0.9218 0.4057
0.6154 0.7382 0.9355
0.7919 0.1763 0.9169
>> eye(2)
ans =
1 0
0 1
Numerical Methods

% generates the 2 x 2 identity matrix

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

47

Accessing Matrix Elements


A=

>> A= [ 1 2 3 ; 4 5 6 ; 7 8 9];
>> x = A ( 1, 3 )
x=
3
>> y = A ( 2 , : )
y=
4 5 6

%A(<row>,<column>)

% selects the 2nd row

>> z = A ( 1:2 , 1:3 ) % selects sub-matrix


z=
1 2 3
How do I select the last
4 5 6

column?

Numerical Methods

A(:,end)

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

48

Concatenating, Appending,
>> R = [ 1 2 3 ] ;
>> S = [ 10 20 30 ] ;
>> T = [ R S ]
T=
1 2 3 10 20 30
>> Q = [ R ; S ]
Q=
1 2 3
10 20 30
>> Q ( 3, 3 ) = 100
Q=
1 2 3
10 20 30
0 0 100
Numerical Methods

A =[A,[1;2;3]]
A=
2 0 1
0 1 2
3 3 3

if you store a value in an element


outside of the matrix, the size
increases to accommodate the
newcomer.
F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

49

Basic Syntax
Mathematical (Array) Operators
Mathematical

Mathematical Array

+
*
/

Addition

Division

+
.*
./

Power

.^ Power

Subtraction
Multiplication

Addition
Subtraction
Multiplication
Division

Note the dimension of matrix in matrix computation


Example: A: 2x1 matrix, B: 2x2 matrix
A*B  invalid operation
B*A  valid operation
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

50

Term by Term vs Matrix Operations


>> B = [ 1 2 ; 3 4 ] ;
B=
1 2
3 4

1 2

1 2

3 4

3 4

>> C = B * B
C=
7 10
15 22

% or equivalent B^2

>> D = B .* B
D=
1 4
9 16

% or B.^2 The Dot denotes term by term operations

Numerical Methods

What is B / B ? B ./ B ?
F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

51

Some Useful Functions


Some useful math functions:
sin(x), cos(x), tan(x), atan(x), exp(x), log(x), log10(x), sqrt(x)
>> t = [ 0 : 0.01 : 10 ];
>> x = sin ( 2 * pi * t );
Some useful matrix and vector functions:
>> size (A)
ans =
3 3
>> length ( t )
ans =
1001

Numerical Methods

A=
1

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

52

Some Useful Functions


diary
Save session to file
Syntax
diary
diary ('filename')
diary off
diary on
diary filename
Description
The diary function creates a log of keyboard input and the resulting text
output. The output of diary is an ASCII file, suitable for searching in,
printing, inclusion in most reports and other documents. If you do not specify
filename, MATLAB creates a file named diary in the current directory.
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

53

More Operators and Functions


For vectors, sum(x) is the sum of the elements of X. For matrices,
sum(x) is a row vector with the sum over each column.
>> sum ( A )
ans =
12 15 18

A=

>> sum ( ans )


ans =
45

% equivalent to sum(sum(A))

>> A
ans =

% equivalent to transpose(A)
1
2
3

>> diag(A)
ans =
1
5
9

Numerical Methods

4
5
6

5 6

7
8
9

What is sum(A')' ?
F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

54

Complex Number Operations


>> x = 3+4j

MATLAB stores the real and


imaginary parts of a complex
number.

>> abs(x)
x=5

%Absolute value.

>> angle(x)
x = 0.9273

%Phase angle (in radians).

>> conj(x)
x = 3-4j

%Complex conjugate.

>> imag(x)
x=4

%Complex imaginary part.

>> real(x)
x=3

%Complex real part.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

55

Basics: Commands
Command

Description

clc

clears Command window

clear

removes all variables

clear var1 var2

removes listed variables

exist (name)

determines if name (file or var) exists

quit

Stops MATLAB

who

lists current variables

whos

lists current variables with sizes

generates array

separates elements of array

suppresses screen printing, also new line in array

continues a line

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

56

Format output
Output can be visualized in different form:
SHORT

Scaled fixed point format, with 4 digits after the decimal point.

SHORT E

Floating point format, with 4 digits after the decimal point.

SHORT G Best of fixed or floating point, with 4 digits after the decimal point.
LONG

Scaled fixed point format with 14 to 15 digits after the decimal point

LONG E

Floating point format, with 14 to 15 digits after the decimal point

LONG G

Best of fixed or floating point, with 14 to 15 digits after the decimal


point

RAT

Ratio of small integers.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

57

Example: >>y = 8/6


>>format short
1.3333
>>format short e
1.3333E+000
default
>>format short g
1.3333
>>format long
1.33333333333333
>>format long e
1.333333333333333E+000
>>format long g
1.33333333333333
>>format rat
4/3

Numerical Methods

: format short

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

58

Controlling Input and Output




The disp Function: Useful to control the output


disp: Display array.
disp(X) displays the array, without printing the array name.
It's the same as leaving the semicolon off an expression
except that empty arrays don't display. If X is a string, the
text is displayed.

EXAMPLES:
>> disp(X) displays the value of variable X, but not its name
>> disp(The value of X is:) displays the string
The value of X is:
but no number

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

59

Controlling Input and Output




The input Function: Used to get interactive input.


input: Prompt for user input.
R = input('How many apples') gives the user the prompt in the
text string and waits for input from the keyboard.
The input can be any MATLAB expression, which is evaluated,
using the variables in the current workspace, and the result
returned in R. If the user presses the return key without entering
anything, INPUT returns an empty matrix.
R = input('What is your name','s') gives the prompt in the text
string and waits for character string input. The typed input is
not evaluated; the characters are simply returned as a MATLAB
string.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

60

Controlling Input and Output




The Menu Function: Used to get interactive input by


selection of an alternative from a menu.
k = menu(title,option1,option2,)

choices=['B','D','F'];
k=menu('Whodoyouwant?',choices(1),choices(2),choices(3));
disp(['You picked ',choices(k)])

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

61

Loading and Saving Data


When using MATLAB, you may wish to leave the
program but save the vectors and matrices you have
defined. To save the file to the working directory, type
save filename
where "filename" is a name of your choice.
To retrieve the data later, type
load filename
>>load data.txt;
%name of array will be data
>>load(new.txt); %name of array will be new
>>mydata = load(proj3.txt); %name of array will be mydata
Numerical
August 29,
Methods
2016

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

62

Programming in MATLAB
M-files are macros of MATLAB commands that are stored
as ordinary text files with the extension "m", that is
filename.m
There are two types of MATLAB programs
script files

function files

% script file

function [y]=fun(x)

P=[1 3 2]

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

roots(P)

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

63
63

M-files cont.
There are two kinds of M files
Script
It consists a list of commands and statements that will
be executed in order

Function
It defines one or more functions that can be called
In Matlab, a function is similar to a C/Fortran function
There are different kinds of Matlab functions
Anonymous functions, which do not require a .m file but
only a single Matlab expression

Primary and subfunctions


Numerical
August 29,
Methods
2016

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

64

Script versus functions files


Script files
List of MATLAB
statements
Variables are global
Run it by typing the
file name

Numerical Methods

Function files
 Starts with function
 List of MATLAB
statements
 Variables are local

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

65
65

Script files
Use script file when you have a long
sequence of statements to solve a problem
Run the program by
typing its name in the command window
from tools in the editor window

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

66
66

Functions
Primary functions
Primary functions are required to define a
primary function
A number of subfunctions can be defined in the
same file
Primary functions can be invoked from
anywhere while subfunctions can only be
invoked within the corresponding primary
function

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

67

Function
Syntax
function [out1, out2, ...] = funname(in1, in2, ...)

Description
function [out1, out2, ...] = funname(in1, in2, ...)
defines function funname that accepts inputs in1,
in2, etc. and returns outputs out1, out2, etc.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

68

Creating M-files
Select FILE  OPEN  NEW  M-files

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

69
69

MATLAB shortcuts
Create
a New
file

Numerical Methods

Open an existing files

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

70
70

How the source-code looks like

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

71

Example
Write a function file to compute the
factorial of a number.
Input: N
Output :NF
Function name: Myfactorial

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

72
72

A solution
output
First
statement
must start
with
function

Function name

input

function
[FC]=Myfactorial(N)
FC=1;
for i=1:N
FC=FC*i;
end

Save the program using Myfactorial as a name


Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

73
73

Creating function file


Open an m-file and start typing the file

function [FC]=Myfactorial(N)
FC=1;
for i=1:N
FC=FC*i;
end
Save the program using Myfactorial as a name
If NOTEPAD is used to create the file use the name Myfactorial.m
Save it in directory recognized by MATLAB
If the directory is not recognized by MATLAB add it to the MATLAB
path
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

74
74

A Better one

These
comments
will be
displayed
when

help
factorial
is typed

Numerical Methods

function [FC]=Myfactorial(N)
% [FC]=Myfactorial(N)
% program to calculate the factorial of a number
% input N : an integer
% if N is not an integer the program obtains the
% factorial of the integer part of N
% output FC : the factorial of N
%
FC=1;
for i=1:N
FC=FC*i;
end

% initial value of FC
% n! =(n-1)!*n

Comments are used to explain


MATLAB statements
F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

75
75

Script file to compute factorial


% program to calculate the factorial of a number
% input N : an integer
% if N is not an integer the program obtains the
% factorial of the integer part of N
% output FC : the factorial of N
%
FC=1;
% initial value of FC
for i=1:N
FC=FC*i;
% n! =(n-1)!*n
end

Comments are used to explain


MATLAB statements
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

76
76

Function file to compute cos


% program to calculate an estimate of cos(0.2)
% cos(x) 1-x^2/2!+x^4/4!
x=0.2
Sum=1
N=2
[FC2]=Myfactorial(N)
Function functional
Sum=Sum-x^2/FC2
N=4
Function factorial
[FC4]=Myfactorial(N)
Sum=Sum+x^4/FC4

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

77
77

Esempio
function [a,p] = polyGeom(s,n)
% polyGeom Compute area and perimeter of a regular polygon
%
% Synopsis: [a,p] = polyGeom(s,n)
%
% Input: s = length of one side of the polygon
%
n = number of sides of the polygon
%
% Output: a = total area of the polygon
%
p = total perimeter of the polygon
r = s/(2*tan(pi/n)); % "radius" of the polygon
a = area(r,n);
p = perimeter(r,n);
% ============ subfunction "area"

function a = area(r,n)
% area Compute area of an n-sided polygon of radius r
a = n*r^2*sin(pi/n);
% ============ subfunction "perimeter"

function p = perimeter(r,n)
% perimeter Compute perimeter of an n-sided polygon of radius r
p = n*2*r*tan(pi/n);
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

78

Global varialble
If you want more than one function to share a single copy of a
variable, simply declare the variable as global in all the
functions. Do the same thing at the command line if you want
the base workspace to access the variable.
The global declaration must occur before the variable is
actually used in a function.
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Numerical Methods

global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

79

Function name as arguments


function y = humps(x)
y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;
Evaluate this function at a set of points in the interval 0 x 1 with

x = 0:.002:1;
y = humps(x);
Then plot the function with

plot(x,y)
if you search for a zero
z = fzero(@humps,.5)
computes the area under the curve in the graph
Q = quadl(@humps,0,1)
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

80

Function eval
Evaluate function
Syntax
[y1, y2, ...] = feval(fhandle, x1, ..., xn)
[y1, y2, ...] = feval(function, x1, ..., xn)
Description
[y1, y2, ...] = feval(fhandle, x1, ..., xn) evaluates
the function handle, fhandle, using arguments x1 through xn.

>> feval('sin',0.6*pi)
ans =
0.9511

Numerical Methods

>> sin(0.6*pi)
ans =
0.9511

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

81

Function eval
fhandle = @humps;
x = fminbnd(fhandle, 0.3, 1);
the fminbnd function uses feval to
evaluate the function handle that was
passed in.
function [xf, fval, exitflag, output] = ...
fminbnd(funfcn, ax, bx, options, varargin)
.
.
.
fx = feval(funfcn, x, varargin{:});
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

82

Example
function s = fsum(fun,a,b,n)
%
%
%
%
%
%
%
%
%

fsum

Computes sum of f(x) values at n points in

Synopsis:
Input:

Output:

s = fsum(fun,a,b,n)

fun = (string) name of the function, f(x), to be evaluated


a,b = endpoints of the interval
n
= number of points in the interval
s = sum of f(x) at n discrete points in the interval

x = linspace(a,b,n);
y = feval(fun,x);
s = sum(y);

Numerical Methods

a <= x <= b

%
%
%

create points in the interval


evaluate function at sample points
compute the sum

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

83

Example
>> s=fsum('sin',0,pi,15)
s =
8.8752

>> s=fsum('cos',0,pi,15)
s =
6.6613e-016

>> s=fsum('sincos',0,pi,15)
s =
5.7142e-016

function y=sincos(x)
y=sin(x).*cos(x);

function s = fsum1(fun,a,b,n,p1)
x = linspace(a,b,n);
y = feval(fun,x,p1);
s = sum(y);

f ( x ) = 1 k 2 sin 2 ( x )

>>s=fsum1('elf',0,pi,15,0.9)
s =
11.4430
Numerical Methods

function y=elf(x,k)
y=sqrt(1-k.^2.*sin(x).^2);

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

84

If structures
The if statement evaluates a logical expression and executes a group of statements
when the expression is true. The optional elseif and else keywords provide for the
execution of alternate groups of statements. An end keyword, which matches the if,
terminates the last group of statements.

General form:
If (x>0)

If condition
statements
else
statements
end

sign=1
elseif (x==0)
sign=0
else
sign=-1
end

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

85
85

Example
if A > B
'greater
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end

Numerical
NumericalMethods
Methods

if condition
statements
end

F.F.Sgallari
SgallariDept.
Dept.
Mathematics-CIRAM,
Mathematics-CIRAM,
University
University
of Bologna
of Bologna

86

Switch and case


The switch statement executes groups of statements based on the value of
a variable or expression. The keywords case and otherwise delineate the
groups. Only the first matching case is executed. There must always be an
end to match the switch.

General form:
switch switch_expr
case case_expr
statement, ..., statement
case {case_expr1, case_expr2, .}
statement, ..., statement
otherwise
statement, ..., statement
end
Numerical Methods

switch (rem(n,4)==0) + (rem(n,2)==0)


case 0
M = odd_magic(n)
case 1
M = single_even_magic(n)
case 2
M = double_even_magic(n)
otherwise
error('This is impossible')
end

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

87
87

for loops
The for loop repeats a group of statements a fixed, predetermined
number of times. A matching end delineates the statements.

General form:

s=0
for i=1:3:11

for index=initial: increment: limit


statements
end

Numerical Methods

s=s+i
end

Al-Amer
F. Sgallari
2006Dept. Mathematics-CIRAM, University of Bologna

88
88

Example
MATLAB program to find the roots of
f ( x ) = 2 cos( x ) 1

Result
% program 1 performs four iterations of
% Newtons Method
X=.7
for i=1:4
X=X (2*cos(X)-1)/(-2*sin(X))

X=
1.1111
X=
1.0483
X=
1.0472
X=
1.0472

end

Numerical Methods

Al-Amer
F. Sgallari
2006Dept. Mathematics-CIRAM, University of Bologna

89
89

x=rand(10,1);
s=0;
for ii=1:length(x)
s=s+x(ii);
end

x=rand(10,1);
s=0;
for ii=length(x):-1:1
s=s+x(ii);
end

s=0;
for x=0:pi/15:pi
s=s+sin(x);
end

for ii=1:m
for jj=1:n
A(ii,jj)=1/(ii+jj);
end
end

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

90

While end
The while loop repeats a group of statements an indefinite
number of times under control of a logical condition. A
matching end delineates the statements.

General form

while condition
statements
end
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

91

Example
Determine the first integer fot which n! ( factorial) is a number
with 100 digits.
.
n=1;
while (prod(1:n) < 1.e10)
n=n+1;
end
disp(n )

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

92

Plotting in MATLAB
MATLAB graphs display in a special window known as a figure.
To create a graph, you need to define a coordinate system.
Therefore, every graph is placed within axes, which are contained
by the figure.

Command

Description

plot(x,y)
title(text)

Generates plot.

xlabel(text)
ylabel(text)

Adds label to horizontal axis.

legend(text)

Places a legend

figure n
hold on

Opens a new figure window numbered n

Numerical Methods

Puts title on plot.

Adds label to vertical axis.

Holds on the current graph


F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

93

Line Specif.
Solid line (default)
Dashed line
Dotted line
Dash-dot line

Colour

Marker specif.

- blu
-- black

point

plus sign

: green
-. red

g
r

star
Circle

*
o

yellow

Cross

white

Cyan

magenta m
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

94

Example
Generating data

time=[0:0.01:6]
Y=sin(time)

plot(time,Y)
xlabel('time')
ylabel('sin(time) ')
title(' plot of sin(time) ')
grid

Plot Y versus time


x- axis is time, y- axis is Y
Add a label to the x- axis
Add a label to the y- axis
Add a title
Add grid lines

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

95
95

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

96
96

Example
Generating data

time=[0:0.01:6]
Y=sin(time)

Plot Y versus time


x- axis is time
y- axis is Y

plot(time,Y)
You can add
a label to the x- axis
a label to the x- axis
Title
And others on the graph
directly (click insert)
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

97
97

Example
time=[0:0.01:6]
Y=sin(time)

plot(Y)

Numerical Methods

Generating data

Plot Y versus index


x- axis is column #
y- axis is Y

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

98
98

Example
time=[0:0.01:6]
Y=sin(time)

plot(Y)

Numerical Methods

Generating data
Plot Y verses index x- axis is
column # y- axis is Y

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

99
99

Continuous
Time
Plots
The plot function has different forms, depending on the input arguments. If y is
a vector, plot(y) produces a piecewise linear graph of the elements of y versus
the index its elements. If you specify two vectors as arguments, plot(x,y)
produces a graph of y versus x.
Plot of the Sine Function
1

0.5
Sine of x

0.5

-0.5

-0.5

-1

>> x = [ 0 : 0.001 : 2*pi ];


>> y = sin ( x );
>> plot (x,y) ;
Numerical Methods

3
x = 0:2

>> xlabel('x = 0:2\pi')


>> ylabel('Sine of x')
>> title('Plot of the Sine Function','FontSize',12)
>> axis tight % observe the limits of x-axis
100

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

100

Discrete Time Plots Stems


Stem function is very similar to plot. It is used to plot discrete
time sequences. For more info: help stem
Example:
>> k = [ 0 : 30 ] ;
>> x = sin ( k / 5 ) ;
>> stem ( k, x)
>> xlabel('0 \leq k \leq 5');
>> ylabel('x [ k ]');
>> title('x [ k ] = sin ( k / 5 ) for 0 \leq k \leq 5');
x [ k ] = sin ( k / 5 ) for 0 k 5
1

x[k]

0.5
0
-0.5
-1

Numerical Methods

10

15
0k5

20

25

30

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

101

Multiple Data Sets in One Graph


Multiple x-y pair arguments create multiple graphs with a
single call to plot. For example, these statements plot three
related functions of x, each curve in a separate distinguishing
color.

x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
legend('sin(x)','sin(x-.25)','sin(x-.5)')

sin(x)
sin(x-.25)
sin(x-.5)

0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1

The legend command provides an easy


way to identify the individual plots.
Numerical Methods

102

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

102

Hold Command
You can also generate multiple overlapping graphs
using the hold command as follows (for more info:
help hold)
1

Example;
x = 0 : pi/100 : 2*pi;
y = sin(x);
plot(x,y,'b');
hold on;
y2 = sin(x - 0.25);
plot(x,y2, 'r');
y3 = sin(x - 0.5);
plot(x,y3, 'g');
axis tight;
hold off;
Numerical Methods

0.5

-0.5

-1

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

103

Subplot
t=-10:.01:10;
y1=t;
y2=t.^2;
y3=exp(t);
y4=abs(t);
subplot(221)
plot(t,y1),
title(Here is the line')
subplot(222)
plot(t,y2),
title(Here is the parabola')
subplot(223)
plot(t,y3),
title(Here is the exponential')
subplot(224)

The subplot command enables you


to display multiple plots in the
same window or print them on the
same piece of paper.
Typing subplot(m,n,p)
partitions the figure window into
an m-by-n matrix of small
subplots and selects the pth
subplot for the current plot.
The plots are numbered along the
first row of the figure window,
then the second row, and so on.

plot(t,y4),
title(Here is the absolute value')
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

104

Subplot

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

105

Example
subplot(2,2,1)
plot(x,r),
hold on
plot(y,--)

subplot(2,2,2)
plot(x,r),
hold on
plot(y,--)

subplot(2,2,3)
plot(x,r),
hold on
plot(y,--)
Numerical Methods

F. Sgallari

subplot(2,2,4)
plot(x,r),
hold on
plot(y,--)
Dept. Mathematics-CIRAM, University
of Bologna

106

Figure Tools
The
figure
is
equipped with sets of
tools that operate on
graphs.
The figure Tools
menu provides access
to many graph tools,
as this view of the
Options
submenu
illustrates.

Numerical Methods

107

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

107

Figure Tools
Many of the
options shown in
this figure also
appear as context
menu items for
individual tools
such as zoom and
pan.

Numerical Methods

108

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

108

Figure Tools
The figure also shows three figure toolbars

Numerical Methods

109

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

109

Figure Tools
When you place the cursor over a particular tool, a text box pops
up with the tool name. The following picture shows the three
toolbars displayed with the cursor over the Data Cursor tool.

Numerical Methods

110

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

110

Figure Tools

The following
picture shows
a figure with
all
three
plotting tools
enabled.

Numerical Methods

111

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

111

Exporting the Graph


Exporting a graph is the process of creating a standard graphics file
format of the graph (such as EPS or TIFF), which you can then
import into other applications like word processors, drawing
packages, etc.
This example exports the graph as an EPS file with the following
requirements:
The size of the picture when imported into the word processor document should
be 4 inches wide and 3 inches high.
All the text in the figure should have a size of 8 points.
Specifying the Size of the Graph
To set the size, use the Export Setup dialog box (select Export Setup from the
figure File menu). Then select 4 from the Width list and 3 from the Height list.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

112

Exporting the Graph

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

113

Exporting the Graph


To set the
font size of
all the text in
the
graph,
select Fonts
in the Export
Setup dialog
box
Properties
selector.
Then click
Use
fixed
font size and
enter 8 in the
text box.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

114

Exporting the Graph


Selecting the File Format
After you finish setting options for the exported graph, click the
Export button. A standard Save As dialog box opens that enables
you to specify a name for the file as well as select the type of file
format you want to use.
The Save as type drop-down menu lists a number of other
options for file formats. For this example, select EPS (*.eps)
from the Save as type menu.
You can import the saved file into any application that supports
EPS files.
You can also use the print command to print figures on your local
printer or to export graphs to standard file types.
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

115

Exporting the Graph

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

116

3D plots
plot3

The plot3 function displays a threedimensional plot of a set of data points.

mesh

Create mesh plot

surf

Create 3-D shaded surface plot

Meshgrid

The meshgrid function transforms the


domain specified by a single vector or two
vectors x and y into matrices X and Y for
use in evaluating functions of two variables.
The rows of X are copies of the vector x and
the columns of Y are copies of the vector y.

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

117

plot3
>>t=0:0.1:10*pi;
>>x=exp(-t/20).*cos(t);
>>y=exp(-t/20).*sin(t);
>>z=t;
>>plot3(x,y,z);
>>title('Esempio di plot 3D');
>>xlabel('x');
>>ylabel('y');
>>zlabel('z');

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

118

mesh

>>x=linspace(0,2*pi,50);
>>y=linspace(0,pi,50);
>>[X,Y]=meshgrid(x,y);
>>Z=sin(X).*cos(Y);
>>mesh(X,Y,Z);
>>title('Esempio di mesh (grafica wireframe)');
>>xlabel('x');
>>ylabel('y');
>>zlabel('z');

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

119

A wire frame model is a visual presentation of a three dimensional or


physical object used in 3D computer graphics. It is created by specifying
each edge of the physical object where two mathematically continuous
smooth surfaces meet, or by connecting an object's constituent using
straight lines or curves. The object is projected onto the computer screen
by drawing lines at the location of each edge.
Using a wire frame model allows visualization of the underlying design
structure of a 3D model. Traditional 2-dimensional views and drawings
can be created by appropriate rotation of the object and selection of
hidden line removal via cutting planes.
Since wireframe renderings are relatively simple and fast to calculate, they
are often used in cases where a high screen frame rate is needed (for
instance, when working with a particularly complex 3D model, or in realtime systems that model exterior phenomena).

In informatica, wireframe o wire frame model (lett. modello in fil di ferro ) indica un tipo di rappresentazione grafica da
computer di oggetti tridimensionali, detta anche vettoriale. Con questo metodo vengono disegnati soltanto i bordi dell'
oggetto, il quale di fatto resta trasparente al suo interno (sembrando, appunto, costruito con il fil di ferro). Questo metodo
richiede calcoli
molto pi semplici rispetto alla rappresentazione
di superfici,
ed quindi considerevolmente
pi veloce. 120
Numerical
Methods
F. Sgallari Dept.
Mathematics-CIRAM,
University of Bologna

surf
>>[X,Y]=meshgrid(-3:.2:3,-2:.2:2);
>>Z=exp(-(X.^2+Y.^2)/3);
>>surf(X,Y,Z);
>>title('Esempio di surf (grafica a faccette)');
>>xlabel('x');
>>ylabel('y');
>>zlabel('z');

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

121

surf
surf(X,Y,Z)
colormap hsv
colorbar

surf(X,Y,Z)
colormap hsv
alpha(.4)
Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

122

surf
surf(X,Y,Z,'FaceColor','red','EdgeColor','none')
camlight left;
lighting phong

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

123

>>x=rand(100,1)*2*pi;
>>y=rand(100,1)*pi;
>>z=sin(x).*cos(y);
>>xlin=linspace(min(x),max(x),40);
>>ylin=linspace(min(y),max(y),40);
>>[X,Y]=meshgrid(xlin,ylin);
>>Z=griddata(x,y,z,X,Y,'cubic');
>>mesh(X,Y,Z);
>>title('Esempio di mesh non uniforme');
>>hold on;
>>plot3(x,y,z,'.','MarkerSize',15);
>>xlabel('x');
>>ylabel('y');
>>zlabel('z');
>>grid on;

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

124

>>x=rand(100,1)*2*pi;
>>y=rand(100,1)*pi;
Interpolation of scattered data(x,y,z),
>>z=sin(x).*cos(y);
Visualize finterpolant function
>>xlin=linspace(min(x),max(x),40);
In the grid points XY
>>ylin=linspace(min(y),max(y),40);
>>[X,Y]=meshgrid(xlin,ylin);
>>Z=griddata(x,y,z,X,Y,'cubic');
>>mesh(X,Y,Z);
>>title('Esempio di mesh non uniforme');
>>hold on;
>>plot3(x,y,z,'.','MarkerSize',15);
>>xlabel('x');
>>ylabel('y');
>>zlabel('z');
>>grid on;

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

125

>>n=31;
>>theta=pi*(-n:2:n)/n;
>>phi=(pi/2)*(-n:2:n)'/n;
>>X=cos(phi)*cos(theta);
>>Y=cos(phi)*sin(theta);
>>Z=sin(phi)*ones(size(theta));
>>surf(X,Y,Z);
>>title('Esempio di surf in forma parametrica');
>>xlabel('x');
>>ylabel('y');
>>zlabel('z');
>>grid on;
>>axis square;

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

126

Manipulating the surface


The figure toolbar and the camera toolbar provide ways to
explore 3-D graphics interactively. Display the camera toolbar
by selecting Camera Toolbar from the figure View menu.
The following picture shows both toolbars with the Rotate 3D
tool selected.

Numerical
NumericalMethods
Methods

F. Sgallari Dept.
Dept.Mathematics-CIRAM,
Mathematics-CIRAM,
University
University
ofof
Bologna
Bologna

127

The best way to learn


MATLAB
is to use MATLAB

Numerical Methods

F. Sgallari Dept. Mathematics-CIRAM, University of Bologna

128

You might also like