0% found this document useful (0 votes)
21 views

Introduction To Matlab Handout

Introduction to Matlab

Uploaded by

graeme
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Introduction To Matlab Handout

Introduction to Matlab

Uploaded by

graeme
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Lecture 2 – Introduction to Matlab

2.1. Starting Matlab:


Logon to your computer and start Matlab by double-clicking on the icon on the desktop (if any)
or by using the Start>Programs menu (Start menu → All Program → MATLAB → MATLAB
R2010b).

The Matlab Desktop window will appear on the screen, like the following.

Current folder

Workspace

Command Window

Command
History Window

12
The desktop consists of several sub-windows. The most important ones are:

• Command Window is used to do calculations, entering variables and running built-in


and your own functions. The prompt >> is displayed in the Command window, and when
the Command window is active, a blinking cursor should appear at the right of the
prompt

• Workspace consists of the set of variables (arrays) created during the current Matlab
session and stored in memory.

• Command History logs commands entered in the Command Window. You can use this
window to view previously run statements, and copy and execute selected statements.

The Command Window, Command History and Workspace can be cleared using Edit → Clear
Command Window, Clear Command History and Clear Workspace, respectively.

2.2. Using Online Help

• Information about any command, M-file, or operation is available by typing in the Command
Window:

>> help command

Matlab will display help for that function. For example, type

>> help sqrt (sqrt is an M-file function that represent square root)

Notice that the “>>” is the Matlab command prompt; so you actually type in only help
sqrt.

Warning: function names are capitalized in help text solely to aid readability, but in use,
functions are called using lower characters. For example: type sqrt(5) and SQRT(5)

• If you don’t know the command you can view a listing of primary help topics simply by
typing:
>> help

• You can also use the MATLAB Help window from the Help menu (or simply by pressing
F1 or clicking on the question mark on the menu bar). Another way of accessing the Help
Window is to type helpwin in the Command Window.

13
• It is also possible to search for function based on keyword by using the lookfor command.
For example, you want to know how to inverse a matrix: first type help inverse (what
happen?), then type lookfor inverse.

2.3. Basic Operations and Mathematical Functions:

• Basic operators: +, -, *, /, ^ (“exponentiation” or “to the power of”)


Example: try 3^2

• Some useful mathematical functions are:

exp Exponential
log Natural logarithm (note that is not represented as ln)
log10 Base 10 logarithm
sqrt Square root

cos Cosine
cosh Hyperbolic cosine
sine Sine
sinh Hyperbolic sine
tan Tangent
tanh Hyperbolic tangent
acos Inverse cosine
acosh Inverse hyperbolic cosine
acot Inverse cotangent
acoth Inverse hyperbolic cotangent
asin Inverse sine
asinth Inverse hyperbolic sine
atan Inverse tangent

Example: calculate cos(π / 6) 2 sin(3π / 8) (note that π is written as pi)


Answer: 0.6929

2.4. Names
There are three types of names in MATLAB:
• Variable names
• Reserved words
• Function names

14
Variable Names:

• Variable names are case sensitive

• Variable names can contain up to 63 characters

• Variable name must start with a letter, followed by any number of letters, digits, or
underscores.
– Punctuation characters are not allowed since many have special meaning to
MATLAB

• When MATLAB performs a calculation, it does so using the values it knows at the time the
requested command is evaluated

• MATLAB has some special variables:

Special Variables Description


ans default variable name for results
beep make sound
pi mathematical constant
smallest number that can be subtracted from 0 to
eps
make a negative
inf infinity
NaN not a number
i (or) j imaginary number
realmin,
smallest & largest positive real numbers
realmax
bitmax largest positive integer
nargin,
number of function in (or) out variables
nargout
varargin variable number of function in arg’s
varaout variable number of function out arg’s

Reserved Words:

• MATLAB has a set of reserved words

• The list of reserved words can be obtained by typing iskeyword in the Command Window

