You are on page 1of 10

1

CH1801 Lab 1
Introduction to Matlab

Matlab is an interactive tool for scientific and engineering computations. Matlab stands
for Matrix Laboratory. It is powerful software for carrying out numerical calculations.
This manual has 3 parts which contain summary of basic commands, some examples and
assignment problems, respectively. You need to submit your solutions to the assignment
problems in the form of a word document containing all Matlab commands and plots
through Edventure within 2 weeks of the assigned lab date.

Part 1: Basics

Starting and Exiting Matlab

In SCBE, Matlab can be accessed in all the computer labs. Matlab can be started by
double-clicking on the shortcut icon on the desktop. When you start MATLAB, the
following MATLAB desktop appears:



The blinking cursor is called command line, where different commands can be entered. A
command is executed as soon as the enter key is pressed (no need to compile like C and
Fortran). To exit Matlab, you may use


>>quit

2
Getting Help

Matlab provides extensive help. To know the usage of the command det, you may use









In case you are not sure about which command to use to carry out a particular task, you
may invoke the helpdesk using



which opens the following GUI. Here you can search for commands easily.



Data Entry and Line Editing

The basic variables in Matlab are treated as matrices. Note that vectors and scalars are
special cases of a matrix. Matlab handles real and complex numbers equally well. To
define the scalar a with a value of 1, the assignment operator = is used.
>>help det

DET Determinant.
DET(X) is the determinant of the square matrix X.

Use COND instead of DET to test for matrix singularity.

See also cond.
>>helpdesk

3







Similarly, a row vector b with 4, -2, and 7 being its entries can be defined as








Continuing the same procedure, a matrix can be defined as









By default, i or j denote the imaginary number (square root of -1) in Matlab. Thus, a
complex vector can be defined by using







A few points to note here
Matlab is case sensitive. Thus, although we have defined d, D remains undefined.
The semicolon is used to denote the end of a particular row of a matrix. Following
this notation, the column vector e can be defined as







>>a =1

a =

1


>>b =[4 -2 7]

b =

4 -2 7


>>C =[2 4 5;4 2 3;7 9 10]

C =

2 4 5
4 2 3
7 9 10


>>d =[1+j*2 3+j*4]

d =

1.0000 +2.0000i 3.0000 +4.0000i

>>e =[3;2;5]

e =

3
2
5

4
By default, Matlab echoes the output of every command that is issued. The
echoing can be suppressed by putting a semicolon at the end of the command.



The individual elements of a matrix can be accessed by using Variable name(row
index, column index). For example, C(2,1) is the element belonging to 2
nd
row and
1
st
column of the matrix C.
Matlab remembers previously entered commands. These commands can be
recalled by pressing up and down arrows, edited and reentered as new commands.

Matrix Operations

As mentioned before, Matlab is very efficient for carrying out matrix operations like
transpose, multiplication, division, addition and subtraction.









Note that any commands preceded by % are treated as text comments. Some more
advanced operations include finding the inverse, rank, determinant, trace and eigenvalues
of a matrix.







Some other useful operations are trigonometric functions (cos, sin, tan), inverse
trigonometric functions (asin, acos, atan), exponential (exp), natural logarithm (log) and
logarithm with base 10 (log10). You can compute various statistics of a data set like
average (mean), standard deviation (std), variance (var), summation (sum), minimum
(min) and maximum (max). The usage of all these functions is fname(variable).

Graphics

As compared to programming languages like C and Fortran, Matlab has better graphics
handling capabilities. Matlab can maintain several figure windows at the same time.
Multiple curves can be plotted in each figure window, as shown below.

>>e =[3;2;5];

>>D =C'; % transpose of matrix C
>>C +D; % element-by-element addition
>>C - D; % element-by-element subtraction
>>C*D; % Matrix multiplication
>>C.*D; % element-by-element multiplication
>>C./D; %element-by-element division
>>C\D; % matrix division, same as inv(C)*D
>>inv(C); %Matrix inverse
>>det(C); %determinant
>>trace(C); %trace
>>rank(C); %rank
>>eig(C); %eigenvalues
5











