Professional Documents
Culture Documents
MATLAB
Fiorella Sgallari
University of Bologna, Italy
School of Engineering and Architecture
Department of Mathematics - CIRAM
Numerical Methods
Tutorials
MATHWORKS web site:
http://it.mathworks.com/
Numerical Methods
Overview
Introduction and Overview
Matrix manipulations and common functions
M Files: Script-Function
Programming
Plots in MATLAB
Numerical Methods
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
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
Matrix manipulation
Finding the roots of polynomials
Digital signal processing applications
Plotting: x-y and polar, 3D graphics
Algorithm development,
Modeling, simulation, and prototyping,
Data acquisition
Data analysis, exploration, and visualization,
Application development, including graphical user interface building.
Numerical Methods
Numerical Methods
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.
Numerical Methods
Numerical Methods
10
Numerical Methods
11
Numerical Methods
12
Numerical Methods
13
Numerical Methods
14
Numerical Methods
15
Numerical Methods
16
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
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
18
Command Window
Command window
>> 39*4.4+5
ans =
176.6000
Command window
The result.
Numerical Methods
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
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
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
22
Different Views
Numerical Methods
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
24
Matlab Help
Numerical Methods
25
Numerical Methods
26
Matlab Programming
Two Approaches
Coding in Command Window
Good for short programs
Commands must be re-entered each time you run a
simulation
Numerical Methods
27
Write your
commands here
Numerical Methods
28
Numerical Methods
29
Numerical Methods
30
.m-file Interface
Write your
commands here
31
Editor
Numerical Methods
32
Operation
MATLAB
exponentiation: ab
a^b
multiplication: ab
a*b
a
b
a/b
a\b
addition: a + b
a+b
subtraction: a-b
a-b
1/4=4\1=0.25
Numerical Methods
33
>
Greater than
>=
<
Less than
<=
==
equal
~=
Not equal
(for ~ in an italian keyboard press ALT and digit 126 on the numeric keyboard)
Numerical Methods
34
&
AND
OR
NOT
Numerical Methods
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
36
Examples
a = sqrt(3);
Double
c = -2+i*8.2
Complex double
t = a<1
Logical double
q = 'k'
Char
'
var_txt'
Numerical Methods
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
38
Basics: Variables
Numerical Methods
39
Description
ans
eps
i,j
Inf
infinity
NaN
pi
realmax
realmin
Numerical Methods
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 %
41
Row vector
The square braces are
used to define a matrix
X=[2,3 7 ]
X=
2 3
Numerical Methods
42
42
Column vector
The square braces are
used to define a matrix
X=[2;3 ; 7 ]
X=
2
3
7
Numerical Methods
43
43
MATLAB Statements
MATLAB Statement
Remarks
C=5.66
C is a scalar
C=[5.66]
An alternative way
Y=[1
4]
Y = [ 1 ; 4]
A=1:5
Equivalent to A=[1 2 3 4 5]
Numerical Methods
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
45
45
% 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
46
Generating Matrices
>> B = [ 1 2 ; 8 9 ]
ans =
1 2
8 9
>> ones(2,2)
ans =
1 1
1 1
>> zeros(2,3)
ans =
0 0 0
0 0 0
>> 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
47
>> 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>)
column?
Numerical Methods
A(:,end)
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
49
Basic Syntax
Mathematical (Array) Operators
Mathematical
Mathematical Array
+
*
/
Addition
Division
+
.*
./
Power
.^ Power
Subtraction
Multiplication
Addition
Subtraction
Multiplication
Division
50
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
Numerical Methods
What is B / B ? B ./ B ?
F. Sgallari Dept. Mathematics-CIRAM, University of Bologna
51
Numerical Methods
A=
1
52
53
A=
% 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
>> abs(x)
x=5
%Absolute value.
>> angle(x)
x = 0.9273
>> conj(x)
x = 3-4j
%Complex conjugate.
>> imag(x)
x=4
>> real(x)
x=3
Numerical Methods
55
Basics: Commands
Command
Description
clc
clear
exist (name)
quit
Stops MATLAB
who
whos
generates array
continues a line
Numerical Methods
56
Format output
Output can be visualized in different form:
SHORT
Scaled fixed point format, with 4 digits after the decimal point.
SHORT E
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
LONG G
RAT
Numerical Methods
57
Numerical Methods
: format short
58
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
59
Numerical Methods
60
choices=['B','D','F'];
k=menu('Whodoyouwant?',choices(1),choices(2),choices(3));
disp(['You picked ',choices(k)])
Numerical Methods
61
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
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
64
Numerical Methods
Function files
Starts with function
List of MATLAB
statements
Variables are local
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
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
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
68
Creating M-files
Select FILE OPEN NEW M-files
Numerical Methods
69
69
MATLAB shortcuts
Create
a New
file
Numerical Methods
70
70
Numerical Methods
71
Example
Write a function file to compute the
factorial of a number.
Input: N
Output :NF
Function name: Myfactorial
Numerical Methods
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
73
73
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
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
75
75
76
76
Numerical Methods
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
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)');
79
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
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
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
82
Example
function s = fsum(fun,a,b,n)
%
%
%
%
%
%
%
%
%
fsum
Synopsis:
Input:
Output:
s = fsum(fun,a,b,n)
x = linspace(a,b,n);
y = feval(fun,x);
s = sum(y);
Numerical Methods
a <= x <= b
%
%
%
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);
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
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
General form:
switch switch_expr
case case_expr
statement, ..., statement
case {case_expr1, case_expr2, .}
statement, ..., statement
otherwise
statement, ..., statement
end
Numerical Methods
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
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
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
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
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)
legend(text)
Places a legend
figure n
hold on
Numerical Methods
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
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
Numerical Methods
95
95
Numerical Methods
96
96
Example
Generating data
time=[0:0.01:6]
Y=sin(time)
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
97
97
Example
time=[0:0.01:6]
Y=sin(time)
plot(Y)
Numerical Methods
Generating data
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
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
3
x = 0:2
100
x[k]
0.5
0
-0.5
-1
Numerical Methods
10
15
0k5
20
25
30
101
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
102
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
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)
plot(t,y4),
title(Here is the absolute value')
Numerical Methods
104
Subplot
Numerical Methods
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
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
108
Figure Tools
The figure also shows three figure toolbars
Numerical Methods
109
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
110
Figure Tools
The following
picture shows
a figure with
all
three
plotting tools
enabled.
Numerical Methods
111
111
Numerical Methods
112
Numerical Methods
113
Numerical Methods
114
115
Numerical Methods
116
3D plots
plot3
mesh
surf
Meshgrid
Numerical Methods
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
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
119
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
121
surf
surf(X,Y,Z)
colormap hsv
colorbar
surf(X,Y,Z)
colormap hsv
alpha(.4)
Numerical Methods
122
surf
surf(X,Y,Z,'FaceColor','red','EdgeColor','none')
camlight left;
lighting phong
Numerical Methods
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
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
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
126
Numerical
NumericalMethods
Methods
F. Sgallari Dept.
Dept.Mathematics-CIRAM,
Mathematics-CIRAM,
University
University
ofof
Bologna
Bologna
127
Numerical Methods
128