Notes Vol - 6 - MATLAB
Notes Vol - 6 - MATLAB
This tutorial gives you aggressively a gentle introduction of MATLAB programming language.
It is designed to give students fluency in MATLAB programming language. Problem-based
MATLAB examples have been given in simple and easy way to make your learning fast and
effective.
Prerequisites
We assume you have a little knowledge of any computer programming and understand concepts
like variables, constants, expression, statements, etc. If you have done programming in any other
high-level programming language like C, C++ or Java, then it will be very much beneficial and
learning MATLAB will be like a fun for you.
MATLAB – Overview
MATLAB(matrix laboratory) is a fourth-generation high-level programming language and
interactive environment for numerical computation, visualization and programming.
It has numerous built-in commands and math functions that help you in mathematical
calculations, generating plots and performing numerical methods.
Features of MATLAB
Following are the basic features of MATLAB:
Uses of MATLAB
MATLAB is widely used as a computational tool in science and engineering encompassing the
fields of physics, chemistry, math and all engineering streams. It is used in a range of
applications including:
MATLAB – Environment
Try it Option Online
You really do not need to set up your own environment to start learning MATLAB/Octave
programming language. Reason is very simple, we already have set up the Octave environment
online, so that you can execute all the available examples online at the same time when you are
doing your theory work. This gives you confidence in what you are reading and to check the
result with different options. Feel free to modify any example and execute it online.
Try following example using Try it option available at the top right corner of the below sample
code box:
x = [1 2 3 4 5 6 7 8 9 10];
y1 = [.16 .08 .04 .02 .013 .007 .004 .002 .001 .0008 ];
y2 = [.16 .07 .03 .01 .008 .003 .0008 .0003 .00007 .00002 ];
semilogy(x,y1,'-bo;y1;',x,y2,'-kx;y2;');
title('Plot title');
xlabel('X Axis');
ylabel('Y Axis');
print -deps graph.eps
For most of the examples given in this tutorial, you will find Try it option, so just make use of it
and enjoy your learning.
MathWorks provides the licensed product, a trial version and a student version as well. You need
to log into the site and wait a little for their approval.
Once you get the download link, as I said, it is a matter of few clicks:
Current Folder - This panel allows you to access your project folders and files.
Command Window - This is the main area where you enter commands at the command
line, indicated by the command prompt (>>).
Workspace - The workspace shows all the variables you create and/or import from files.
Command History - This panels shows or rerun commands that you entered at the
command line.
Set up GNU Octave
If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly
download latest version from Download GNU Octave. You can check given installation
instruction for your machine.
MATLAB is an interpreted environment. In other words, you give a command and MATLAB
executes it right away.
Hands on Practice
Type a valid expression, for example,
5+5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is:
ans = 10
ans = 9
Another example,
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is:
ans = 1
Another example,
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is:
ans = Inf
warning: division by zero
Another example,
732 * 20.3
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is:
ans = 1.4860e+04
MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf
for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'.
For example,
x = 3;
y=x+5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is:
y= 8
Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
You can also write a block of comments using the block comment operators % { and % }.
The MATLAB editor includes tools and context menu items to help you add, remove, or change
the format of comments.
Operator Purpose
+ Plus; addition operator.
- Minus; subtraction operator.
* Scalar and matrix multiplication operator.
.* Array multiplication operator.
^ Scalar and matrix exponentiation operator.
.^ Array exponentiation operator.
\ Left-division operator.
/ Right-division operator.
.\ Array left-division operator.
./ Array right-division operator.
Colon; generates regularly spaced elements and represents an entire row
:
or column.
Parentheses; encloses function arguments and array indices; overrides
()
precedence.
[] Brackets; enclosures array elements.
. Decimal point.
… Ellipsis; line-continuation operator
, Comma; separates statements and elements in a row
; Semicolon; separates columns and suppresses display.
% Percent sign; designates a comment and specifies formatting.
_ Quote sign and transpose operator.
._ Nonconjugated transpose operator.
= Assignment operator.
Name Meaning
ans Most recent answer.
eps Accuracy of floating-point precision.
i,j The imaginary unit √-1.
Inf Infinity.
NaN Undefined numerical result (not a number).
pi The number π
Naming Variables
Variable names consist of a letter followed by any number of letters, digits or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters, where N
is given by the function namelengthmax.
For example,
save myfile
You can reload the file anytime later using the load command.
load myfile
MATLAB – Variables
In MATLAB environment, every variable is an array or matrix.
MATLAB will execute the above statement and return the following result:
x=
3
It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another
example,
MATLAB will execute the above statement and return the following result:
x=
4
Once a variable is entered into the system, you can refer to it later.
Variables must have values before they are used.
When an expression returns a result that is not assigned to any variable, the system
assigns it to a variable named ans, which can be used later.
For example,
sqrt(78)
MATLAB will execute the above statement and return the following result:
ans =
8.8318
9876/ans
MATLAB will execute the above statement and return the following result:
ans =
1.1182e+03
MATLAB will execute the above statement and return the following result:
y=
441.8400
Multiple Assignments
You can have multiple assignments on the same line. For example,
a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result:
c=
14
who
MATLAB will execute the above statement and return the following result:
whos
MATLAB will execute the above statement and return the following result:
a 1x1 8 double
ans 1x1 8 double
b 1x1 8 double
c 1x1 8 double
x 1x1 8 double
y 1x1 8 double
The clear command deletes all (or the specified) variable(s) from the memory.
Long Assignments
Long assignments can be extended to another line by using an ellipses (...). For example,
initial_velocity = 0;
acceleration = 9.8;
time = 20;
final_velocity = initial_velocity ...
+ acceleration * time
MATLAB will execute the above statement and return the following result:
final_velocity =
196
However, if you want more precision, you need to use the format command.
For example:
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result:
x=
17.231981640639408
Another example,
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result:
x=
17.2320
The format bank command rounds numbers to two decimal places. For example,
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result:
weekly_wage =
1064.70
The format short e command allows displaying in exponential form with four decimal places
plus the exponent.
For example,
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result:
ans =
2.2922e+01
The format long e command allows displaying in exponential form with four decimal places
plus the exponent. For example,
format long e
x = pi
MATLAB will execute the above statement and return the following result:
x=
3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a calculation. For
example,
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result:
ans =
2063/90
Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors:
Row vectors
Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or
comma to delimit the elements.
For example,
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result:
r=
Columns 1 through 4
7 8 9 10
Column 5
11
Another example,
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result:
res =
Columns 1 through 4
9 11 13 15
Column 5
17
Column vectors are created by enclosing the set of elements in square brackets, using
semicolon(;) to delimit the elements.
MATLAB will execute the above statement and return the following result:
c=
7
8
9
10
11
Creating Matrices
A matrix is a two-dimensional array of numbers.
m = [1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result:
m=
1 2 3
4 5 6
7 8 9
MATLAB – Commands
MATLAB is an interactive program for numerical computation and data visualization. You can
enter a command by typing it at the MATLAB prompt '>>' on the Command Window.
In this section, we will provide lists of commonly used general MATLAB commands.
Command Purpose
clc Clears command window.
clear Removes variables from memory.
exist Checks for existence of file or variable.
global Declares variables to be global.
help Searches for a help topic.
lookfor Searches help entries for a keyword.
quit Stops MATLAB.
who Lists current variables.
whos Lists current variables (long display).
Commands for Working with the System
MATLAB provides various useful commands for working with the system, like saving the
current work in the workspace as a file and loading the file later.
It also provides various commands for other system-related activities like, displaying date, listing
files in the directory, displaying current directory, etc.
Command Purpose
cd Changes current directory.
date Displays current date.
delete Deletes a file.
diary Switches on/off diary file recording.
dir Lists all files in current directory.
load Loads workspace variables from a file.
path Displays search path.
pwd Displays current directory.
save Saves workspace variables in a file.
type Displays contents of a file.
what Lists all MATLAB files in the current directory.
wklread Reads .wk1 spreadsheet file.
Command Purpose
disp Displays contents of an array or string.
fscanf Read formatted data from a file.
format Controls screen-display format.
fprintf Performs formatted writes to screen or file.
input Displays prompts and waits for input.
; Suppresses screen printing.
The fscanf and fprintf commands behave like C scanf and printf functions. They support the following
format codes:
Format Code Purpose
%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.
%e Format as a floating point value in scientific notation.
%g Format in the most compact form: %f or %e.
\n Insert a new line in the output string.
\t Insert a tab in the output string.
The format function has the following forms used for numeric display:
Command Purpose
cat Concatenates arrays.
find Finds indices of nonzero elements.
length Computes number of elements.
linspace Creates regularly spaced vector.
logspace Creates logarithmically spaced vector.
max Returns largest element.
min Returns smallest element.
prod Product of each column.
reshape Changes size.
size Computes array size.
sort Sorts each column.
sum Sums each column.
eye Creates an identity matrix.
ones Creates an array of ones.
zeros Creates an array of zeros.
cross Computes matrix cross products.
dot Computes matrix dot products.
det Computes determinant of an array.
inv Computes inverse of a matrix.
pinv Computes pseudoinverse of a matrix.
rank Computes rank of a matrix.
rref Computes reduced row echelon form.
cell Creates cell array.
celldisp Displays cell array.
cellplot Displays graphical representation of cell array.
num2cell Converts numeric array to cell array.
deal Matches input and output lists.
iscell Identifies cell array.
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows some of the
commonly used commands for plotting:
Command Purpose
axis Sets axis limits.
fplot Intelligent plotting of functions.
grid Displays gridlines.
plot Generates xy plot.
print Prints plot or saves plot to a file.
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel Adds text label to y-axis.
axes Creates axes objects.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
gtext Enables label placement by mouse.
hold Freezes current plot.
legend Legend placement by mouse.
refresh Redraws current figure window.
set Specifies properties of objects such as axes.
subplot Creates plots in subwindows.
text Places string in figure.
bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
Creates semilog plot. (logarithmic
semilogx
abscissa).
Creates semilog plot. (logarithmic
semilogy
ordinate).
stairs Creates stairs plot.
stem Creates stem plot.
MATLAB M-Files
So far, we have used MATLAB environment as a calculator. However, MATLAB is also a
powerful programming language, as well as an interactive computational environment.
In previous chapters, you have learned how to enter commands from the MATLAB command
prompt. MATLAB also allows you to write series of commands into a file and execute the file as
complete unit, like writing a function and calling it.
The M Files
MATLAB allows writing two kinds of program files:
Scripts - script files are program files with .m extension. In these files, you write series
of commands, which you want to execute together. Scripts do not accept inputs and do
not return any outputs. They operate on data in the workspace.
Functions - functions files are also program files with .m extension. Functions can
accept inputs and return outputs. Internal variables are local to the function.
You can use the MATLAB Editor or any other text editor to create your .m files. In this section,
we will discuss the script files. A script file contains multiple sequential lines of MATLAB
commands and function calls. You can run a script by typing its name at the command line.
edit
Or
edit <filename>
The above command will create the file in default MATLAB directory. If you want to store all
program files in a specific folder, then you will have to provide the entire path.
Let us create a folder named progs. Type the following commands at the command prompt(>>):
If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes.
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and
creates a file named Untitled. You can name and save the file after typing the code.
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
Total = NoOfStudents + TeachingStaff ...
+ NonTeachingStaff;
disp(Total);
After creating and saving the file, you can run it in two ways:
Clicking the Run button on the editor window or
Just typing the filename (without extension) in the command prompt: >> prog1
6170
Example
Create a script file, and type the following code:
a = 5; b = 7;
c=a+b
d = c + sin(b)
e=5*d
f = exp(-d)
When the above code is compiled and executed, it produces the following result:
c=
12
d=
12.6570
e=
63.2849
f=
3.1852e-06
If the variable already exists, then MATLAB replaces the original content with new content and
allocates new storage space, where necessary.
For example,
Total = 42
The above statement creates a 1-by-1 matrix named 'Total' and stores the value 42 in it.
Example
Create a script file with the following code:
When the above code is compiled and executed, it produces the following result:
str =
Hello World!
n=
2345
d=
2345
un =
790
rn =
5.6789e+03
c=
5679
Function Purpose
char Convert to character array (string)
int2str Convert integer data to string
mat2str Convert matrix to string
num2str Convert number to string
str2double Convert string to double-precision value
str2num Convert string to number
native2unicode Convert numeric bytes to Unicode characters
unicode2native Convert Unicode characters to numeric bytes
base2dec Convert base N number string to decimal number
bin2dec Convert binary number string to decimal number
dec2base Convert decimal to base N number in string
dec2bin Convert decimal to binary number in string
dec2hex Convert decimal to hexadecimal number in string
hex2dec Convert hexadecimal number string to decimal number
hex2num Convert hexadecimal number string to double-precision number
num2hex Convert singles and doubles to IEEE hexadecimal strings
cell2mat Convert cell array to numeric array
cell2struct Convert cell array to structure array
cellstr Create cell array of strings from character array
mat2cell Convert array to cell array with potentially different sized cells
num2cell Convert array to cell array with consistently sized cells
struct2cell Convert structure to cell array
Following table provides the functions for determining the data type of a variable:
Function Purpose
is Detect state
isa Determine if input is object of specified class
iscell Determine whether input is cell array
iscellstr Determine whether input is cell array of strings
ischar Determine whether item is character array
isfield Determine whether input is structure array field
isfloat Determine if input is floating-point array
ishghandle True for Handle Graphics object handles
isinteger Determine if input is integer array
isjava Determine if input is Java object
islogical Determine if input is logical array
isnumeric Determine if input is numeric array
isobject Determine if input is MATLAB object
isreal Check if input is real array
isscalar Determine whether input is scalar
isstr Determine whether input is character array
isstruct Determine whether input is structure array
isvector Determine whether input is vector
class Determine class of object
validateattributes Check validity of array
whos List variables in workspace, with sizes and types
Example
Create a script file with the following code:
x=3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
When you run the file, it produces the following result:
x=
3
ans =
0
ans =
1
ans =
1
ans =
1
ans =
1
x=
23.5400
ans =
0
ans =
1
ans =
1
ans =
1
ans =
1
x=
1 2 3
ans =
0
ans =
1
ans =
1
ans =
0
x=
Hello
ans =
0
ans =
0
ans =
1
ans =
0
ans =
0