Sunteți pe pagina 1din 10

1

Matlab Tutorial

1- What is Matlab?

Matlab is a powerful tool for almost any kind of mathematical application. It enables one
to develop programs with a high degree of functionality. The user can write programs,
scripts or interface with the program directly calling various math functions.

Matlab is more than a glorified calculator. It has powerful plotting capabilities that allow
one to plot 2D and 3D graphs, contour plots, vector plots, slices etc.

2- Basic Matlab

Matlab interfaces to the user through a scripting window. In essence, one types
commands into the ‘Command Window’. The Matlab engine then interprets these
commands and executes the appropriate function(s). For example, entering:

>> var1 = 2

var1 =

>> var2 = var1 + var1^2

var2 =

In this case in the first line the user asks Matlab to create a new variable var1 and
assign it a value of 2. Next, another variable is created var2 and an expression
involving var1 is evaluated and its value is assigned to the newly created variable.

The value assigned to a variable can be checked by simply typing in the variable name:

>> var2

var2 =

6
2

Let’s look at something a bit more useful. One of Matlab’s strong points is its ability to
deal with matrices of any dimension. Almost all fields of science use arrays. They are
very convenient and Matlab simplifies the handling of matrices greatly. For example,
let’s create three simple arrays:

>> A = [ 1 5;
3 6]

A =

1 5
3 6

>> B = [3 5.5 1.1;


4 1.2 1.33333]

B =

3.0000 5.5000 1.1000


4.0000 1.2000 1.3333

>> X = [0 2;
4 -1]

X =

0 2
4 -1

Three variables are created (A, B and X) which are arrays. Arrays can be created by the
use of square brackets and semi-colons. The opening square bracket tells Matlab that one
is defining an array. A space between numbers means that they are in adjacent columns,
while a semi-colon means the end of a row. One can check the size of an array:

>> size(B)

ans =

2 3

This means that array B is an array with 2 rows and 3 columns.

One can calculate the product of two matrices:

>> C = A*B

C =
3

23.0000 11.5000 7.7667


33.0000 23.7000 11.3000

In this case a variable C was created that was the product of the matrices A and B. Of
course, if the inner dimensions of the two matrices don’t agree then Matlab complains,
for example:

>> C = B*A
??? Error using ==> *
Inner matrix dimensions must agree.

What if one wants to multiply each element in an array with the corresponding elements
in another array:
>> Y = A.*X

Y =

0 10
12 -6

The ‘.’ in front of the operator tells Matlab to apply the operator ‘*’ between
corresponding elements. This holds for other operators.

The transpose of a matrix is easily calculated:

>> T = A'

T =

1 3
5 6

As is the inverse:

>> P = inv(T)

P =

-0.6667 0.3333
0.5556 -0.1111

To access an element in an array, all one needs to do is designate the column and row
index:
>> A(1,2)

ans =
4

To access several elements one uses the ‘:’ operator. For example to extract the first row
in array X and assign it to a new variable D one does:

>> D = X(1,:)

D =

0 2

In this case all the columns in array X are called using the ‘:’ operator. One can also
access a set of indices, for example:

>> D = C(1,1:2)

D =

23.0000 11.5000

In this example only columns 1 and 2 of row 1 are retrieved from array C.

The ‘:’ operator is also useful in defining arrays. For example, to obtain a vector that
starts at 0 and increases in 0.5 steps to a value of 5:

>> t = [0:0.5:5]

t =

Columns 1 through 10

0 0.5000 1.0000 1.5000 2.0000


2.5000 3.0000 3.5000 4.0000 4.5000

Column 11

5.0000

The first value specifies the start value, the second is the increment and the third is the
maximum value. By not entering an interval, Matlab assumes it to be equal to 1. One can
reference the last element in and index by using the reserved word ‘end’, for example, to
access elements 3 and on in vector t we use:

t(3:end)
5

This and many other basic features are well documented. To get started, check out the
following website:

http://math.ucsd.edu/~driver/21d-s99/matlab-primer.html

Also, Matlab itself has a lot of documentation. Help on a specific function can be
accessed by typing ‘help’ and then the name of the function. Also by typing
‘helpwin’ a dialog window pops up with a list of all the functions available. By typing
‘helpdesk’, Matlab will access the Mathworks website via the Netscape browser.

2.1 Plotting in Matlab


Plotting in Matlab is extremely easy and at the same time offers a great deal of control to
the user. One can alter any aspect of the plot by accessing its properties. In this section,
the basic Matlab plotting tools are presented.

Let’s plot a sine wave. First, the values that we wish to plot must be generated. First the
x-values must be created.

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

Here we are defining a vector with values that go from 0 to 2π (one period) with a step of
0.1. Note that arithmetic operations are allowed in the definition of arrays as long as
they result in real scalars .

Now let’s calculate the value of the sine wave at each value of x:

>> y = sin(x);

We passed a vector to the sin function. This is possible with most Matlab functions,
simplifying our task. Without this capability, one would have to loop through the vector
as in regular programming languages.

Now let’s plot the function. For basic 2D graphs, the function plot is used:

>> plot(x,y)
The plot functions plots x vs. y . x and y must be vectors of the same length.

The result is:


6

Let’s label the graph:

>> xlabel('x');
>> ylabel('y = sin(x)');
>> title('Plot of sine wave');

If we again call the function plot, the old plot is destroyed, along with labels, title etc. and
a new plot is created. To create a new figure one uses the command ‘figure’. At this
point the new figure is now the focus and all plot command are directed towards it.

One might want to have several plots on one pair of axes. For example, close all the
figures and type:

>> v = cos(x);
>> plot(x,y);
>> hold on;
>> plot(x,v,'r');
7