15
• You cannot change the meaning of a reserved word
e.g. you cannot use a reserved word as a variable or function name (try if = 5)

• List of reserved words:


break else global return
case elseif if spmd
catch end otherwise switch
classdef for parfor try
continue function persistent while

Function Names:

• Naming rules for functions are similar to that of variables

• The functions are stored as files with the same name as the function and the .m extension

• Two types of functions:


• User defined function (function created by the user)
• Built-in MATLAB function (e.g. sin, log,…)

• Special remarks about built-in MATLAB function:


• In the Command Window (and in M-files) always written in lower case
[be careful: in the help display their description is shown in capital letter!](Try help log)
• Function names can be overloaded (i.e. can be used to define variables)
Not recommended at all!

2.5. Commands

• The equality sign is used to assign values to variables:

Example: Consider the following mass balance:


Accumulation = Input – Output + Reaction
Where Input = 200, Output = 250, and Reaction = 60
Calculate the accumulation assigning values to the different variables

Type
» Input = 200
» Output = 250
» Reaction = 60
» Accumulation = Input – Output + Reaction

16
You can see the variables Input, Output, Reaction and Accumulation, and their types and
sizes on the Workspace window, and can see the commands on the Command History
window.

• If we write a semicolon at the end of the line, the answer is not displayed.

Example: type » Input = 200; and compare with what happened in the previous
exercise.

• When MATLAB performs a calculation, it does so using the values it knows at the time the
requested command is evaluated.

Example: type » Input = 300


» Accumulation
The result for accumulation is still the result calculated previously for Input = 200

• MATLAB remembers the commands and the values of the variables (they reside in the
Matlab workspace). To see the name available in the workspace use the command who. Try
it. To see a list of variable together with information about their size, density, etc, use the
command whos.

• Previous commands can be recalled by using the Cursor keys, ↑, ↓,←,→. Press the ↑ key
and see what happens. Pressing the Return key with the cursor anywhere in the command
tells MATLAB to process it. The Escape key erases the current command at the prompt.

2.6. Comments and Punctuation

• Use of semicolons (;): answer not displayed

• Use of percent sign (%): all text after % is considered as comment statement

Example: » Input = 200 % Inflow in the reactor

• Multiple commands can be placed on one line if they are separated by commas or
semicolons.

Example:
» Input=200;Output=250;Reaction=60;Accumulation=Input–
Output+Reaction

• If an expression is very long, it can be written over two lines by using three periods (…)
Example: » Accumulation = Input – Output …
+ Reaction

17
2.7. The Command Window

• The command clear deletes variables from the MATLAB workspace. Using the command
clear alone deletes all the variables from the workspace.

Example: » who (look at the variables in the workspace)


» clear Input
» who (Input variable has disappeared)
» clear, who

• The clc command clears the Command Window and moves the cursor to the upper left
corner. The home command moves the cursor to upper left corner (but you can still see the
previous commands by scrolling the page up). The more command control the page output
in command window (press RETURN key to go to the next line, press the space bar to go to
the next page).

Example: » more on
» help which

(use more off to deactivate the more feature)

2.8. Characters and Strings

• Characters and Strings (i.e. group of characters) are entered using single quotes as delimiters

Example: >> A = ‘My favourite sport is ‘;


>> B = ‘Hockey‘;
>> C = ‘Soccer‘;

• A string is stored as an array of characters, starting with the index one. You can access
characters within the string by using the array name followed by the index in parenthesis:

Example: >> A(4)


>> A(2),A(4)
>> A(2);A(4) (here can you explain the results of this last line?)

• Matlab makes the difference between numeric array type (array of numbers) and char array
type (array of character and strings). From the example before the variable A, B and C are of
type char, whereas Input, Output, Reaction and Accumulation were of numeric type.

The type (or class) can be seen in the workspace. Another way to check whether it char or
numeric is to use the commands ischar or isnumeric. The ischar command will return
true (1) if the variable is of type char, otherwise it returns false (0). Similar for isnumeric.

