Introduction To Matlab Handout
Introduction To Matlab Handout
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:
• 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.
• Information about any command, M-file, or operation is available by typing in the Command
Window:
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.
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
2.4. Names
There are three types of names in MATLAB:
• Variable names
• Reserved words
• Function names
14
Variable Names:
• 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
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)
Function Names:
• The functions are stored as files with the same name as the function and the .m extension
2.5. Commands
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.
• 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.
• Use of percent sign (%): all text after % is considered as comment statement
• 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.
• 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
• Characters and Strings (i.e. group of characters) are entered using single quotes as delimiters
• 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:
• 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.
18
>> isnumeric(A)
• Some functions accept only char types. For example the function strcat.
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.
• 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)
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.
• 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
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’)
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, …)
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:
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:
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:
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.
• 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.
• 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+’)
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
• 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)’)
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.
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
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
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:
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.
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]
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.
• 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.
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’)
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