Professional Documents
Culture Documents
Notes On How To Use MATLAB
Notes On How To Use MATLAB
Kesarkar,
M. Tech. TFE
tejaskesarkar.xlr8@gmail.com
+917208548978
A message for the learners
I myself did not gain knowledge about all of the things
mentioned in these notes at once. Whenever I wanted to
learn something new in MATLAB I simply googled and tried
out stuff. I learnt everything bit by bit. For you Ill suggest
that, dont go on swallowing all of the knowledge in these
notes at once. At first, you may only have a quick review of
what all things can be achieved in MATLAB. Do not go about
learning everything as you read it. When you are dealing
with your assignments or stuff, just look out for things you
need. That way you will not strain yourselves by learning too
much stuff together, stuff which you may not need at that
moment. Pick up only things that you may need at a certain
point time.
-Tejas
MATLAB Layout
Command window (Enter commands directly, view output, give
inputs)
Workspace (Holds all the existing variables created by you while
running a program)
Initializing variables
v_name = XY will assign memory for a variable named v_name and
the value of XY will be stored at that location
zeros function
This function is used for initializing an array of a given size which has
all elements equal to 0
By default, if the function is given only one argument, say n then it
will create a square array of size n x n
ones function
This function is used for initializing an array of a given size which has
all elements equal to 1
By default, if the function is given only one argument, say n then it
will create a square array of size n x n
zeros function
This function is used for initializing an array of a given size which has
all elements equal to 0
Important commands
clc : clears command window
switch expression
case value_1
.statements.
case value_2
.statements.
otherwise
.statements.
end
Expression value is compared with different case values. If expression value matches
with a case value , then the statements corresponding to that case block are executed. If
two case values are the same then priority is given to the case value which occurs first. If
an otherwise block is specified and if no case value matches the expression,the staements
in the otherwise block will be executed
Here the value of variable i will
loops
while(condition)
(while)
..statements to be repeated..
end
Loop will be continuously executed until condition is proven to be false
Logical AND & OR
Logical AND : ((a==b)&&(b~=c))
The final result will be true only if both
arguments are true else it will be false
Logical OR : ((a>b)||(a==c))
The final result will be true if either of the
arguments is true else it will be false
Loop control commands (continue,
break)
Statements in a loop appearing after continue will be
skipped and the next iteration will start
Occurrence of break will terminate the loop
numel function
Given the array as an argument, this function returns
back number of elements in an array
Using functions
Function is an operational tool which takes in some input, does some
operations on it and gives us desired output
A function having (i1,i2,.) as input variables and (o1,o2,.) as output
variables is given as :
function [o1,o2,] = function_name(i1,i2,.)
.statements 1..
.statements 2..
end
Function is to be written in a separate .m file and this file is to saved with a
name same as the function_name
Function can be called in the main program by using the function name
with the required parameters as [o1,o2,] = function_name(i1,i2,.) . For
this to happen, the function file should be saved in the directory in which
the main program exists
Function need not necessarily have any output variables. In case of no
output variables, the first line of function definition will be given as
follows :
function [] = function_name(i1,i2,.)
Using functions
Note : Names of variables used in the
main program are independent of the
names given to them in the function
Plotting points using plot
plot(x,y,_) where x,y are the coordinates of the point and _ is to replaced by
color and marker type (Note that default color is blue)
After every plotting operation
MATLAB wipes off the graphics
window. For retaining back the
plot history, hold on is to be
used after every plotting
operation
figure command opens a new
graphics window
axis ([x1 x2 y1 y2]) will limit the
display from lower left corner
(x1,y1) and top right corner
(x2,y2). Though this will be
overridden if a point lies
outside the limit
Plotting points using plot
Colors can be specified by [R
List of markers (default is point) :
G B] i.e. Red, Green, Blue + : plus
concentration
E.g. [0 0 0] : Black
o : circle
[1 1 1] : White * : asterisk
{0 1 0] : Bright green
. : point
x : cross
List of colors :
square or s : square
(default is blue)
diamond or d : diamond
b : blue [0 0 1]
y : yellow [1 1 0] ^ : upward pointing triangle
m : magenta [1 0 1] v : downward pointing triangle
c : cyan [0 1 1] > : rightward pointing triangle
r : red [1 0 0] < : leftward pointing triangle
g : green [0 1 0] pentagram or p : five pointed star
w : white [1 1 1] hexagram or h : six pointed star
k : black [0 0 0]
Plotting points using plot
Specifying marker color and type together. E.g. plot(x ,y, r+) ;
This will plot a red colored plus type of marker at (x,y)
Color can be explicitly stated. E.g.
plot(x, y, *, Color, b) or plot(x, y, *, Color, [0 0 1]) ; both
statements will plot a blue colored asterisk type marker at
(x,y)
Specifying marker size. E.g. plot(x, y, b*, MarkerSize,10) ;
This will plot a size 10 blue colored asterisk type marker at
(x,y). Default size is supposedly 1
Setting background color of plot. E.g. set(gca,Color,b) or
set(gca, Color, [0 0 1]) will give the plot a blue background
color. Here gca is axes handle
Multiple points can be plotted in a single operation. Color and
marker size for every point will be the same, though marker
type can be varied E.g.
plot(x1, y1, o, x2, y2, h, Color, r, MarkerSize, 30) ; This will
plot a circle type marker at (x1,y1) and hexagram type marker
at (x2,y2), both having the color r and marker size of 30
Plotting points using plot
Plotting points using plot
axis tight : this command shrinks the limits of the plot to the
smallest rectangle which can containg the coordinates of all
points in the plot
Plotting points using plot
Instead using PrinstScr or Snipping tool (which will
compromise the image quality), you can copy the plot to
clipboard for use by going to Edit > Copy Figure.
Plotting points using scatter
scatter(X, Y, area) : Here X,Y are arrays, necessarily of the same size, which
contain coordinates for the points to be plotted. And the area argument is for
controlling marker size. If area argument is not specified then MATLAB
supposedly assumes it to be 50. The default marker type is hollow circle.
You can have filled marker shapes
E.g. scatter(X,Y,100,filled) will produce solid circle type markers of area 100
Plotting points using scatter
You can use particular marker
type, edge color, face color and
line width for the edges of the
marker. The default marker
type is an hollow circle i.e.
having white face color. And
the default line width value for
the edge is 1. E.g.
scatter(X,Y,100, d,
MarkerEdgeColor, [0 1 0],
MarkerFaceColor, y,
Linewidth, 2)
This will produce diamond
shaped markers of area 100
which have green colored edges
and have yellow colored faces.
Also the line widths will be
twice the normal size.
Plotting lines using plot
plot(X, Y, Color, color_value) : This will plot lines
between adjacent points represented by the coordinate
arrays X, Y which have the specified color. Default color
is blue. E.g. only plot(X,Y) will produce blue lines, but
plot(X,Y, Color, r) and plot(X,Y, r) both will red
lines since the keyword Color is optional
xlabel(string) : for giving label to x-axis
ylabel(string) : for giving label to y-axis
title(string) : for giving title to the plot
Note : If the labeling and titling commands are placed
above the plotting commands then hold on should be
used just after the labeling commands inorder to retain
the labels.
Plotting lines using plot
Plotting lines using plot
set(gca,'FontSize',15,'fontWeight','bold, fontAngle, normal) : This will set the x
and y scale font to size 15, make it bold and set the font angle to normal
set(findall(gcf,'type','text'),'FontSize',15,'fontWeight', normal, fontAngle, italic) :
This will set the fonts of all labels to size 15 ,make it of normal width and set the
font angle to italic
Plotting lines using plot
You can have different line styles as follows
1) plot(X,Y, -) : Solid line (default)
2) plot(X,Y.--) : Dashed line
3) plot(X,Y, :) : Dotted line
4) plot(X,Y, -.) : Dash-dotted line
The widths of the lines can be adjusted. E.g. plot(X,Y,
LineWidth, 2) will plot lines of width twice the normal size
Also markers can be used for the endpoints of the lines. Markers
of different shape can be used. E.g. plot(X,Y, --or) will produce
dashed lines of red color with circles at endpoints
Also the marker size, edge color and face color can be adjusted.
E.g. plot(X,Y, :^g, MarkerEdgeColor, k, MarkerFaceColor,
[0 1 1], MarkerSize,2) will produce dotted lines of green color
with upward pointing triangles at endpoints. The markers will
have black edges and green faces. Also they will be of size 2.
legend(string 1, string 2,) will give names to the different lines
in the order in which they occur
Plotting lines using plot
grid on : turns the
background grid
on
Plotting lines using plot
grid minor :
displays refined
background grid
axis equal : will give
unity aspect ratio to
the plot which
means that the
background grid
displayed will
comprise of perfect
squares
2D
plots (contour)
contour(X,Y,Z,n) : Here for X, Y being 2D coordinate arrays and Z is the
third dimension (E.g. Temperature) we get n contour levels. Contour
levels are the number of states existing between the minimum and
maximum values of Z
[C,h] = contour(X,Y,Z,n) : will return contour information in arrays C
and h. Then using clabel(C,h) we get Z values along isolines
colorbar : displays a colored bar based on the maximum and minimum
value of Z
2D plots (contour)
2D plots (contourf)
contourf(X,Y,Z,n) : will produce a flooded contour
2D plots (surf)
surf(X,Y,Z) : Will give a 3D surface with height defined
by value of Z
In addition to the labels for x and y axes, use
zlabel(String) to give label to z axis
tic-toc
tic : Starts the stopwatch
toc : Outputs the time value in the stopwatch
A = toc; returns the stopwatch value to variable A
Reuse of tic command will restart the stopwatch
max, min
Max_a = max(a) returns maximum value in 1D array a
Max_b = max(max(b)) returns maximum value in 2D array b
Min_a = min(a) returns maximum value in 1D array a
Min_b = min(min(b)) returns maximum value in 2D array b
Thus the keywords max and min are to be restated n times where
n is the number of dimensions of the array. E.g. n = 1 for 1D array,
n = 2 for 2D array
Accessing specific row or column
b = a(i,:) : This will return row number i of array a into
b
c = a(:, j) : This will return column number j of array a
into c
num2str, round, ceil, floor
a = num2str(x) : converts numerical value into string
value
b = round(x) : rounds off to nearest integer
c = ceil(x) : gives smallest integer greater than or equal to
x
d = floor(x) : gives largest integer less than or equal to x
Skipping a block of statements
%{
..block of statements to be skipped
%}
Excel read and write
xlswrite(filename.xls, A, s, xlRange) : This will create an
filename.xls file which has the variable A stored in sheet number s,
in the range of cells specified by xlRange. The filename.xls file will
be created in the directory in which exists the main program
B = xlsread(filename.xls, s, xlRange) : This will extract the values
stored in range of cells specified by xlRange, in the sheet number s
of filename.xls into the variable B. The filename.xls should exist in
the same folder as does the main program
txt read and write
dlmwrite(filename.txt,A) : This create a filename.txt which has the variable
A stored in it. The filename.txt file will be created in the directory in which
exists the main program.
dlmwrite(filename.txt, A, delimiter_value) : The elements of A are
separated by the specified delimiter. The default delimiter is comma. The
different delimiters are
1) dlmwrite(filename.txt, A, , ) for commas
2) dlmwrite(filename.txt, A, ; ) for semicolons
3) dlmwrite(filename.txt, A, \t ) for tab spaces
The delimiter can be specified explicitly using the keyword delimiter
followed by the delimiter value. E.g. for commas as delimiter use
dlmwrite(filename.txt, A, delimiter, , )
dlmwrite(filename.txt, A, delimiter_value, R, C) : This will create a
filename.txt file which has the variable A stored with its entries offset by R
number of rows and C number of columns. The blank spaces are filled with
zeros. The row and column offset values can be specified explicitly using
keywords roffset and coffset respectively.
E.g. for a row offset of 1 and column offset of 2 use dlmread(filename.txt, A,
delimiter, delimiter_value, roffset, 1, coffset, 2)
dlmwrite(filename.txt, B, -append) : This will write the value of variable B
at the end of filename.txt
txt read and write
Here it may seem that two rows are not
separated. But there exists is an invisible
divider between entries of consecutive rows