The plots produced using these commands can be embellished with figure title, axes title
etc. This can be done directly from workspace, but it is much more convenient to use a
GUI. To enable the property editor for figure window, select the arrow button and click
on the white space anywhere in the plot window. This opens up the figure editor palette,
where different details can be entered. You can change the color, line width, marker style
etc. for a curve by selecting the same arrow button and double clicking on the curve.

If you need to copy this figure to a word document, you can use Edit>Copy Figure from
the menu. Then use of paste command in word will copy the figure. You can also save a
figure as an individual file by using File>Save As from the menu. By default, the figure
is saved as a .fig file, which can be read by Matlab only. You can also save your figure as
a picture (jpeg, gif etc.) by selecting the appropriate filetype from the pull down menu.

>>x =[0 0.6 1.2 1.8 2.4 3.0 3.6 4.2 4.8 5.4 6.0]; % define vector x
>>plot(x,sin(x)) % open a new figure window and plots x Vs. sin(x)
>>hold % keep the current curve. Omitting this command will
Current plot held % overwrite the previous curves
>>plot(x,cos(x),'r') % plot cos(x) in same figure window with line color being red
>>figure % open a new figure window
>>plot(cos(x),sin(x),'g') % plot cos(x) Vs. sin(x)

Click this button and double-click
anywhere on the white space to activate
property editor
6
Saving and Deleting Results

The available variables in the workspace can be seen by using












which shows the available variables, their size, Bytes used for storing them, class (single
precision, double precision, integer, character etc.) and attribute (real or complex). If you
want to save all these available variables, you can use



which creates a file called primerdata.mat in the current directory. A selected set of
variables can be saved using



where the variables to be saved follow the filename. These variables can be loaded back
to the workspace using



To delete all the variables from the workspace, you can use



As before, a set of selected variables can be deleted using



>>whos
Name Size Bytes Class Attributes

C 3x3 72 double
a 1x1 8 double
b 1x3 24 double
d 1x2 32 double complex
e 3x1 24 double
f 1x5 40 double
g 1x9 72 double
>>save primerdata
>>save primerdata a b c
>>load primerdata
>>clear all
>>clear a b c
7
Part 2: Examples

This section contains some examples, which can be solved using Matlab.

Solving linear equations

Consider that we want to find x and y, which satisfy

2x +3y =5 (1)
3x +7y =-5 (2)

These equations can be expressed in matrix notation as

b Az = (3)

where


