You are on page 1of 65

MATLAB Introduction

Matlab Introduction
Is an interactive, matrix-based system for scientific and
engineering numeric computation and visualization.
You can solve complex numerical problems in a fraction
of the time required with a programming language such
as Fortran or C.
The name MATLAB is derived from MATrix LABoratory.
The command prompt is the symbol >>.
When using MATLAB, the command help functionname
will give information about a specific function.
A list of available functions and commands may be
displayed by typing "help"
You can preview some of the features of MATLAB by
just entering the command demo and then selecting from
the options offered.
Matlab introduction

Typing either "exit" or "quit" at the command prompt will


get you out of the program and back to the operating
system.
AN IMPORTANT NOTE-MATLAB is normally casesensitive. All built-in commands are in lower case.
Consider the MATLAB command
>> sin(0.25*pi)
Note that
(a) "pi" is a built in constant,
(b) "sin" is the built in function that returns the sine of an
angle,
(c) angles are accepted (and returned) in radians and
not degrees and
(d) numbers can be entered in almost any format such
as 0.25, 1/4 or 2.5e-1.
Matlab introduction

On pressing the ENTER key this command is instantly


executed, as is every other command "entered" at the
command prompt, and MATLAB responds with the onscreen display
ans
= 0.7071
note that the answer, is stored in the variable "ans",
since no variable was specified on the command line.
we may enter the following
>> s=sin(pi/4)
This will result in the display
s
= 0.7071
Matlab introduction

NOTES:
1.The variable "ans" always stores results of the most
recent command.
2.Comments may be inserted with any command
following the percent sign %"
>> exp(-1) % The exponential quantity e^(-1)
>> ans*exp(1) % Ans here is e^(-1) so this should yield 1
>> ans*2 % Ans here is 1, so this should yield 2
Arrays or rows of values can be generated by entering
values separated by commas or spaces and enclosed in
square brackets. The statement x=[1 3 5 7] stores the
numbers 1 3 5 7 in the variable x

Matlab introduction

THE ELLIPSIS
An array list longer than one line can be continued on the next by
using an ellipsis (... i.e. two or more periods followed by a carriage
return) No MATLAB prompt or display will appear until the enter key
is pressed again. In the following command, the first line contains an
ellipsis followed by a carriage return. The second line is also
followed by a carriage return Only after the second line is entered is
the command executed
>>x=[1 2 3 4 ...
5 6]
THE COLON
Generation of arrays is made painless using the colon ":". Thus
>> x=1:6 % yields the array [1 2 3 4 5 6]
The default increment is one. For a different increment, use for
example
>> y=0.2:.2:1.1 %yields the array [.2 .4 .6 .8 1.0]

Matlab introduction

THE SEMI-COLON
The semi-colon ";", used after a command is equally
useful. It actually suppresses the onscreen display of
results (but not the execution of a command). Thus the
command z=1:300; generates an array with values from
1 to 300 and simply returns to the MATLAB prompt upon
execution without displaying the values on the screen.
The result is
>> z=1:300;
The variable z does indeed exists in the workspace. For
example
>> z(1) % the first element of the array z which should
equal 1

Matlab introduction

ABORTING DISPLAYS OR EXECUTION


Actually, typing "CTRL-C" aborts the currently executing
command or operation
THE COMMA, SEMI-COLON AND CONCATENATION
More than one command can be included in a single line
provided the commands are separated by commas
(which do not suppress the on-screen display of the
preceding command) or semi-colons (which do).
>> x=2,y=3*x*x;z=y-6*x % This will display x and z but not
y Note that the semi-colon suppresses display of the
second command
VARIABLES AND MATRICES
Every variable in MATLAB is regarded as a matrix , even
if its dimensions are 1*1 (a single element). No
dimensioning (or type declaration) is required and
MATLAB automatically allocates the appropriate storage.
Matlab introduction

Index values for matrices always start at one (and not


zero as with some computer languages).
Individual elements are addressed by their row and
column indices (as in A(2,3), the element in row 2 and
column 3). If you execute the following statement
>> avar(2,2)=3
Notice how MATLAB has recognized avar(2,2) as the
element of a matrix and assigned
enough storage to avar which it recognizes as a 2*2
matrix. Now if we enter
>> avar(2,3)=4
storage is automatically allocated to avar based on the
element of avar that is encountered.
Element values can be changed. For example
>> avar(1,2)=5
Matlab introduction

