You are on page 1of 62

By Tejas M.

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

clear v : frees the memory occupied by the variable v

clear all : frees the memory occupied by all variables

Ctrl + C : Terminate program while it is being executed


Math operations (+,-,/,*)
+ : addition
- : subtraction
/ : division
* : multiplication
Math operations (^,exp,log,log10)
^ : power
exp(x) : exponetial raise to power x
log(x) : natural logarithm of x
log10(x) : logarithm to the base 10 x
Trignometric functions
sin(x) : sine asin(x) : sine inverse
cos(x) : cosine acos(x) : cosine inverse
tan(x) : tangent atan(x) : tangent inverse
csc(x) : cosecant acsc(x) : cosecant inverse
sec(x) : secant asec(x) : secant inverse
cot(x) : cotangent acot(x) : cotangent inverse
Hyberbolic functions
sinh(x) : hyperbolic sine asinh(x) : hyperbolic sine inverse
cosh(x) : hyperbolic cosine acosh(x) : hyperbolic cosine inverse
tanh(x) : hyperbolic tangent atanh(x) : hyperbolic tangent inverse
csch(x) : hyperbolic cosecant acsch(x) : hyperbolic cosecant inverse
sech(x) : hyperbolic secant asech(x) : hyperbolic secant inverse
coth(x) : hyperbolic cotangent acoth(x) : hyperbolic cotangent
inverse
Matrix algebra
det(a) : determinant of a square matrix a
inv(a) : inverse of a non-singular square matrix a
Matrix algebra
Accessing elements of an array, X(i,j) : first index will denote the
row number, second index will denote the column number
If matrix is a row matrix then only column number can be
mentioned as argument
If matrix is a column matrix then only row number can be
mentioned as argument
Matrix algebra
Add, subtract, multiply matrices as simple variables
Creating programs using Editor
format for saving of files ____.m
Run programs using Run button
Anything written on a line after % will not be executed
disp() : Used for printing messages and values of variables
Creating programs using Editor
input() : used to assign values of variables by user. For string type of inputs,
enter string within single inverted commas
fprintf(string,variable_names,) : Used to print strings
Use \n for going to next line
Use %d for integer type and %f for floating point type, %s for string type
variables
%d, %f and %s will be replaced by the variables specified after the string
remainder function
rem(x,y) : returns the remainder after division of x by
y
Conditional statements (different
types of conditions)
(a==b) : a is equal to b
(a~=b) : a is not equal to b
(a<b) : a is less than b
(a>b) : a is greater than b
(a<=b) : a is less than or equal to b
(a>=b) : a is greater than or equal to b
Arguments need not be single variables. They can be
expressions. E.g. (a<(b*c)) will mean a is less than the
product of b and c
Conditional statements (if-elseif-
else-end)
if(condition 1)
.statements
end
if(condition 1)
.statements.
else
..statements.
end
if(condition 1)
.statements
elseif(condition 2)
statements
end
The execution goes from top to bottom. If first if condition is true the statements in the first
block are executed and the execution will come to the end statement. If the first if condition is
false and an elseif condition is present there can happen two things. If this elseif condition is
true the statements in its block are executed and the execution goes to the end statement. If that
elseif condition is false then the next elseif condition (if present) is checked. If all the
conditions are proven to be false then the statements in the else block (if present) are executed.
Conditional statements (switch-case-
otherwise-end)
switch expression
case value_1
.statements.
case value_2
.statements.
end

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

Using loops (for)


vary from start_value to
end_value with step_value as
the increment/decrement
between two successive values of
for i = start_value : step_value : end_value i
statements to be repeated.. Note : Default step value is 1. Also I
cannot take zero or negative
end values
Using

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

Here the seemingly blank spaces actually


have zero values
txt read and write
C = dlmread(filename.txt) : This will write the value stored in
filename.txt into the variable C. The filename.txt should exist in the
same folder as does the main program
C = dlmread(filename.txt, delimiter_value) : This will write the
values stored in filename.txt into the variable C. The elements in
filename.txt are separated by the specified delimiter
C = dlmread(filename.txt, delimiter, R, C) : This will write the values
stored in filename.txt into the variable C, starting with a row offset R
and column offset C. That the reading of values will start from the
element at (R+1,C+1)
C = dlmread(filename.txt, delimiter, range) : This will write the
values stored in filename.txt into the variable C for the range specified.
Range can be specified in two ways E.g.
1) C = dlmread(filename.txt, delimiter, [R1 C1 R2 C2]) : Here R1, C1
are the row and column offset values for the start point (top left
element) of the range and R2,C2 are the row and column offset values
for the end point (bottom right element)of the range. Therefore the
range is from element at (R1+1,C1+1) to the (R2+1,C2+1)
2) C = dlmread(filename.txt, delimiter, A1..C4) : Here the range is
specified in the excel numbering sense. Thus for A1..C3 the values
stored from element at (1,1) to element at (4,3) will be written into C
txt read and write
txt read and write
sprintf
A = sprintf(..%d.%f.., a, b) : will create a string
variable A with the values of a and b inserted into the string
quoted by the single inverted commas
concatenation of strings
A = strcat(string_1, string_2,.) will create a string
variable A with the value string_1 string 2 .. i.e. it will
create a string A which is an addition of all the strings
concatenation of strings
A = cat(dim,a,b) : This will join
the arrays a and b along the
dimension specified by dim. E.g.
dim = 1 will join a and b along
the rows; dim = 2 will join a and
b along the columns; dim = 3 will
create a 3D array in which a will
be placed on the first level and b
on the second
error
error(string) : This will display the message given by
string and will terminate the program i.e nothing after
error() is executed
Keep learning more stuff. You may
add what you learn to the end of
these notes for your reference.
-Tejas

You might also like