(

=
(

=
(

=
5
5
, ,
7 3
3 2
b
y
x
z A (4)

Now the unknowns x and y can be found as




















The last command (A*z-b) verifies the solution. Note that the numerical solution is
almost zero, but not exactly zero due to finite precision used by software.


>>A =[2 3; 3 7];
>>b =[5;-5];
>>z =A\b

z =

10.0000
-5.0000
>>A*z-b

ans =

1.0e-014 *

-0.3553
0.7105
8
Solving nonlinear equations

Consider the following formula used to determine the friction factor f in pipes:


|
|
.
|

\
|
+ =
f
D e
f Re
51 . 2
7 . 3
log 0 . 2
1 (5)

where e/D =0.0001 and Re =50000. The unknown f cannot be found analytically, but
the command fzero can be used for finding f numerically. The command fzero iteratively
solves equations of the form f(x) =0 starting a user supplied initial value. The syntax for
using fzero is x = fzero(@(x) f(x),x0), where f(x) is the function and x0 is the initial
guess. With a simple rearrangement of the nonlinear equation (5) and using f =0.05 as
the initial guess, the nonlinear equation can be solved as















The last command verifies the obtained solution. A few remarks about this example are
as follows:

With default settings, Matlab only echoes the first few significant digits of a
variable. More significant digits can be obtained by changing the format to long.
The solution obtained using fzero heavily depends on the supplied initial guess
and for certain initial guesses, it may fail to find any solution, as is the case with
most of numerical schemes for solving nonlinear equations.

Linear Regression

Often, a model needs to be fitted to data obtained using experiments. For example,
consider the following conductivity (K) measurements at different temperatures (T):

T (
o
C) 231.07 240 260 280 300 320 340 360
K (Mho/cm) 0.0114 0.0121 0.0139 0.0159 0.018 0.0202 0.0226 0.0252

>>format long
>>f =fzero(@(f) 1/sqrt(f)+2*log10(0.0001/3.7 +2.51/(50000*sqrt(f))),0.05)

f =

0.021247883751740

>>1/sqrt(f)+2*log10(0.0001/3.7 +2.51/(50000*sqrt(f)))

ans =

0
9
The following model is proposed


b
aT K =

(6)
where a and b are unknown parameters. By taking the logarithm of both sides of equation
(6), we have
T b a K log log

log + = (7)

Equation (7) corresponds to the expression of a straight line with slope b and intercept
log a. Now, the model can be fitted by using the Matlab command polyfit, which fits
polynomial-type models of the form


1
1
2 1
.....
+

+ + + + =
n n
n n
p x p x p x p y (9)

The usage of this function is p = polyfit(x,y,n), where x is the independent variable, y is
the dependent variable and n is the order of the polynomial to be fitted. For the given data
set, a linear model (polynomial of order 1) can be fitted as follows:

























The last 2 commands compute the predicted conductivity values and compare them
against the experimentally measured values.

>>T=[231.07 240 260 280 300 320 340 360];
>>K=1e-2*[1.14 1.21 1.39 1.59 1.80 2.02 2.26 2.52];
>>p =polyfit(log10(T),log10(K),1)

p =

1.7918 -6.1820

>>b =p(1)

b =

1.7918

>>a =10^p(2)

a =

6.5764e-007

>>Khat=a*(T.^b);
>>plot(T,K,'r+-',T,Khat,'ko-')
10
Part 3: Assignment Problems

1. The roots of quadratic equation
0
2
= + + c bx ax
are given as


a
ac b b
x
2
4
2

=
(8)

Using equation (8), find x for a =4, b =-4, c =0.2. Verify your solution using the Matlab
command roots.

2. A refinery produces Gasoline, Kerosene and Fuel oil using three different grades of
crude oil. The percentage yields of each of these products from the different grades of
crude oil are given as

Crude oil #1 Crude oil #2 Crude oil #3
Gasoline 0.8 0.6 0.5
Kerosene 0.15 0.25 0.15
Fuel oil 0.05 0.15 0.35

Find the quantities of each of the crude oils, which are needed to produce a) 29500, 7500
and 6000 barrels/day of Gasoline, Kerosene and Fuel oil, respectively; and b) 16000,
3000 and 1000 barrels/day of Gasoline, Kerosene and Fuel oil, respectively.

3. The Van der Waals equation of state is given as

( ) RT b v
v
a
p =
|
.
|

\
|
+
2
(9)
where p is the pressure, v is the specific volume of the gas, T is absolute temperature, R =
0.083145 L
2
bar
-1
mol
-2
is the universal gas law constant, and a and b are Van der Waals
constants. At p =0.8 bar and T =400 K, fine the specific volume of CO
2
(a =3.640 L
2

bar mol
-2
, b =0.04267 L mol
-1
) and N
2
(a =1.408 L
2
bar mol
-2
, b =0.03913 L mol
-1
).
Which of these gases have a higher specific volume at the given conditions?

4. For mixtures of acetone (A) and ethanol at 1 atm, the liquid fraction and temperature at
equilibrium conditions are given in the following table:

T (
o
C) 78.3 67.3 65.9 63.6 61.8 60.4 59.1 58.0 57.0 56.1
x
A
0.000 0.250 0.300 0.400 0.500 0.600 0.700 0.800 0.900 1.000

Fit a model given by a 3
rd
order polynomial to this dataset considering x
A
as the
independent variable and T as the dependent variable. Compare your model predictions
by plotting together with the experimentally recorded values. Label your graph clearly.

You might also like