In this instance, a sine wave is plotted as before and then Matlab is told to hold the figure.
Then a cosine wave is plotted in red. This is accomplished by the third argument in the
plot command. This third command (if used) must be a string. It specifies the colour
and/or the line type and/or the symbols to be used. The result is shown. See the
documentation for the different available options.

3- Application

In Computational Fluid Dynamics (CFD), post processing data properly is crucial. In this
section, some of the tools that are useful in post processing are presented.

We will be using a flow field created using sinks and sources as an example.

First we need a mesh. This way we can solve the equations for velocity potential, stream
function, pressure and velocity at each point in the mesh, thereby supplying us with a set
of data. We will be using the function meshgrid.

>> [X Y] = meshgrid(-5:5:5,-5:5:5)

X =

-5 0 5
-5 0 5
-5 0 5

Y =

-5 -5 -5
0 0 0
5 5 5

Here we have created a simple 3x3 mesh. The array X holds the x-values for each node
point while the array Y holds the y-values.

We want our domain to stretch from x=-5 to x=5 in steps of 0.1 and from y=-5 to y=5
also in steps of 0.1:

[X Y] = meshgrid(-5:0.1:5,-5:0.1:5);

This returns two arrays (X and Y). Each one is 101 by 101 and contains the x and y
coordinates of each node respectively.

We are now going to calculate the flow-field that is caused by a source in uniform flow.
8

A set of user defined functions are provided with the tutorial. These functions can be
called in the same manner as the built-in Matlab functions.
First we need to know the influence of the uniform field on the velocity potential (phi)
and the stream function (psi) at every node. One can use the user defined function
unistreamtheta. The first parameter is the free-stream velocity (which is set to 1),
the second is the angle of attack in degrees (which in this case is set to 0). The 3rd and 4th
parameters are the X and Y coordinates of the nodes respectively.

U = 1;
[phi_stream,psi_stream] = unistreamtheta(U,0,X,Y);

Now we can visualize the streamlines by plotting the lines of equal psi. This entails
plotting the contour map of psi, which is accomplished through the use of the function
contour,

contour(X,Y,psi_stream,32);

where the additional argument specifies the number of contour lines to plot.

Let us now place a source at x=0 and y=0 and see what happens to the flow field. To do
this, we can calculate the influence of the source at each grid point by using equation
4.131 in White. We have created a function called source, which returns the value of
the velocity potential (phi) and the stream function (psi) at every node. We pass to the
function our arrays X and Y along with the strength of the source and its position:

strength = .50;
[phi_source,psi_source] = source(strength,X,Y,0,0);

The combined effect of the source and free-stream can again be plotted using contour.

contour(X,Y,psi_source+psi_stream,32);

A Rankine oval is created combining a source, sink and uniform stream:

[phi_source,psi_source] = source(strength,X,Y,-1,0);
[phi_sink,psi_sink] = source(-strength,X,Y,1,0);
contour(X,Y,psi_sink+psi_source+psi_stream,32);

We can also plot lines of equal potential:

hold on
lev = [-5:10/31:5];
contour(X,Y,phi_sink+phi_source+phi_stream,lev,’:’);

In this case, the contour map it produces has a great deal of lines close to the sink and
source and very few away from them. We need to tell Matlab what levels to plot. Also,
9

we wish to distinguish lines of equal potential from streamlines, so we plot the former
using dotted lines.

We can also calculate the velocity field by using equations 4.125 and 4.126. The function
velpsi returns the horizontal and vertical velocity components at each grid point based
on the stream function. It is also possible to calculate pressure at each grid point.

[u,v] = velpsi(X,Y,psi_stream+psi_sink+psi_source);
Vel = sqrt(u.^2 + v.^2);

rho = 1.2;
P = 0.5*rho*U^2 - 0.5*rho*Vel.^2;
vmin = 0;vmax = 1.5*U;
vv = vmin:(vmax-vmin)/31:vmax;
pp = (0.5*rho*U^2 - 0.5*rho*max(vv)^2):.1:0;

The contour levels for both the velocity and pressure variables are user specified.

figure
subplot(2,1,1)
contourf(X,Y,Vel,vv)
caxis([vv(1) vv(end)]);
colorbar
subplot(2,1,2)
[c,h] = contourf(X,Y,P,pp);
set(h,'EdgeColor','none');
caxis([pp(1) pp(end)])
colorbar

In this set of commands we want to plot the velocity (magnitude) contours and the
pressure contours. We create a new figure and then divide it into two axes by using the
command subplot(a,b,c) where a is the number of rows, b the number of columns
and c the axes which we want to target. So in this case we want two axes stacked one
below the other and we want to target the first one initially (subplot(2,1,1)). The
function contourf is identical to contour but in that it fills in the contours. We again
specify the levels by creating a variable vv. In the pressure plot, we wish to eliminate the
black lines between contour level. We accomplish this by setting the ‘EdgeColor’ to
‘none’.

NOTE: Every object in Matlab has a set of properties. The figure itself is an object, so are
the axes in the figure etc. The object attributes such as colour, line style, line type etc. can
be altered by the set function. The handle of the object is a pointer or identifier. So,
when setting a property, the object’s handle must be referenced.

figure(2);
10

hold on;
quiver(X(30:60,30:40),Y(30:60,30:40),u(30:60,30:40),v(30:60
,30:40));

Vector plots are often a good way of visualizing the velocity field. The function quiver
accomplishes this. This function scales the size of the arrows depending on the magnitude
of the velocity vector. In our example, the velocity field inside the Rankine oval is not
important but they still exist and have large magnitudes. Therefore a limit is imposed on
the area that is to be plotted.

S-ar putea să vă placă și