Example: >> ischar(A)

18
>> isnumeric(A)

• Some functions accept only char types. For example the function strcat.

Example: >> strcat(‘Lab’,’1’) What happened?


>> strcat(1,2) What happened?

It might be useful to be able to convert a number between a numeric type to a char type (and
vice versa). To do so, use the functions num2str (numeric to string) and str2num.

Example: >> strcat(‘Lab’,num2str(1))

>> number = ‘2’;


>> 5 + number does it make sense? (don’t worry why now)
>> 5+str2num(number)does it make sense?

2.9. Vectors, Matrices

• Create row vector X containing elements specified.


Example: » m = [1 2 3 4 5 6]

• Create row vector X starting with first, counting by one, ending at or before last:
X = first:last
Example: >> m = [1:6]
>> m = [1:6.5]
>> m = [1.2:6]

• Create row vector X starting with first, counting by increment, ending at or before last:
X = first:increment:last

Example: create an array t that represents the time between 0 and 8 hours, with a 0.5 hr
increment.
» t = 0:0.5:8

• Create row vector X starting with first, ending at last, having n elements:
X = linspace(first, last, n)

Example: create an array t that represents the time between 0 and 8 hours, with 10 elements.
» t = linspace(0,8,10)

• Two or more arrays can be combined to form a new array:


Example: » a = 1:5, b=1:2:9
» c = [b a]

19
• To create column vector:
- separate the elements by a semicolon: » c = [1;2;3;4;5]
- or transpose a row vector (use ‘): » a = 1:5
» b = a’
• Creating matrices is as follows:

>> m = [1 2 3; 4 5 6]
m =
1 2 3
4 5 6

Elements of a row may be separated either by space or a comma, and the rows may be
separated by a semicolon or carriage return (i.e. new line). All rows must contain the same
number of columns.

2.10. M-file Script

• Instead of using the command window, the Matlab commands can be placed in files called
script files or simply M-files (must end with the extension ‘.m’).

• To create M-files, either choose New from the File menu and select M-File, or enter the
command in any other text editor.

• To execute the script M-file choose Run Script… from the File menu, or type the name of
the script file without the .m extension. Alternatively, you can just press F5.

Shortcut to Run
(alternative to F5)

20
Example 1 (Example1_2.m):

Enter the following instruction in the MATLAB editor, save it and run it:
Input = 200;
Output = 250;
Reaction = 60;
Accumulation = Input – Output + Reaction

• Useful commands when used in M-files:

disp(variable) Display results without identifying variable name


input Prompt user for input
pause Pause until user presses any keyboard key
pause(n) Pause for n seconds, then continue

If you want the user to enter a string, you can either enter the characters in single quotes (but not
very convenient) or better, use the following structure (note the ‘s’):
Name = input(‘Enter the user’s name: ‘, ‘s’)

For displaying the results of a calculation, you have several possibilities:


1) Just write Accumulation = Input – Output + Reaction (without semi
colon at the end), as in Example 1.
2) Use the disp function as follows:
disp([‘The accumulation is :’ num2str(Accumulation)])

Here you actually display an array of two strings (thus the presence of []). The first string is ‘The
accumulation is :’ and the second one is a string corresponding to the value of accumulation. The
function num2str convert a numerical format to a string format. This is necessary here because
you cannot mix types within one array. Check what happen if you would have typed:
disp([‘The accumulation is :’ Accumulation])

Example 2 (Example2_2.m):

Using Example 1, Input, Output and Reaction have to be entered by the user. Also, ask the user
to enter his/her name. Display the results using a sentence and display the name of the user as
well.
Username = input('Enter user name: ','s');
Input = input('Enter the inlet flow rate: ');
Output = input('Enter the outlet flow rate: ');
Reaction = input('Enter the reaction term: ');
Accumulation = Input - Output + Reaction;
disp(['name of user is ' Username])
disp(['Accumulation is ' num2str(Accumulation)])