Elements of a matrix may be entered by rows, with


elements separated by spaces (or commas) and rows
separated by semi-colons, all within square brackets.
The command
>> b=[1 2 4; 3 1 2] % results in a 3x2 matrix
NOTE: In this format, all rows must have the same
number of elements.
COMPLEX NUMBERS Variables may be complexvalued. Complex entries are entered in rectangular form
(e.g. 2+i*3). All results are returned in the same form.
Either i or j may be used for the imaginary unit. Consider
for example.
>> j=sqrt(-1);i=j; % Force i or j to be imaginary unit (not
necessary).
>> zc=2+j*3 % A complex number
Its real and imaginary parts may be accessed via
>> zr=real(zc),zi=imag(zc)
Matlab introduction
10

NOTE: Angles are returned in radians. To find the angle


in degrees, we use the conversion deg=rad*180/pi.
>> za= 180*angle(zc)/pi %Angle of zc in degrees
TRANSPOSE
The transpose command is an apostrophe ('). Consider
>> c=[1 5 2;3 4 8] % 2x3 matrix
The transpose of this matrix is
>> c' % the transposed 3x2 matrix
OPERATIONS ON MATRICES AND THE "DOT"
CONVENTION
Let us choose two matrices a and b and define the
various operations allowed by MATLAB. These
seemingly innocuous operations can actually prove both
powerful or disastrous depending on how they are used
or misused.
Matlab introduction

11

>> a=[1 2;3 4],b=[4 5;6 7]


ADDITION AND SUBTRACTION:
In operations involving a scalar and a matrix, the scalar
is treated as a matrix with the same dimensions as the
matrix with all entries equal to the scalar value. The
operations of addition and subtraction are performed
element by element.
>> c=4-a
For two matrices, addition and subtraction is also
element wise provided the dimensions are identical.
>> d=a-b
MULTIPLICATION
The operation a.*b (NOTE THE DOT) denotes element
wise multiplication. Here a and b may be matrices of the
same size or one or both may be scalar.
>> c=a.*b
Matlab introduction

12

If a is a scalar, each element is of b is multiplied by a


>> a,d=4 .*a
NOTE the space between 4 and the dot is important in
v3.5, else the dot acts as a decimal point following the 4.
To avoid confusion enclose numbers in ().
For matrices, a*b denotes matrix multiplication. The
columns of a must equal the rows of b. If not, an error
results. If a is scalar, a*b = a.*b.
>> a,d=4;d1=d.*a,d2=d*a
DIVISION
Elementwise division is produced by using a./b. Either a
or b may be scalar
>> a=[2 4;6 8],b=[1 2;2 4],c=a./b

Matlab introduction

13

The quantity a/b is not defined in the usual sense.


Actually there are two types of division operators in
MATLAB, the left and right division denoted by the
slashes / and \. We shall not discuss these at this time
EXPONENTIATION
Exponentiation can also be elementwise (.^) or
matrixwise (^).
>> a=[1 2;3 4],b=a.^2,c=(2).^a
NOTE: Elementwise exponentiation requires
dimensional consistency unless the variable or exponent
is a scalar
But functions such as sqrt (square root), exp (raising to
the power e) are all implemented elementwise.
>> a=[1 4;9 36],b=sqrt(a)
Matlab introduction

14

POLYNOMIALS AND ROOTS


Consider the polynomial f(x) = x^3 + 5x^2 +3x + 2. To
find its roots, we set up the coefficient array as follows
>> p=[1 5 3 2]
Note that the coefficients are in descending powers of x.
To find its roots we use the routine roots as follows
>>rts=roots(p)
Note that rts is a column vector!! To reassemble the
polynomial from its roots, we use the command poly
>> pp=poly(rts)

Matlab introduction

15

To evaluate the polynomial f(x) at various values of x we


first generate an array of values.
For example
>>zz=[0 1 2 -1]
Then we use the command polyval to evaluate the
polynomial as follows
>>ff=polyval(p,zz)
>>clear a a1 avar b c d d1 d2 e ff i j k p pp rts s
>>clear x y ymax ymin z za zabs zc zi zr zstar zz
>>clear

Matlab introduction

16

If you do not know the exact command for the function


that you are after, another useful command is lookfor.
This command works somewhat like an index. If you did
not know the command for the exponential function was
exp, you could type
lookfor exponential
EXP Exponential.
EXPM Matrix exponential.
The MATLAB Workspace
We can view the variables currently in the workspace by
typing
who
Your variables are:
ans x y z
Matlab introduction

17

Sometimes it is desirable to clear all of the variables in a


workspace. This is done by simply typing
clear
more frequently you may wish to clear a particular
variable, such as x
clear x
You may wish to quit MATLAB but save your variables
so you don't have to retype or recalculate them during
your next MATLAB session. To save all of your
variables, use
save file_name
(saving your variables does not remove them from your
workspace; only clear can do that)
To load a set of previously saved variables
load file_name
Matlab introduction

18

Plotting
For a standard solid line plot, simply type
plot(x,z)
Axis labels are added by using the following commands
xlabel('x')
ylabel('z')
Consider now the following equation
y(t) = 4 e-0.1 t
we can solve this for a vector of t values by two simple
commands
t = 0:1:50;
y = 4*exp(-0.1*t);
and we can obtain a plot by typing
plot(t,y)
Matlab introduction

19

Notice that we could shorten the sequence of commands


by typing
plot(t,4*exp(-0.1*t))

Matlab introduction

20

Matlab introduction

21

Matlab introduction

22

Matlab introduction

23

Matlab introduction

24

Plotting Multiple Curves


Eachtime you execute a plotting command, MATLAB
erases the old plot and draws a new one. If you want to
overlay two or more plots, type hold on.
This command instructs MATLAB to retain the old
graphics and draw any new graphics on top of the old.
It remains in effect until you type hold off.
Heres an example using ezplot:
The commands
>> ezplot(exp(-x), [0 10])
hold
>> hold on
on and hold off
>> ezplot(sin(x), [0 10])
work with all
>> hold off
graphics
commands.
>> title exp(-x) and sin(x)
Matlab introduction

25

Matlab introduction

26

Adding Plots to an Existing Graph


The hold command enables you to add plots to an
existing graph. When you type
hold on
MATLAB does not replace the existing graph when you
issue another plotting command; it adds the new data to
the current graph, rescaling the axes if necessary.
hold off
This command reverses the plotting.

Matlab introduction

27

Multiple Plots in One Figure


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 first the top row of
the figure window, then the second row, and so on. For
example, these statements plot data in four different
subregions of the figure window.

Matlab introduction

28

t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
Setting Grid Lines
The grid command toggles grid lines on and off. The
statement
grid on
turns the grid lines on and
grid off
turns them back off again.
Matlab introduction

29

ezplot lets you plot the graph of a function directly from


its defining symbolic expression.
syms t x y
ezplot(sin(2*x))
ezplot(t + 3*sin(t))
ezplot(2*x/(x^2 - 1))
ezplot(1/(1 + 30*exp(-x)))
By default, the x-domain is [-2*pi, 2*pi]. This can be
overridden by a second input variable, as with:
ezplot(x*sin(1/x), [-.2 .2])
You will often need to specify the x-domain and ydomain to zoom in on the relevant portion of the graph.
Compare, for example,
ezplot(x*exp(-x))
ezplot(x*exp(-x), [-1 4])
Matlab introduction

30

ezplot attempts to make a reasonable choice for the


yaxis. With the last figure, select Edit Axes Properties
in the Figure window and modify the y-axis to start at -3,
and hit enter. Changing the x-axis in the Property Editor
does not cause the function to be reevaluated, however.
To plot an implicitly defined function of two variables:
ezplot(x^2 + y^2 - 1)
which plots the unit circle over the default x-domain and
y-domain of [-2*pi, 2*pi]. Since this is too large for the
unit circle, try this instead:
ezplot(x^2 + y^2 - 1, [-1 1 -1 1])
The first two entries in the second argument define the
xdomain. The second two define the y-domain. If the
ydomain is the same as the x-domain, then you only
need to specify the x-domain.
Matlab introduction

31

fplot (' exp(-2*t)+exp(-3*t)',[0,5])


MATLAB supplies a function fplot to plot the graph of a
function.to plot the graph of the function above, you can
first define the function in an M-file called, say,
expnormal.m containing:
function y = expnormal(x)
y = exp(-x.^2) ;
Then:
fplot(@expnormal, [-3 3])
will produce the graph over the indicated x-domain.

Matlab introduction

32

Workspace window
lists variables that you have either entered or computed
in your MATLAB session
The command who (or whos) lists the variables currently
in the workspace.
A variable or function can be cleared from the workspace
with the command clear variablename or by rightclicking
the variable in the Workspace editor and selecting
Delete. The command clear alone clears all variables
from the workspace.
invoking the command save before exiting causes all
variables to be written to a machine-readable file named
matlab.mat in the current working directory.
When you later reenter MATLAB, the command load will
restore the workspace to its former state.
Matlab introduction

33

Command History window


This window lists the commands typed in so far.
You can re-execute a command from this window by
doubleclicking or dragging the command into the
Command window.
For more options, select and right-click on a line of the
Command window.

Matlab introduction

34

Array Editor window


Once an array exists, it can be modified with the Array
Editor, which acts like a spreadsheet for matrices. Go to
the Workspace window and double-click on the matrix C.
Click on an entry in C and change it, and try changing
the size of C. Go back to the Command window and
type: C and you will see your new array C. You can also
edit the matrix C by typing the command openvar('C').

Matlab introduction

35

Current Directory window


Your current directory is where MATLAB looks for your
M-files, and for workspace (.mat) files that you load and
save.
You can also load and save matrices as ASCII files and
edit them with your favorite text editor.
The file should consist of a rectangular array of just the
numeric matrix entries.
Use a text editor to create a file in your current directory
called mymatrix.txt (or type edit mymatrix.txt) that
contains these 2 lines:
22 67
12 33
Type the command load mymatrix.txt, and the file will be
loaded from the current directory to the variable
mymatrix.
Matlab introduction

36

The file extension (.txt in this example) can be anything


except .mat.
You can use the menus and buttons in the Current
Directory window to peruse your files, or you can use
commands typed in the Command window.
The command pwd returns the name of the current
directory, and cd will change the current directory.
The command dir lists the contents of the working
directory, whereas the command what lists only the
MATLAB-specific files in the directory, grouped by file
type.
The MATLAB commands delete and type can be used to
delete a file and display a file in the Command window,
respectively
Matlab introduction

37

The while loop


The general form of a while loop is:
while expression
statements
end
The statements will be repeatedly executed as long as the
expression remains true. For example, for a given number a, the
following computes and displays the smallest nonnegative integer n
such that 2n > a:
a = 1e9
n=0
while 2^n <= a
n=n+1;
end
n

Matlab introduction

38

The for loop


This loop:
n = 10
x = []
for i = 1:n
x = [x, i^2]
end
produces a vector of length 10,
You can terminate a for or while loop with the break
statement and skip to the next iteration with the continue
statement.

Matlab introduction

39

Here is an example for both. It prints the odd integers


from 1 to 7 by skipping over the even iterations and then
terminates the loop when i is 7.

Matlab introduction

40

The if statement
The general form of a simple if statement is:
if expression
statements
end
The statements will be executed only if the expression is
true. Multiple conditions also possible:

Matlab introduction

41

M-files
MATLAB can execute a sequence of statements stored
in files. These are called M-files because they must
have the file type .m as the last part of their filename

M-file Editor/Debugger window


M-files are usually created using your favorite text editor
or with MATLABs M-file Editor/Debugger.
See also Help: MATLAB: Desktop Tools and
Development Environment: Editing and Debugging MFiles.
There are two types of M-files: script files and function
files.

Matlab introduction

42

Create a new M-file, either with the edit command, by


selecting the File New M-file menu item, or by
clicking the new-file button
Type in these lines in the Editor,
f = sum(A, 2) ;
A = A + diag(f) ;
and save the file as ddom.m by clicking:
The semicolons are there because you normally do not
want to see the results of every line of a script or
function.

Matlab introduction

43

Script files
A script file consists of a sequence of normal MATLAB
statements. Typing ddom in the Command window
causes the statements in the script file ddom.m to be
executed. Variables in a script file refer to variables in
the main workspace, so changing them will change your
workspace variables. Type:
A = rand(3)
ddom
A
in the Command window. It seems to work; the matrix A
is now diagonally dominant.

Matlab introduction

44

Function files
Function files provide extensibility to MATLAB.
You can create new functions specific to your problem,
which will then have the same status as other MATLAB
functions.
Variables in a function file are by default local.
Convert your ddom.m script into a function by adding
these lines at the beginning of ddom.m:
function B = ddom(A)
% B = ddom(A) returns a diagonally
% dominant matrix B by modifying the
% diagonal of A.
and add this line at the end of your new function:
B=A;
Matlab introduction

45

The first line of the function declares the function name,


input arguments, and output arguments; without this line
the file would be a script file.
Then a MATLAB statement D=ddom(C), for example,
causes the matrix C to be passed as the variable A in
the function and causes the output result to be passed
out to the variable D.
Since variables in a function file are local, their names
are independent of those in the current MATLAB
workspace.
Your workspace will have only the matrices C and D.
Lines that start with % are comments;
An optional return statement causes the function to finish
and return its outputs.
An M-file can reference other M-files, including itself
recursively.
Matlab introduction

46

User input
In an M-file the user can be prompted to interactively
enter input data, expressions, or commands. When, for
example, the statement:
iter = input('iteration count: ') ;
is encountered, the prompt message is displayed and
execution pauses while the user keys in the input data
(or, in general, any MATLAB expression).
Upon pressing the return or entry key, the data is
assigned to the variable iter and execution resumes.

Matlab introduction

47

Echoing Commands.
the commands in a script M-file will not automatically be
displayed in the Command Window. If you want the
commands to be displayed along with the results, use
echo:
echo on
format long
x = [0.1, 0.01, 0.001];
y = sin(x)./x
echo off

Matlab introduction

48

Adding Comments.
It is worthwhile to include comments in a lengthy script M-file.
Any line in a script M-file that begins with a percent sign is treated as
a comment and is not executed by MATLAB.
echo on
% Turn on 15 digit display
format long
x = [0.1, 0.01, 0.001];
y = sin(x)./x
% These values illustrate the fact that the limit of
% sin(x)/x as x approaches 0 is 1.
echo off
If you use echo on in a script M-file, then MATLAB will also echo
the comments, so they will appear in the Command Window.

Matlab introduction

49

Structuring Script M-Files.


For the results of a script M-file to be reproducible, the
script should be self-contained, unaffected by other
variables that you might have defined elsewhere in the
MATLAB session, and uncorrupted by leftover graphics.
With this in mind, you can type the line clear all at the
beginning of the script, to ensure that previous
definitions of variables do not affect the results.
You can also include the close all command at the
beginning of a script M-file that creates graphics, to close
all graphics windows and start with a clean slate.

Matlab introduction

50

% Remove old variable definitions


clear all
% Remove old graphics windows
close all
% Display the command lines in the command window
echo on
% Turn on 15 digit display
format long
% Define the vector of values of the independent variable
x = [0.1, 0.01, 0.001];
% Compute the desired values
y = sin(x)./x
% These values illustrate the fact that the limit of
% sin(x)/x as x approaches 0 is equal to 1.
echo off

Matlab introduction

51

Sometimes you may need to type, either in the


Command Window or in an M-file, a command that is too
long to fit on one line. If so, when you get near the end of
a line you can type ... (that is, three successive periods)
followed by ENTER, and continue the command on the
next line. In the Command Window, you will not see a
command prompt on the new line.

Matlab introduction

52

Matlab introduction

53

Matlab introduction

54

Matlab introduction

55

Matlab introduction

56

Matlab introduction

57

Matlab introduction

58

Matlab introduction

59

Matlab introduction

60

Matlab introduction

61

Arrays of Linear Models

Matlab introduction

62

Matlab introduction

63

Matlab introduction

64

Matlab introduction

65

You might also like