Professional Documents
Culture Documents
Introduction To Matlab: Object-Oriented Programming. These Factors Make MATLAB An Excellent Tool For
Introduction To Matlab: Object-Oriented Programming. These Factors Make MATLAB An Excellent Tool For
1.Introduction
The component that is the heart of MATLAB is called the Command Window,
located in the center by default. Here you can give MATLAB commands typed at the
prompt >> . Unlike FORTRAN and other compiled computer languages, MATLAB is an
interpreted environment , you give a command, and MATLAB tries to execute it right
away before asking for another.
At the top left you can see the Current Folder. In general MATLAB is aware
only of files in the current folder and on its path, which can be customized. Commands
for working with the directory and path include cd, what, addpath, and editpath (or you
can choose “File/Set path. . . ” from the menus). You can add files to a directory on the
path and thereby add commands to MATLAB.
At the top right is the Workspace tab. The workspace shows you what variable
names are currently defined and some information about their contents. (At start-up it is,
naturally, empty.) This represents another break from compiled environments: variables
created in the workspace persist for you to examine and modify, even after code
execution stops.
Below the Workspace window is the Command History window. As you enter
commands, they are recorded here. This record persists across different MATLAB
sessions and commands or blocks of commands can be copied from here or saved to files,
packaged sets of capabilities that provide in-depth expertise on particular subject areas.
1.2 Help
Below we list the most important ways to use the MATLAB help facilities.
• Help Functions - By typing the command >> help ’function name’ in the Command
Window, an M-help file appears in the Command Window. This file contains a short
description of the function, the syntax, and other closely related help functions. This is
MATLAB’s most direct help facility, and you will often use this facility to quickly check
how a certain function works and which notation should be used. If more extensive
results are needed, try the command doc.
• Look for - By typing the command lookfor ’topic’ in the Command Window, you
can call up all help possibilities which contain the specific search word. You can use this
possibility to look for a function of which you do not remember the function name
exactly. In this manner, all related topics appear in the Command Window.
• Help Browser - You can use the ‘Help Browser’ to find and browse information about
Mathworks products. This help browser contains different ways to obtain the correct
information, like lists, a global index and a search function. You will especially use this
help facility if you are looking for a function of which you do not remember the name.
• Other help facilities - You can use product specific help facilities, have a look at
Mathworks’ demos by typing demos in the Command Window, consult the Technical
Support, look for documentation about other Mathworks products, have a look at a list or
other books, and take part in a MATLAB newsgroup. More information about these
topics can be found in the MATLAB Help Browser or on the site www.mathworks.com.
If you type in a valid expression and press Enter, MATLAB will immediately
execute it and return the result .
>> 2+2
ans =
4
>> sin(pi/2)
ans =
1
>> 1/0
Warning: Divide by zero.
ans =
Inf
>> exp(i*pi)
ans =
-1.0000 + 0.0000i
A special value is NaN, which stands for not a number. NaN is used to express
an undefined value.
For example,
>> Inf/Inf
ans =
NaN
(!) NaNs can be tricky. For example, two NaN values are unequal by definition.
>> 3*z
??? Undefined function or variable ’z’.
Observe that variables must have values before they can be used. When an
expression returns a single result that is not assigned to a variable, this result is assigned
to ans, which can then be used like any other variable.
>> atan(x)
ans =
1.0472
>> pi/ans
ans =
3
If you enter save myfile, all the variables in the workspace will be saved to a file
called myfile.mat in the current directory. You can also select the variables to be saved
by typing them after the filename argument. If you later enter load myfile, the saved
variables are returned to the workspace (overwriting any values with the same names).
If you highlight commands in the Command History window, right-click, and
select “Create M-File”, you can save the typed commands to a text file.
The heart and soul of MATLAB is linear algebra. In fact, MATLAB was originally
a contraction of “matrix laboratory.” More so than any other language, MATLAB
encourages and expects you to make heavy use of arrays, vectors, and matrices.
The simplest way to construct a small array is by enclosing its elements in square
brackets.
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
123
456
789
>> b = [0;1;0]
b=
0
1
0
>> size(A)
ans =
33
>> ndims(A)
ans =
2
>> size(b)
ans =
31
>> ndims(b)
ans =
2
Notice that there is really no such thing as a one-dimensional array in MATLAB. Even
vectors are technically two-dimensional, with a trivial dimension. Table 1 lists more
commands for obtaining information about an array.
Arrays can be built out of other arrays, as long as the sizes are compatible.
>> [A b]
ans =
1230
4561
7890
>> [A;b]
??? Error using ==> vertcat
All rows in the bracketed expression must have the same number of columns.
B=
125
346
An especially important array constructor is the colon operator.
>> 1:8
ans =
12345678
>> 0:2:10
ans =
0 2 4 6 8 10
The format is first:step:last. The result is always a row vector, or the empty matrix if
last< first .
One special array is the empty matrix, which is entered as [].
The colon is often a useful way to construct these indices. There are some special
syntaxes: end means the largest index in a dimension .
The arithmetic operators +,-,*,ˆ are interpreted in a matrix sense. When appropriate,
scalars are “expanded” to match a matrix. One consequence is that adding a scalar to a
square matrix is not the same as adding a scalar times the identity matrix.
>> A+A
ans =
246
8 10 12
14 16 18
>> ans-1
ans =
135
7 9 11
13 15 17
>> 3*B
ans =
369
9 12 18
>> A*b
ans =
2
5
8
>> B*A
ans =
30 36 42
61 74 87
>> Aˆ2
ans =
30 36 42
66 81 96
102 126 150
>>exp(A)
ans =
1.0e+03 *
0.0027 0.0074 0.0201
0.0546 0.1484 0.4034
1.0966 2.9810 8.1031
An M-file is a plain text file containing MATLAB commands and saved with the
filename extension .m. There are two types, scripts and functions. MATLAB comes
with a pretty good editor that is tightly integrated into the environment; start it by typing
edit with a file name. However, you are free to use any text editor.
An M-file should be saved in the path in order to be executed. The path is just a
list of directories (folders) in which MATLAB will look for files. Use editpath or menus
to see and change the path.
There is no need to compile either type of M-file, simply type in the name of the
file (without the extension) in order to run it. Changes that are saved to disk will be
included in the next call to the function or script. (You can alter this behavior with
mlock.)
One important type of statement in an M-file is a comment, which is indicated by a
percent sign %. Any text on the same line after a percent sign is ignored (unless %
appears as part of a string in quotes). Furthermore, the first contiguous block of
comments in an M-file serves as documentation for the file and will be typed out in the
command window if help is used on the file.
3.1 Scripts
The following script file will calculate the amount of melting and the amount remaining
after each day .
3.2 Functions
Functions are the main way to extend the capabilities of MATLAB. Compared to scripts,
they are much better at compartmentalizing tasks. Each function starts with a line such as
function [out1,out2] = myfun(in1,in2,in3)
The variables in1, etc. are input arguments, and out1 etc. are output arguments. You
can have as many as you like of each type (including zero) and call them whatever you
want. The name myfun should match the name of the disk file.
Here is a function that implements the quadratic formula.
One of the most important features of a function is its local workspace. Any
arguments or other variables created while the function executes are available only within
the function. Conversely, the variables available to the command line (the so-called base
workspace) are normally not visible to the function. If during the function execution,
other functions are called, each of those calls also sets up a private workspace. These
restrictions are called scoping, and they make it possible to write complex programs
without worrying about name clashes. The values of the input arguments are copies of the
original data, so any changes you make to them will not change anything outside the
function’s scope. In general, the only communication between a function and its caller is
through the input and output arguments.You can always see the variables defined in the
current workspace by typing who or whos.
3.3 Scripts versus Functions
There are more subtle differences between scripts and functions. A script can be
thought of as a keyboard macro: when you type the name of the script, all of the
commands contained in it are executed just as if you had typed these commands into the
command window. Thus, all variables created in the script are added to the workspace for
the current session. Furthermore, if any of the variables in the script file have the same
name as the ones in your current workspace, the values of those variables in the
workspace are changed by the actions in the script. This can be used to your advantage. It
can also cause unwanted side effects.
In contrast, function variables are local to the function. (The exception is that it's
possible to declare and use global variables, but that requires and explicit action by the
user.) The local scope of function variables gives you greater security and flexibility. The
only way (besides explicitly declared global variables) to get information into and out of
a function is through through the variables in the parameter lists.
The conditions for if statements may involve the relational operators or functions
such as isinf that return logical values. Numerical values can also be used, with nonzero
meaning true, but “if x˜=0” is better practice than “if x”.
Individual conditions can be combined using:
& (logical AND)
| (logical OR)
˜ (logical NOT)
The if/elseif construct is fine when only a few options are present. When a large
number of options are possible, it’s customary to use switch instead. For instance:
switch units
case ’length’
disp(’meters’)
case ’volume’
disp(’liters’)
case ’time’
disp(’seconds’)
otherwise
disp(’I give up’)
end
The switch expression can be a string or a number. The first matching case has its
commands executed. If otherwise is present, it gives a default option if no case matches.
In nested loops, continue statement passes control to the next iteration of the for
or while loop enclosing it. continue temporarily interrupts the execution of a program
loop, skipping any remaining statements in the body of the loop for the current pass.
The example below shows a continue loop that counts the lines of code in the file,
skipping all blank lines and comments. A continue statement is used to advance to the
next line without incrementing the count whenever a blank line or comment line is
encountered .
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) | strncmp(line,'%',1)
continue
end
count = count + 1;
end
disp(sprintf('%d lines',count));
Try and catch blocks allow you to override the default error behavior for a set of
program statements. If any statement in a try block generates an error, program control
goes immediately to the catch block, which contains your error handling statements.
The example below shows a try/catch block within a function that multiplies two
matrices. If a statement in the try segment of the block fails, control passes to the catch
segment. In this case, the catch statements check the error message that was issued
(returned by lasterr) and respond appropriately.
try
X=A*B
catch
errmsg = lasterr;
if(strfind(errmsg, 'Inner matrix dimensions'))
disp('** Wrong dimensions for matrix multiply')
end
Return statement terminates the current sequence of commands and returns control to
the invoking function or to the keyboard. return is also used to terminate keyboard mode.
A called function normally transfers control to the function that invoked it when it
reaches the end of the function. You can insert a return statement within the called
function to force an early termination and to transfer control to the invoking function.
return causes a normal return to the invoking function or to the keyboard
In the following example return is used to handle the case when the matrix element
is greater than 5 .
for i=1:9
if a(i)>5
return
elseif a(i)<5
disp 'OK'
end
end
5. Exercises
for 0 ≤ x ≤ 10 .
4 .Give a MATLAB expression that uses only a single matrix multiplication with B
to obtain
(a) the sum of columns 5 and 7 of B
(b) the last row of B
(c) a version of B with rows 2 and 3 swapped .
5. Given the array A=[2 8 4+i 5; 0 -i -1 4; 3 -1 3 -1], explain the results of each of the
following commands:
a. A’
b. A.’
c. A(:,[1:3])
d. A([1 3],[3 2]
e. [A;A(end,:)]
f. A(:,[2 4 1 3])
g. sum(A)
h. sum(A.’)
i. [A;sum(A)]
6.What is the greatest value of n that can be used in the sum
7.Given the matrix A = [1:3; 4:6; 7:9] , compute the sum of all the elements of A (use
the sum function ) .
11.Write a function that will accept the integer n as input and return the nth Fibonacci
number .
where s = (a + b + c)=2. Write a Matlab function that will accept the values a, b and c as
inputs and return the value of A .
14. Write a function that will find the solution of the equation sin x = 2x – 2 .
18.Count the number of primes less than 100 and add them up , without using loops .
19. Solve the diferential equation
where α =0.2 and β=0.5 .
20.Write a script that takes as input an integer n and creates the n x n matrix A with (i;j)th
component given by A(i;j) = sin(1/(i+j-1)) .