21
• More on display format

You can get even more control of the display format if you use the function fprintf
(formatted print function).

The general form of the fprintf command contains two arguments, one a string and the
other a list of matrices:
fprintf(format-string, var, …)

For example, the following:


fprintf(‘The accumulation is %f g/day \n’, Accumulation)

yields: The accumulation is 470.000000 g/day

The % symbol indicates where the value of the variable (here “Accumulation” should be
placed). The % symbol is followed immediately by the formatting information (here f). The
various formats are shown in the table below:

Type Field Result


%f fixed-point, or decimal notation
%e exponential notation
%g whichever is shorter, %f or %e
%c character information
%s string of characters

The \n cause Matlab to start a new line. \n is called a linefeed (be careful it is a backshlash
(\) here, not a forward slash (/). There are other format commands as shown in the following
table:

Format Command Resulting Action


\n linefeed
\r carriage return (similar to linefeed)
\t tab
\b backspace

You can further control how the variables are displayed by using the optional width field and
precision field with the format command. The width field controls the minimum number of
characters to be printed. It must be a positive decimal integer. The precision field is
preceded by a period (.) and specifies the number of decimal places after the decimal point
for exponential and fixed-point types. For example:

fprintf(‘The accumulation is %5.2f g/day \n’, Accumulation)


yields: The accumulation is 470.00 g/day

fprintf(‘The accumulation is %5.2e g/day \n’, Accumulation)


yields: The accumulation is 4.70e+002 g/day

22
2.11. Graphics

• plot function. The plot function open a graphic window, called a Figure window, scales the
axes to fit the data, plots the points, and the connects the points with straight lines.

Example 3 (Example3_2.m): Plot of sin(x) for x between 0 and 2 π


x = linspace(0, 2*pi, 30);
y = sin(x);
plot(x,y)
title(‘sin x as a function of t’)

Example 4 (Example4_2.m): Plot several set of data in one graph:


x = linspace(0, 2*pi, 30);
y = sin(x);
z = cos(x);
plot(x,y,x,z)
title(‘sin x and cos x’)

This is equivalent to:


W = [y,z];
plot(x,W) (try modifying Example 4 by using plot(W,x))

• Add or remove grid: grid on or grid off (you can use only grid to toggle them)

• Horizontal and vertical axis can be labelled with the xlabel and ylabel functions,
respectively.
Example: » xlabel(‘Variable x’)
» ylabel(‘Variables y and z’)

• Add label or text string: text(x,y, ‘string’), where (x,y) represents the coordinates
of the center left edge string in unit taken from the plot axes.
Example: » text(2.5,0.7,’sin(x)’)
• Text formatting: for xlabel, ylabel and text you can format the text in many ways
(e.g. add symbols, Greek letters, subscript, superscript).
Example: » text(pi,0,' \leftarrow sin(\pi)','FontSize',18)
» xlabel(‘Distance x (m^2)’)

For more information about formatting: type helpwin, then type go to help (F1) → Index
and enter string in the Search for box, then select Text property in the list.

• Place text with the mouse: gtext


Example: » gtext(‘cos(x)’)

• Linestyles, Marker and Colors: you can select them according to the following table:

23
Symbol Color Symbol Marker Symbol Linestyle
b Blue . Point - Solid line
g Green o Circle : Dotted line
r Red x Cross -. Dash-dot line
c Cyan + Plus sign -- Dashed line
m Magenta * Asterisk
y Yellow s Square
k Black d Diamond
w White v Triangle (down)
^ Triangle (up)
< Triangle (left)
> Triangle (right)
p Pentagram
h Hexagram

Example: » plot(x,y,’b:p’,x,z,’m+’)

• Customizing plot axes:


Axis([xmin xmax ymin ymax]) Set the minimum and maximum values

axis auto Return the axis scaling to its automatic default

axis manual Freeze scaling at the current limits, so that if hold is


turned on, subsequent plots use the same axis limit

axis square Set the current plot to be a square rather than the
default rectangle
axis tight Set axis limits to the range of the data

axis off Turn off axis background, labeling, grid, box, and
tic mark

axis on Turn on axis background, labeling, grid, box, and


tic mark if they are enabled

• You can add new plots to an existing plot using the hold command.

• Sometimes it is important to plot graphs with different y-axis but compare them on the same
figure. MATLAB can do this using plotyy. plotyy(X1,Y1,X2,Y2) plots Y1 versus X1 with y-
axis labeling on the left and plots Y2 versus X2 with y-axis labeling on the right.

24
Example 5 (Example5_2.m):
x=0:0.1:3*pi;
y1=sin(x+0.5);
y2=10*sin(x-0.5);
[AX,L1,L2] = plotyy(x,y1,x,y2);
xlabel('x-axis')
ylabel(AX(1),'y1-axis')
ylabel(AX(2),'y2-axis')
set(L1,'LineStyle','--')
set(L2,'LineStyle',':')

In order to label the left and right y-axis, the plotyy command must return a handle. In the
above case, AX is the axis handle, L1 is the handle for the first curve, and L2 is the handle
for the second curve.

In addition to line style, you could specify the line colour (‘Color’), the linewidth
(‘LineWidth’) and the marker type (‘Marker’)

• Multiple figures: use the figure command. You can choose a specific Figure window to be
the active or current figure by selecting it with the mouse, or by using figure(n), where n
is the number of the window.

• Figure window can be deleted by closing them with a mouse or by using the close
command. To specify a particular window to delete, use close(n). Use close to delete
all figures.

• To clear the window, use the command clf. You can specify the window to clear by using
clf(n).

• One Figure window can hold more than one set of axes. The command subplot(m,n,p)
subdivises the current Figure window into an m-by-n matrix of plotting areas and chooses
the pth area to be active.

Example 6 (Example6_2.m):
close
clear
clc
x = linspace(0,2*pi,30);
y = sin(x);
z = cos(x);
a = tan(x);
subplot(2,2,1)
plot(x,y), axis([0 2*pi -1 1]), title('sin(x)')
subplot(2,2,2)
plot(x,z), axis([0 2*pi -1 1]), title('cos(x)')
subplot(2,2,3)
plot(x,a), axis([0 2*pi -20 20]), title('tan(x)')

25
• Use of legend: (use legend off to remove the legend)
Example: » clf
» plot(x,y,x,z)
» legend(‘sin(x)’,’cos(x)’)

2.12. Functions in Matlab

You have already used Matlab functions several times, for example, the function sin(x). Here the
name of the function is sin; it uses user input inside the parenthesis and returns a result.

2.12.1. Quick Ways to Define Simple Functions in Matlab

Matlab Function inline

A function can be defined by the inline Matlab function.

The basic syntax is simply: inline(expression)

Where expression is a string describing the function to be defined.

Example: generate the function f(x) = x lnx – x:

In Matlab: >> f = inline('x*log(x)-x')


f =
Inline function:
f(x) = x*log(x)-x

The function f can now be called as any other function. For example:

>> f(1)
ans =
-1

Note: when we define the function with the inline command, we used the variable x. Actually,
any other letters would work (try to use a lowercase letter, though). For example, try:
>> f = inline('w*log(w)-w');
>> f(1)

The function inline can accommodate functions with several independent variables. For example:
>> vector_norm = inline('sqrt(x^2+y^2)','x','y');
>> vector_norm(2,1)
ans =
2.2361

26
Anonymous Function

An anonymous function is a simple way of creating simple functions. It is an alternative to the


inline function and might have a somewhat simpler syntax.

The syntax is: fhandle = @(arglist) expression

Where fhandle is the name of the function, arglist is the list of independent variables and
expression represents the function.

Examples:
>> f = @(x) x*log(x)-x;
>> f(1)
ans =
-1

>> vector_norm = @(x,y) sqrt(x^2+y^2);


>> vector_norm(2,1)
ans =
2.2361

2.12.2. Matlab Functions

MATLAB functions are different from script files. A script file is a text file containing a list of
commands for MATLAB to execute. A function makes use of their local variables and accepts
input arguments. A function also gives you the return value, without creating the other variables
in your workspace.

Arguments: information passed to (input arguments or input parameters) and from (output
arguments or output parameters) a function.

Local variables: variables defined within the function. The function will use the input
argument(s) and the local variables to calculate the output result.

Structure of a function:

• the definition line


• the H1 (HELP 1) line and help section
• the function body

The definition line:


• the keyword function
• the output argument
• the function name
• the input argument

27
Example: function out = function_test(x)

Note: When the function will be called, it will the name under which the function has been saved
(the name of the M-file), which might be different from the function name in the definition
line. It is recommended that you use the same name for the function name in the definition
line and for the M-file.

The H1 line and help section:


The first comment lines (starting with %) immediately after the definition line are called
the Help 1 or H1 lines. These comments provide a summary of the description of the
function. When you type help followed by a command name, what is returned are the H1
lines.

Example: function out = function_test(x)


% This is the first function the students are writing.
% x is the input argument
% out is the output argument

Save this file as function_test.m.

Function body:
This is the section that contains the code for the function

Example:
We want to create a function that will convert a number x into a matrix [x x2 x3]
To the function_test add the line:
out = [x x^2 x^3]

From the Matlab command, enter: function_test(5)


Then type: help function_test
(note: if Matlab cannot recognize function_test, you will have to change the path)

You can have more than one output argument:


For example, modify function_test as follows:
function [out1 out2 out3] = function_test2(x)
% x is the input argument
% out1, out2 and out3 are the output arguments
out1 = x;
out2 = x^2;
out3 = x^3;
Save this file as function_test2.m
In the Matlab command type: [a b c] = function_test2(5)

You can have more than one input argument:


For example, modify function_test as follows:
function out = function_test3(x,y)
28
% x and y are the input arguments
% out is the output argument
out = [x^2 y^2 x*y];
Save this file as function_test3.m

In the Matlab command type: function_test3(5,6)

Now in the Matlab command try: a = [1 2 3];


b = [4 5 6];
function_test3(a,b)
what would you change in the function to make it work?

Variable Types
• Local variables:
Variables defined within the function. They do not appear in the workspace (i.e. they are
used only temporary while executing the function). It also means that their name does not
conflict the name in the global workspace.

Example: At the end of the function_test add the following line:


x = 10
then in the Matlab command window, enter the following:
x = 5;
function_test(5)
x

• Global variables:
A global variable is a variable that is passed on from the global workspace to the
function. Even if this variable is modified within the function, it will be modified
globally. A variable is declared global by using the keyword global.

Example: function [ ] = increment


% increment the global variable ‘counter’
global Counter
Counter = Counter + 1

In the command window, do the following:


global Counter
Counter = 2;
increment → Counter = 3
increment → Counter = 4

29
Determining the Number of Arguments
In case you have variable numbers of input and outputs in your function, it is very useful to
know the number of the arguments. To do so, use the following built-in functions:

nargin: determine the number of input arguments (note: if a variable number of input is possible,
nargin will return a negative number).

Try: nargin(‘function_test’)
nargin(‘function_test3’)

nargout: determine the number of output arguments.


Try: nargout(‘function_test’)
nargout(‘function_test2’)

If you want to create a function for which the number of input arguments can vary, instead of the
list of input arguments, you will use varargin in the definition line
Example: function out = my_average(varargin)
% my_average computes the arithmetic mean of a variable
% number of input arguments
Total = 0;
for i = 1:nargin
total = total + varargin{i};
end
out = Total/nargin;

30

You might also like