SlideShare a Scribd company logo
1 of 90
MATLAB – An Overview
INTRODUCTION
MATLAB (MATrix LABoratory)
 Deals with matrix manipulations
 Data defined : Array (in the form of row and column)
 Special purpose computer programme
 Perform engineering & scientific calculations with
graphical visualization
 Provide Integrated Development Environment (IDE) for
programming
 No. of predefined functions for computation and
visualization
Features and capabilities
MATLAB
(Programming Language)
Built-in Functions
User Defined Functions
Visualization
-2D Graphics
-3D Graphics
(With edit features)
GUI Tool
Toolboxes
(for dynamic simulations)
Simulink
SimpowerSystems
Fuzzy Logic
Neural Network
Communication
Control system
DSP
External Interface
(With C and FORTRAN)
Starting and Ending MATLAB
Starting:
Start / All Programs / MATLAB / R2010b / MATLAB
R2010b
Double clicking on MATLAB icon located on the
desktop
Ending:
Entering exit at MATLAB command prompt : >>exit
Entering quit at MATLAB command prompt: >>quit
Selecting Exit from file menu
Pressing Ctrl+Q at command prompt
Basic elements of Matlab’s desktop
 Command Windows: Where all commands and programs
are run. Write the command or program name and hit
Enter.
 Command History: Shows the last commands run on the
Command Windows. A command can be recovered clicking
twice
 Current directory: Shows the directory where work will
be done.
 Workspace: To see the variables in use and their
dimensions (if working with matrices)
 Help (can also be called from within the command
windows)
 Matlab Editor: All Matlab files must end with .m extension.
Command
Windows
Current
directory
Command
History
Basic elements of Matlab’s desktopBasic elements of Matlab’s desktop
Basic elements of Matlab’s desktop
Some comments about the command window
Commands can be retrieved with arrow up /
arrow down keys ↓↑
Moving around the command line is possible
with left / right arrow keys . Go to the→ ←
beginning of the line with Inicio (Home) and to
the end with Fin (End). Esc deletes the whole
line.
A program can be stopped with Ctrl+c
Matlab editor
 There can not be empty spaces in the name of
the Matlab files
 Use “main_” for the name of the main programs, for
example: main_curvature
 Write “;” at the end of a line If you don’t want that the
intermediate calculus is written in the window while the
program is running
 Write “%” at the beginning of a line to write a comment
in the program
 Write “…” at the end of a line if you are writing a very
long statement and you want to continue in the next line
MATLAB Editor Window
%Calculate volume of the cylinder
r=5; %Define radius of cylinder
h=10; %Define height of cylinder
volume=pi*r^2*h;
string=['The Volume of the cylinder
is',num2str(volume)];
disp(string);
Workspace
Temporary memory
All variables are cleared on ending/quit
MATALB
Save workspace : save <file name>
Particular value can be saved
Save <file name> <variable1 variable2 ….>
Load workspace: load <file name>
List of variables with details can generated
>>whos
>>who
Types of Files
.m files – Script files and function files (M-files)
.mat files – Binary data files (MAT-files)
.fig files – Figure windows
.mdl files – Model files (Simulink or
other toolboxes)
.mes files – MEX files
◦ Interface files write in C or FORTRAN
◦ Using mex function, mex compiles and link
source file into a shared library
Data input and output
 Saving to files and recovering data:
 Save <mat file_name> matrix1_name, matrix2_name
 Load <mat file_name> matrix1_name, matrix2_name
 save file_name matrix1_name –ascii (saves 8 figures after
the decimal point)
 save file_name matrix1_name –ascii –double (saves 16
figures after the decimal point)
Getting help
help command ( >>help )
lookfor command ( >>lookfor)
LOOKFOR Search all M-files for keyword.
Help Browser ( >>doc )
helpwin command ( >>helpwin )
Important Commands
cd – Display/ Change current working directory
clc – Clear command window
clear – Clear content of workspace
clf – Clear content of current figure window
close – Close current figure window
^c – Abort / terminate the execution of current
program/command
date – Current date as date string
demo – Runs the demo programs
dir – List files/folders in present directory
exit – End (quit) a MATLAB session
help – Display help text in command window
Important Commands
 load – Load saved workspace from working directory
 lookfor – Search all M-files for a particular command or
keyword
 path – Get/set MATLAB search path
 pwd – Gives present working directory
 quit – End a MATLAB session
 save – Saves current workspace variables in working
directory
 ver – Gives the MATLAB, SIMULINK and Toolboxes
version information
 who – Generate the list of variables available in the
current workspace
 whos – Generate the list of variables available in the
current workspace with their details (type, size, etc.)
Input/Output Commands
Input command
R=input(‘Enter the value of Resistance (in ohms): ’);
Output command
disp (variable name) or disp (‘Content of string’)
E.g.:- >>A=[1 2 3; 4 5 6];
>>disp(A);
>>disp(‘My Name is MATLAB’);
Display formatted string : fprintf (‘Text String’)
E.g.: fprintf(‘n Invalid data range.n Please enter new input.n’);
n : Newline; b: Backspace; t: Horizontal tab
f: Form feed; r: Carriage return; : Print backlash ()
’: Print apostrophe or single quote; %%: Print %
-- Continue…
 Display a variable with text
fprintf (‘…Text…. Formatting elements ….Text….’, variable name);
Formatting elements : %-4.2d
% = Start of format element
- = Flags
4 = field width
2 = Precision
d = conversion character
E.g.: fprintf (‘The value of pi is %2.3f displayed up to three decimal digits’, pi);
 Display more than one variable
 fprintf (‘…Text…. %f…. %g… %c….’, variable1, variable 2, variable3 );
E.g.: >>x=2.34; y=3.15; z=2*pi;
>> fprintf (‘The value %f is less than %f is less than %g’, x, y, z);
-- Continue…
Field width and precision specifications
 Field width – A string specifying minimum number of digits to
be printed (%6f)
 Precision – A string including a period (.) specifying the number
of digits to be printed to the right of the decimal point (%6.2f)
Optional flags
‘-’ – Left justifies the number within the field (%-4.2d)
‘+’ – prints a sign character (+ or -) before the number (%+4.2d)
‘0’ – add zero before the number it is shorter than the defined
field (%04.2d)
Space character – Inserts a space before the value (% 4.2d)
-- Continue…
Conversion characters
%c – Single character
%d – Decimal notation (signed)
%e - Exponential notation (using lowercase e as 3.1415e+00)
%E - Exponential notation (using uppercase E as 3.1415E+00)
%f – Fixed point notation
%g – The shorter of %e or %f
%G – Same as %g, with uppercase E
%i – Decimal notation (signed)
%o – Octal notation (unsigned)
%s – String of characters
%u – Decimal notation (unsigned)
%x – Hexadecimal notation (using lowercase letters a-f)
%X - Hexadecimal notation (using uppercase letters A-F)
-- Continue…
>> x = [0 0.2 0.4 0.6 0.8 1.0]
 Default format : >> x = 0:0.2:1;
 Compact format: >> fprintf (‘%g ’, x);
 Compact format with new line: >> fprintf (‘%gn ’, x);
 Floating point format with width 4 and precision 2 in
newline: >> fprintf (‘%4.2fn ’, x);
 Exponent format with new line: >> fprintf (‘%4.2en ’,
x);
Numbers and operations
Numerical Data:
 Variables are defined with the assignment operator “=“. MATLAB is
dynamically typed, meaning that variables can be assigned without declaring their
type, and that their type can change. There is no need to define variables as integers,
reals, etc, as in other languages
◦ Integers: a=2
◦ Reals: x=-35.2
 Maximum 19 significant figures
 2.23e-3=2.23*10-3
 Precision and formats: By defect, it uses a short format defect, but other formats
can be used:
>> format long (14 significant figures)
>> format short (5 significant figures)
>> format short e (exponential notation)
>> format long e (exponential notation)
>> format rat (rational approximation)
See in File menu: Preferences Command Windows→
Numbers and operations
Preferences (in File menu)
Numbers and operations
Numerical data:
 They’re case sensitive: x=5, X=7
 Information about the variables used and their dimensions (if they’re
matrices): Workspace. Also typing
>> who
>> whos (gives more information)
 To delete a variable (or several), run:
>> clear variable1 variable2
 To delete all the variables, run: >> clear
 Characteristic constants: pi=π, NaN (not a number, 0/0), Inf=∞.
 Complex numbers:
i=sqrt(-1) (only i or j can be used), z=2+i*4, z=2+4i
◦ Careful not to use ‘i’ or “j” afterwards as a counter for a
loop when working with complex numbers.
Numbers and operations
Basic Arithmetic Operations:
 Addition: +, Substraction -
 Multiplication: *, Division: /
 Power: ^
 Priority Order: Power, division and multiplication,
and lastly addition and substraction. Use () to
change the priority.
Numbers and operationsNumbers and operations
Matlab Functions:
 exp(x), log(x) (base e), log2(x) (base 2), log10(x) (base 10),
sqrt(x)
 Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x),
atan(x), atan2(x) (entre –pi & pi)
 Hyperbolic functions: sinh(x), cosh(x), tanh(x), asinh(x), acosh(x),
atanh(x)
 Other functions: abs(x) (absolute value), int(x) (integer part ),
round(x) (rounds to the closest integer), sign(x) (sign function)
 Functions for complex numbers: real(z) (real part), imag(z)
(imaginary part), abs(z) (modulus), angle(z) (angle), conj(z)
(conjugated)
 ceil, floor: Round toward infinities
 fix: Round toward zero
Vectors and matrices
Defining vectors:
 Row vectors; elements separated by spaces or comas
>> v =[2 3 4]
 Column vectors: elements separated by semicolon (;)
>> w =[2;3;4;7;9;8]
 Length of a vector w: length(w)
 Generating row vectors:
◦ Specifying the increment h between the elements v=a:h:b
◦ Specifying the dimension n: linspace(a,b,n) (by default
n=100)
◦ Elements logarithmically spaced logspace(a,b,n) (n
points logarithmically spaced between 10a
y 10b.
By default
n=50)
Vectors and matrices
Defining matrices:
 It’s not needed to define their size before hand (a size can be defined
and changed afterwards).
 Matrices are defined by rows; the elements of one row are
separated by spaces or comas. Rows are separated by semicolon (;).
» M=[3 4 5; 6 7 8; 1 -1 0]
 Empty matrix: M=[ ];
 Information about an element: M(1,3), a row M(2,:), a column M(:,3).
 Changing the value of an element: M(2,3)=1;
 Deleting a column: M(:,1)=[ ], a row: M(2,:)=[ ];
Vectors and matrices
Defining matrices:
 Generating the matrices:
◦ Generating a matrix full of zeros, zeros(n,m)
◦ Generating a matrix full of ones, ones(n,m)
◦ Initializing an identity matrix eye(n,m)
◦ Generating a matrix with random elements rand(n,m)
 Adding matrices: [X Y] columns, [X; Y] rows
Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
3
4
5
1 2 3 4 5
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A =
A(3,1)
A(3)
A(1:5,5)
A(:,5)
A(21:25)
A(4:5,2:3)
A([9 14;10 15])
A(1:end,end)
A(:,end)
A(21:end)’
Operations with vectors and matrices
Operating vectors and matrices with scalars:
v: vector, k: scalar:
 v+k addition
 v-k sustraction
 v*k product
 v/k divides each element of v by k
 k./v divides k by each element of v
 v.^k powers each element of v to the k-power
 k.^v powers k to each element of v
Operations with vectors and matrices
Operating vectors and matrices
 + addition
 – subtraction
 * matrix product
 .* product element by element
 ^ power
 .^ power element by element
  left-division
 / right-division
 ./ or . right and left division element by element
 Transposed matrix: B=A’ (in complex numbers, it returns the
conjugated transposed, to get only the trasposed: B=A.’)
Functions for vectors and matrices
 sum(v) adds the elements of a vector
 prod(v) product of the elements of a vector
 dot(v,w) vectors dot product
 cross(v,w) cross product
 mean(v) (gives the average)
 diff(v) (vector whose elements are the differenceof the elements of v)
 [y,k]=max(v) or min(v)
maximum value or minimum valueof the elements of a vector (k gives the
position)
The maximum value of a matrix V is obtained with max(max(v)) and the
minimum with min(min(v))
 Some of these operations applied to matrices, give the result by columns.
Functions for vectors and matrices
 [n,m]=size(M) gives the number of rows and columns
 Inverted matrix: B=inv(M), rank: rank(M)
 diag(M): gives the diagonal of a matrix. sum(diag(M)) sums the
elements of the diagonal of M. diag(M,k) gives the k-th diagonal.
 norm(M) norm of a matrix (maximum value of the absolute values
of the elements of M)
 flipud(M) reorders the matrix, making it symmetrical over an
horizontal axis.
 fliplr(M) ) reorders the matrix, making it symmetrical over a vertical
axis.
 [V, landa]=eig(M) gives a diagonal matrix landa with the eigen
values, and another V whose columns are the eigenvectors of M
MATLAB Special Variables
ans Default variable name for results
pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number
Matrix Multiplication (Example)
» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10
26 26 26
» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10
26 26 26
[2x4]
[4x3]
[2x4]*[4x3] [2x3]
a(2nd row).b(3rd column)
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16
5 12 21 32
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16
5 12 21 32 c(2,4) =
a(2,4)*b(2,4)
Array Multiplication
- Continue …
>> a = [1 2 3 4;5 6 7 8]
a =
1 2 3 4
5 6 7 8
>> b = [1:4;1:4]
b =
1 2 3 4
1 2 3 4
>> a.*b
ans =
1 4 9 16
5 12 21 32
Sample Program
% Program to accept input for the matrix A
rows = input('Enter the number of rows: ');
cols = input('Enter the number of columns: ');
for a = 1:rows
for b =1:cols
A(a,b)=input('Enter number: ');
end;
end;
Sample Program
transpose = transpose(A)
rot90 = rot90(A)
lowertriangle =tril(A)
uppertriangle = triu(A)
determinant =det(A)
inverse =inv(A)
eigenvalues=eig(A)
rank=rank(A)
disp(A)
Sample Program
Enter the number of rows: 3
Enter the number of columns: 3
Enter number: 12
Enter number: 10
Enter number: 14
Enter number: 5
Enter number: 6
Enter number: 7
Enter number: 8
Enter number: 9
Enter number: 15
The given matrix is:
12 10 14
5 6 7
8 9 15
Sample Program
transpose =
12 5 8
10 6 9
14 7 15
rot90 =
14 7 15
10 6 9
12 5 8
lowertriangle =
12 0 0
5 6 0
8 9 15
Sample Program
uppertriangle =
12 10 14
0 6 7
0 0 15
determinant =
92
inverse =
0.2935 -0.2609 -0.1522
-0.2065 0.7391 -0.1522
-0.0326 -0.3043 0.2391
eigenvalues =
29.0862
2.7732
1.1406
rank = 3
String Array Concatenation
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =
Hi there, Everyone!
» str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone!
Isn't MATLAB great?
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =
Hi there, Everyone!
» str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone!
Isn't MATLAB great?
1x19 vector
1x9 vectorsUsing [ ] operator:
Each row must be
same length
Row separator:
semicolon (;)
Column separator:
space / comma (,)
For strings of different length:
• STRVCAT
• char
» new_str3 = strvcat(str, str2)
new_str3 =
Hi there,
Isn't MATLAB great?
» new_str3 = strvcat(str, str2)
new_str3 =
Hi there,
Isn't MATLAB great?
2x19 matrix
2x19 matrix
(zero padded)
1x19 vectors
Working with String Arrays
String Comparisons
strcmp: compare whole strings
strncmp: compare first ‘N’ characters
findstr: finds substring within a larger string
Converting between numeric & string arrays:
num2str: convert from numeric to string array
str2num: convert from string to numeric array
Sample Program
%Program for sring manipulations
str1 = input('Enter first string ','s');
str2 = input('Enter second string ','s');
str3 = input('Enter third string ','s');
catstr = strcat(strcat(str1,str2),str3);
disp('The concatenated string is')
disp(catstr)
if strcmp(str1,str2)
disp('The first two strings are same')
else
disp('The first two strings are not same')
end;
Logical Operations
» Mass = [-2 10 NaN 30 -11 Inf 31];
» each_pos = Mass>=0
each_pos =
0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
all_pos =
0
» all_pos = any(Mass>=0)
all_pos =
1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin =
0 1 0 1 0 0 1
» Mass = [-2 10 NaN 30 -11 Inf 31];
» each_pos = Mass>=0
each_pos =
0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
all_pos =
0
» all_pos = any(Mass>=0)
all_pos =
1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin =
0 1 0 1 0 0 1
= = equal to
> greater than
< less than
>= Greater or equal
<= less or equal
~ not
& and
| or
isfinite(), etc. . . .
all(), any()
find
Note:
• 1 = TRUE
• 0 = FALSE
Polynomials
Polynomials
Roots (>> roots)
Evaluation (>> polyval)
Derivatives (>> polyder)
Curve Fitting (>> polyfit)
Partial Fraction Expansion (residue)
eg.
p = [1 2 3 7 10]
p =
1 2 3 7 10
Polynomials
>>roots(p)
ans =
0.5408 + 1.7419i
0.5408 - 1.7419i
-1.5408 + 0.7951i
-1.5408 - 0.7951i
>> polyder(p)
ans =
4 6 6 7
Control Structures
if (Conditional statement)
Matlab Commands
end
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
if (Conditional statement)
Matlab Commands
else
Matlab Commands
end
If Statement Syntax
Sample Program – Selection (IF)
% Program to accept 3 numbers and display the largest no.
fn = input('Enter first number:');
sn = input('Enter Second number:');
tn = input('Enter third number:');
if ((fn > sn)& (fn > tn))
disp('The largest number is')
disp(fn)
elseif (sn > tn)
disp('The largest number is')
disp(sn)
else
disp('The largest number is')
disp(tn)
end;
Structures of control condicionated: switch
 switch is similar to a sequence of if...elseif
switch_expresion=case_expr3
switch switch_expresion
case case_expr1,
actions1
case {case_expr2, case_expr3,case_expr4,...}
actions2
otherwise,
actions3
end
Sample Program – Selection (switch)
% Program to accept a choice from the user and perform
addition, subtraction, multiplication and division
testflag = 1;
disp('1.Add')
disp('2. Subtract')
disp('3. Multiply')
disp('4. Divide')
fn = input('Enter first number:');
sn = input('Enter second number:');
choice = input('Enter Choice');
switch choice
case 1
add = fn+sn;
disp('add =')
disp(add)
Sample Program – Selection (switch)
case 2
disp('sub =')
sub = fn - sn;
disp(sub)
case 3
disp('mul =')
mul = fn*sn;
disp(mul)
case 4
disp('div =')
div = fn/sn;
disp(div)
otherwise
disp('Invalid Choice')
testflag = 0;
end;
For loop syntax
for i=Index_Array
Matlab Commands
end
MATLAB Program
 Write a program to find the sum of even numbers
between 0 and 21 using the for loop.
%Program to use for loop
%File name example2_for.m
Sum=0;
for j=0:2:21
Sum=Sum + j;
end
Sum
While Loop Syntax
while (condition)
Matlab Commands
end
MATLAB Program
 Write a program to find the sum of even numbers between
0 and 21 using the fro loop.
%Program to use while loop
%File name example3_while.m
n=0;
Sum=0;
while n<21
Sum=Sum + n;
n=n+2;
end
Sum
Sample Program – Iteration (while)
% Program to accept a choice from the user and perform
addition, subtraction, multiplication and division
testflag = 1;
disp('1.Add')
disp('2. Subtract')
disp('3. Multiply')
disp('4. Divide')
fn = input('Enter first number:');
sn = input('Enter Second number:');
while (testflag == 1)
choice = input('Enter Choice');
switch choice
case 1
add = fn+sn;
disp('add =')
disp(add)
Sample Program – Iteration (while)
case 2
disp('sub =')
sub = fn - sn;
disp(sub)
case 3
disp('mul =')
mul = fn*sn;
disp(mul)
case 4
disp('div =')
div = fn/sn;
disp(div)
otherwise
disp('Invalid Choice')
testflag = 0;
end;
end;
Graphics Fundamentals
Basic Plotting
plot, title, xlabel, grid,
legend, hold, axis
Editing Plots
Property Editor
Mesh and Surface Plots
meshgrid, mesh, surf,
colorbar, patch, hidden
2-D Plotting
Example 1
x=[2004 2005 2006 2007 2008 2009];
y=[85 100 90 95 85 90];
plot(x,y)
Example 2
f=50;
w=2*pi*f;
t=0:1e-3:0.04;
x=w*t;
y=sin(x);
plot(t,y);
Basic Task: Plot the function sin(x)
between 0≤x≤4π
Create an x-array of 100 samples between 0
and 4π.
Calculate sin(.) of the x-array
Plot the y-array
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
0 10 20 30 40 50 60 70 80 90 100
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Plot the function e-x/3
sin(x) between
0≤x≤4π
Create an x-array of 100 samples between
0 and 4π.
Calculate sin(.) of the x-array
Calculate e-x/3
of the x-array
Multiply the arrays y and y1
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>y1=exp(-x/3);
>>y2=y*y1;
Plot the function e-x/3
sin(x) between
0≤x≤4π
Multiply the arrays y and y1 correctly
Plot the y2-array
>>y2=y.*y1;
>>plot(y2)
0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Display Facilities
plot(.)
stem(.)
Example:
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
>>plot(x,y)
Example:
>>stem(y)
>>stem(x,y)
0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
- Continue
title(.)
xlabel(.)
ylabel(.)
>>title(‘This is the sinus function’)
>>xlabel(‘x (secs)’)
>>ylabel(‘sin(x)’)
0 10 20 30 40 50 60 70 80 90 100
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
This is the sinus function
x (secs)
sin(x)
>>grid;
Formatting a plot
>>Plot(x, y, ‘linespecifier’, ‘propertyname’, propertyvalue’)
Line specifier
Line style Marker style Colour
- Solid . Point y Yellow
: Dotted o Circle m Magenta
- Dash-dot x X-mark c Cyan
-- Dashed + Plus r Red
<none> No line * Star g Green
s Square b Blue
d Diamond w White
v Triangle(down) k Black
^ Triangle(up)
< Triangle(left)
> Triangle(right)
p Pentagram
h Hexagram
<none> No marker
- Continue
Property name and value
 LineWidth
 MarkerEdgeColor
 MarkerFaceColor
 Markersize
E.g.: f=50;
w=2*pi*f;
t=0:1e-3:0.04;
x=w*t;
y=sin(x);
plot(t, y, ‘- - rs’, ‘LineWidth’, 2.5, ‘MarkerEdgeColor’, ‘k’,
‘MarkerFaceColor’, ‘g’, ‘MarkerSize’, 8);
Multiple Plots
Using plot command
 Plot the voltage (v=5sinwt) and current(i=2sin(wt-Φ))
flow through a circuit on the common axis.
%Multiple plot using plot command
%Filename Example1_mp
t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3;
v=5*sin(w*t);
i= 2*sin((w*t)-phi);
plot(t,v,t,i)
title(“Multiple plot using plot command’);
xlabel(‘Time(sec)’);
ylabel(‘Voltage & Current’);
grid;
- Continue
Using hold command
%Multiple plot using hold command
%Filename Example2_mp
t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3;
v1=sin(w*t);
plot(t,v1)
hold on; % Retain the current plot and certain axes properties
gtext(‘v1 = sin(wt)’);
v2=cos(w*t);
plot(t,v2)
hold off; % Reset axes properties to their defaults before drawing new plot
gtext(‘v2 = cos(wt)’);
title(‘Multiple plot using hold command’);
xlabel(‘Time(sec)’);
ylabel(‘V1 & V2’);
grid;
- Continue
Using line command
>>line (xdata, ydata, parameter_name, parameter_value)
%Multiple plot using line command
%Filename Example3_mp
t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3;
v1=sin(w*t);
v2=cos(w*t);
plot(t, v1, ‘- -’);
gtext(‘v1 = sin(wt)’);
line(t,v2);
gtext(‘v2=cos(wt)’);
title(‘Multiple plot using hold command’);
xlabel(‘Time(sec)’);
ylabel(‘V1 & V2’);
grid;
Adding legend to a plot
>> legend(‘string1’, ‘string2’,… pos)
Value Position Value Position
-1 Outside axis on the right
side
MC Middle and
centre
0 Auto placement with least
interferes with data
ML Middle and left
1 Upper right corner of the
plot (default)
MR Middle and right
2 Upper left corner of the
plot
BL Bottom left
3 Lower left corner of the
plot
BC Bottom centre
4 Lower right corner of the
plot
BR Bottom right
Formatting the text in Title, Labels and Legends
Modifier Effect Character
String
Greek Letter
bf Bold fonts alpha α
it Italic fonts beta β
rm Normal fonts gamma γ
fontname Type of font used theta θ
fontsize Size of font used phi Φ
- Subscript Delta Δ
^ Superscript delta δ
omega ω
Omega Ω
sigma σ
Sigma Σ
infty ∞
circ º
Special plots
>>subplot(p, r, r)
E.g.: subplot(2,1,1); plot(t,v);
subplot(2,1,2); plot(t,i);
>>semilogx(x, y); semilogy(x, y); loglog(x,y)
% Logarithmic plot of a function
% File name example4_sp
x=linspace(0.1,60,1000);
y=3.^(-0.2*x+10)-5;
subplot(2,2,1), plot(x,y);
title(‘plot(x,y)’); xlabel(‘Linear’); ylabel(‘Linear’); grid;
subplot(2,2,2), semilogx(x,y);
title(‘Semilogx(x,y)’); xlabel(‘Log’); ylabel(‘Linear’); grid;
subplot(2,2,3), semilogy(x,y);
title(‘Semilogy(x,y)’); xlabel(‘Linear’); ylabel(‘Log’); grid;
subplot(2,2,4), loglog(x,y);
title(‘Loglog(x,y)’); xlabel(‘Log’); ylabel(‘Log’); grid;
- Continue
>>bar(x,y); %Vertical bar chart
>>barh(x,y); %Horizontal bar chart
>>stairs(x,y); %Stairs plot
>>stem(x,y); %Stem plot
>>pie(x); % Pie plot
>>pie(x, explode); %Pie plot with explode
Specialized Plotting Routines
bar; bar3h; hist; area; pie3; rose
Plotting a complex data
Both real and imaginary can be plotted with
respect to time
>> plot(t, real(x));
>>plot(t, imag(x));
Real part can be plotted versus imaginary part
>>plot(x)
Complex function can be directly plotted as a
polar plot in terms of magnitude versus angle
>>polar(angle(x), abs(x))
- Continue…
 E.g.: - x(t)=e-0.2t
(sint + jcost) for (0≤t ≤ 2π)
%Plot the complex function
%File name example_cf
% Real & Imaginary w.r.t time
t=0: pi/20 : 2*pi;
x=exp(-0.2*t) .* (sin(t) + i*cos(t));
figure(1);
plot(t, real(x), ‘-.’);
hold on;
plot(t, imag(x), ‘r’);
title(‘Plot of complex data versus time’);
xlabel(‘bfTime’);
ylabel(‘bfx(t)’);
legend(‘real’, ‘imaginary’);
grid;
- Continue…
% Real versus imaginary
figure(2);
plot(x);
title(‘Plot of complex data’);
xlabel(‘bfReal part’);
ylabel(‘bfImaginary part’);
grid;
% Polar plot
figure(3);
polar(angle(x), abs(x));
title(‘Plot of complex data as polar plot’);
grid;
Plotting a function
>> command(‘fun’, limits, linespecifiers)
◦ Command: ezplot or fplot
◦ fun: Function to be plotted
◦ limits: Limits of plot(optional)
◦ Linespecifiers: Type and colour of the line and marker (optional)
E.g: - Plot the function f(x) = 0.2x+(sin(2x)/x)
>>ezplot(‘(0.2*x)+(sin(2*x)/x)’);
>> fplot(‘(0.2*x)+(sin(2*x)/x)’);
>> fplot(‘(0.2*x)+(sin(2*x)/x)’, [-2*pi 2*pi]);
>> fplot(‘(0.2*x)+(sin(2*x)/x)’, [-2*pi 2*pi –pi pi]);
3-D plotting
>>Plot3(x, y, z, ‘linespeicifiers’, ‘propertyname’,
‘propertyvalue’)
E.g.: x(t) = √tcos2t; y(t) = √tsin2t;
%3-D plot
%plot3 command
% file name example_3d
t=0: 0.1: 10;
x=sqrt(t).*cos(2*t);
y=sqrt(t).*sin(2*t);
plot3(x,y,t);
title(‘bf 3-D Plot’); xlabel(‘x’); ylabel(‘y’); zlabel(‘time’);
grid;
Surface plot Example
x = 0:0.1:2;
y = 0:0.1:2;
[xx, yy] = meshgrid(x,y);
zz=sin(xx.^2+yy.^2);
surf(xx,yy,zz)
xlabel('X axes')
ylabel('Y axes')
x = 0:0.1:2;
y = 0:0.1:2;
[xx, yy] = meshgrid(x,y);
zz=sin(xx.^2+yy.^2);
surf(xx,yy,zz)
xlabel('X axes')
ylabel('Y axes')
3-D Surface Plotting
contourf; colorbar; plot3; waterfall; contour3; mesh; surf
MATLAB Function Programming
Functions and function files
>>function[output_argument]=function_name(input_argument);
>>function[output_argument1, output_argument2 …. ]
=function_name(input_argument1, input_argument2….);
E.g.: Write a program to solve the function
By writing a function file with ‘fun_1’, with the input to the function is
y and output f(y) for following values of x;
a) f(y) for y=4
b) f(y) for y=2, 4, 6, 8, 10
%Program to solve y(x) using function approach
Y=input(‘Enter the value of Y:’);
X=fun_1(Y);
disp(X);
%Function file fun_1
function X = fun_1(Y);
X=(Y.^3.*sqrt(2*Y+4))./(Y.^3+1).^2;
Differential equation solver
ODE - Ordinary Differential Equations
MATLAB ODE Solvers
Solver Problem type
/Accuracy
Description
ode23 Non-stiff /Medium One-step solver based on explicit Runge-Kutta (II
and III) method. In general faster but less accurate
than ode45
ode45 Non-stiff /Low One-step solver based on explicit Runge-Kutta (IV
and V) method. In general moderate accuracy
ode113 Non-stiff /Low to high Multi-step solver based on Adams method
ode15s Stiff /Moderate Multi-step solver of variable order (I to V)
ode23s Stiff /Low One-step low order solver based on a modified
Rosenbrock formula of order two
ode23t Moderately stiff /Low One-step solver based on trapezoidal rule
ode23tb Stiff /Low A low order solver, more efficient than ode15s
ode15i Solves fully implicit differential equations, variable
order method
ODE solver syntax
ODE = dy/dt = f(t, y)
>>[t, y] = solver_name(‘function’, tspan, y0);
E.g.:1) for 1≤ t ≤ 2 with initial condition y1=2.3 at t=0
for 1≤ t ≤ 2 with initial condition y2=1.2 at t=0
% create function file
function y1dot = ode_fun_1(t, y1) % Save file name ode_fun_1.m
y1dot = (t^2-2*y1)/t;
function y2dot = ode_fun_2(t, y2) % Save file name ode_fun_2.m
y2dot = (t^2-2*t)/t;
% Solve ODE
>>[t, y1] = ode45(‘ode_fun_1’, [1:0.2:2], 2.3);
>>[t, y2] = ode45(‘ode_fun_2’, [1:0.2:2], 1.2);
- Continue
 E.g.:2) Write a program to find the step response of RL circuit for
the time range 0 to 1 sec with initial condition i=1 amps at t=0.
V = iR + L (di/dt); di/dt = (V-iR) / L
% Program to plot step response of series RL circuit
close all; clear; clc;
global R L V
R = 2; L=100e-3; V=10;
[t i] = ode45(‘RL_series’, [1:0.01:1], 1);
plot(t, i); grid; xlabel (‘Time(sec)’); ylabel (‘Current(amps)’);
%Function file RL_series
function idot = RL_series (t, i)
global R L V
idot = (1/L)*(V-i*R);
Calculus functions
Differentiation
>>diff(y) % dy/dx
>>diff(y,x) % dy/dx
>>diff(y,a) % dy/da
>>diff(y,t,2) % d2
y/dt2
Integration
>> int(y)
>> int(y,t)
>> int(y, a, b)
>> int (y, t, a, b)
Symbolic math functions
Sym  x = sym(x)
>>a=5; b=sqrt (sym(a))
>>a=2/3; b=3/4; x = sym(a) + sym(b)
>>syms a b c; x = a^2 + 2*b + c
>>subs(x, a, 2)
>>subs(x, 2)
>>findsym(x)
>>findsym(x, 2)
ASSIGNMENT – MATLABASSIGNMENT – MATLAB
OVERVIEWOVERVIEW
 Accept the roll number, name, 3 subject marks of a
student and print the details of the student with total
and average.
 For problem (1), print the grade of the student as
pass(average>=50) or fail (average<50). Use If
statement
 For problem (1), print the grade of the student as
Distinction (average>=90), First Class (average >=80
and <90), Second Class(average >=70 and <80), Third
Class (average>=60 and <70) otherwise Fail. Use
nested if statement
 Accept a number and based on the choice of the user
display the square, cube, and quadruple of the number.
Use Switch case
 Count the number of Vowels in a given string
Find the total number of characters in a given string
- Continue …
 Check whether the original string and the reversed string are
same. If so, display palindrome string else not a palindrome
string.
 Generate the Fibonacci Series 0 1 1 2 3 5 8 …N
 Check whether the given number is perfect square (Number
divisible by 1 and itself)
 List all Prime numbers between 1 and 100
 Consider 3 subject marks for a student and use bar chart to
represent.
 Consider a subject mark for 5 students and use bar chart to
represent
 Perform Matrix Addition (Size mxn)
 Find the roots and derivatives of the polynomial accepted from
the user.
 Concatenate two vectors and sort.
Introduction to matlab

More Related Content

What's hot

Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Randa Elanwar
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabTarun Gehlot
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to MatlabAmr Rashed
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Loops in matlab
Loops in matlabLoops in matlab
Loops in matlabTUOS-Sam
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlabaman gupta
 
Importance of matlab
Importance of matlabImportance of matlab
Importance of matlabkrajeshk1980
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab OverviiewNazim Naeem
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming LanguageExplore Skilled
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Insertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexityInsertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexityMotaleb Hossen Manik
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sortMadhu Bala
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 

What's hot (20)

Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab basic and image
Matlab basic and imageMatlab basic and image
Matlab basic and image
 
MATLAB INTRODUCTION
MATLAB INTRODUCTIONMATLAB INTRODUCTION
MATLAB INTRODUCTION
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Loops in matlab
Loops in matlabLoops in matlab
Loops in matlab
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Importance of matlab
Importance of matlabImportance of matlab
Importance of matlab
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Insertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexityInsertion Sort, Quick Sort And Their complexity
Insertion Sort, Quick Sort And Their complexity
 
Matlab GUI
Matlab GUIMatlab GUI
Matlab GUI
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 

Viewers also liked

Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Randa Elanwar
 
Introduction to matlab_application_to_electrical_engineering
Introduction to matlab_application_to_electrical_engineeringIntroduction to matlab_application_to_electrical_engineering
Introduction to matlab_application_to_electrical_engineeringzulfikar37
 
Simulink - Introduction with Practical Example
Simulink - Introduction with Practical ExampleSimulink - Introduction with Practical Example
Simulink - Introduction with Practical ExampleKamran Gillani
 
DIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSINGDIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSINGSnehal Hedau
 
Introduction to Digital Signal Processing
Introduction to Digital Signal ProcessingIntroduction to Digital Signal Processing
Introduction to Digital Signal Processingop205
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introductionideas2ignite
 

Viewers also liked (7)

Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4
 
Introduction to matlab_application_to_electrical_engineering
Introduction to matlab_application_to_electrical_engineeringIntroduction to matlab_application_to_electrical_engineering
Introduction to matlab_application_to_electrical_engineering
 
Simulink - Introduction with Practical Example
Simulink - Introduction with Practical ExampleSimulink - Introduction with Practical Example
Simulink - Introduction with Practical Example
 
DIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSINGDIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSING
 
Introduction to Digital Signal Processing
Introduction to Digital Signal ProcessingIntroduction to Digital Signal Processing
Introduction to Digital Signal Processing
 
Dsp ppt
Dsp pptDsp ppt
Dsp ppt
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
 

Similar to Introduction to matlab

Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabvikrammutneja1
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introductionAmeen San
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondMahuaPal6
 
More instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxMore instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxgilpinleeanna
 
Basics of MATLAB programming
Basics of MATLAB programmingBasics of MATLAB programming
Basics of MATLAB programmingRanjan Pal
 
Handout2.pdf
Handout2.pdfHandout2.pdf
Handout2.pdfShoukat13
 

Similar to Introduction to matlab (20)

1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
Matlab1
Matlab1Matlab1
Matlab1
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Es272 ch1
Es272 ch1Es272 ch1
Es272 ch1
 
Tutorial2
Tutorial2Tutorial2
Tutorial2
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
More instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxMore instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docx
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Basics of MATLAB programming
Basics of MATLAB programmingBasics of MATLAB programming
Basics of MATLAB programming
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Handout2.pdf
Handout2.pdfHandout2.pdf
Handout2.pdf
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Introduction to matlab

  • 1. MATLAB – An Overview
  • 2. INTRODUCTION MATLAB (MATrix LABoratory)  Deals with matrix manipulations  Data defined : Array (in the form of row and column)  Special purpose computer programme  Perform engineering & scientific calculations with graphical visualization  Provide Integrated Development Environment (IDE) for programming  No. of predefined functions for computation and visualization
  • 3. Features and capabilities MATLAB (Programming Language) Built-in Functions User Defined Functions Visualization -2D Graphics -3D Graphics (With edit features) GUI Tool Toolboxes (for dynamic simulations) Simulink SimpowerSystems Fuzzy Logic Neural Network Communication Control system DSP External Interface (With C and FORTRAN)
  • 4. Starting and Ending MATLAB Starting: Start / All Programs / MATLAB / R2010b / MATLAB R2010b Double clicking on MATLAB icon located on the desktop Ending: Entering exit at MATLAB command prompt : >>exit Entering quit at MATLAB command prompt: >>quit Selecting Exit from file menu Pressing Ctrl+Q at command prompt
  • 5. Basic elements of Matlab’s desktop  Command Windows: Where all commands and programs are run. Write the command or program name and hit Enter.  Command History: Shows the last commands run on the Command Windows. A command can be recovered clicking twice  Current directory: Shows the directory where work will be done.  Workspace: To see the variables in use and their dimensions (if working with matrices)  Help (can also be called from within the command windows)  Matlab Editor: All Matlab files must end with .m extension.
  • 6. Command Windows Current directory Command History Basic elements of Matlab’s desktopBasic elements of Matlab’s desktop
  • 7. Basic elements of Matlab’s desktop Some comments about the command window Commands can be retrieved with arrow up / arrow down keys ↓↑ Moving around the command line is possible with left / right arrow keys . Go to the→ ← beginning of the line with Inicio (Home) and to the end with Fin (End). Esc deletes the whole line. A program can be stopped with Ctrl+c
  • 8. Matlab editor  There can not be empty spaces in the name of the Matlab files  Use “main_” for the name of the main programs, for example: main_curvature  Write “;” at the end of a line If you don’t want that the intermediate calculus is written in the window while the program is running  Write “%” at the beginning of a line to write a comment in the program  Write “…” at the end of a line if you are writing a very long statement and you want to continue in the next line
  • 9. MATLAB Editor Window %Calculate volume of the cylinder r=5; %Define radius of cylinder h=10; %Define height of cylinder volume=pi*r^2*h; string=['The Volume of the cylinder is',num2str(volume)]; disp(string);
  • 10. Workspace Temporary memory All variables are cleared on ending/quit MATALB Save workspace : save <file name> Particular value can be saved Save <file name> <variable1 variable2 ….> Load workspace: load <file name> List of variables with details can generated >>whos >>who
  • 11. Types of Files .m files – Script files and function files (M-files) .mat files – Binary data files (MAT-files) .fig files – Figure windows .mdl files – Model files (Simulink or other toolboxes) .mes files – MEX files ◦ Interface files write in C or FORTRAN ◦ Using mex function, mex compiles and link source file into a shared library
  • 12. Data input and output  Saving to files and recovering data:  Save <mat file_name> matrix1_name, matrix2_name  Load <mat file_name> matrix1_name, matrix2_name  save file_name matrix1_name –ascii (saves 8 figures after the decimal point)  save file_name matrix1_name –ascii –double (saves 16 figures after the decimal point)
  • 13. Getting help help command ( >>help ) lookfor command ( >>lookfor) LOOKFOR Search all M-files for keyword. Help Browser ( >>doc ) helpwin command ( >>helpwin )
  • 14. Important Commands cd – Display/ Change current working directory clc – Clear command window clear – Clear content of workspace clf – Clear content of current figure window close – Close current figure window ^c – Abort / terminate the execution of current program/command date – Current date as date string demo – Runs the demo programs dir – List files/folders in present directory exit – End (quit) a MATLAB session help – Display help text in command window
  • 15. Important Commands  load – Load saved workspace from working directory  lookfor – Search all M-files for a particular command or keyword  path – Get/set MATLAB search path  pwd – Gives present working directory  quit – End a MATLAB session  save – Saves current workspace variables in working directory  ver – Gives the MATLAB, SIMULINK and Toolboxes version information  who – Generate the list of variables available in the current workspace  whos – Generate the list of variables available in the current workspace with their details (type, size, etc.)
  • 16. Input/Output Commands Input command R=input(‘Enter the value of Resistance (in ohms): ’); Output command disp (variable name) or disp (‘Content of string’) E.g.:- >>A=[1 2 3; 4 5 6]; >>disp(A); >>disp(‘My Name is MATLAB’); Display formatted string : fprintf (‘Text String’) E.g.: fprintf(‘n Invalid data range.n Please enter new input.n’); n : Newline; b: Backspace; t: Horizontal tab f: Form feed; r: Carriage return; : Print backlash () ’: Print apostrophe or single quote; %%: Print %
  • 17. -- Continue…  Display a variable with text fprintf (‘…Text…. Formatting elements ….Text….’, variable name); Formatting elements : %-4.2d % = Start of format element - = Flags 4 = field width 2 = Precision d = conversion character E.g.: fprintf (‘The value of pi is %2.3f displayed up to three decimal digits’, pi);  Display more than one variable  fprintf (‘…Text…. %f…. %g… %c….’, variable1, variable 2, variable3 ); E.g.: >>x=2.34; y=3.15; z=2*pi; >> fprintf (‘The value %f is less than %f is less than %g’, x, y, z);
  • 18. -- Continue… Field width and precision specifications  Field width – A string specifying minimum number of digits to be printed (%6f)  Precision – A string including a period (.) specifying the number of digits to be printed to the right of the decimal point (%6.2f) Optional flags ‘-’ – Left justifies the number within the field (%-4.2d) ‘+’ – prints a sign character (+ or -) before the number (%+4.2d) ‘0’ – add zero before the number it is shorter than the defined field (%04.2d) Space character – Inserts a space before the value (% 4.2d)
  • 19. -- Continue… Conversion characters %c – Single character %d – Decimal notation (signed) %e - Exponential notation (using lowercase e as 3.1415e+00) %E - Exponential notation (using uppercase E as 3.1415E+00) %f – Fixed point notation %g – The shorter of %e or %f %G – Same as %g, with uppercase E %i – Decimal notation (signed) %o – Octal notation (unsigned) %s – String of characters %u – Decimal notation (unsigned) %x – Hexadecimal notation (using lowercase letters a-f) %X - Hexadecimal notation (using uppercase letters A-F)
  • 20. -- Continue… >> x = [0 0.2 0.4 0.6 0.8 1.0]  Default format : >> x = 0:0.2:1;  Compact format: >> fprintf (‘%g ’, x);  Compact format with new line: >> fprintf (‘%gn ’, x);  Floating point format with width 4 and precision 2 in newline: >> fprintf (‘%4.2fn ’, x);  Exponent format with new line: >> fprintf (‘%4.2en ’, x);
  • 21. Numbers and operations Numerical Data:  Variables are defined with the assignment operator “=“. MATLAB is dynamically typed, meaning that variables can be assigned without declaring their type, and that their type can change. There is no need to define variables as integers, reals, etc, as in other languages ◦ Integers: a=2 ◦ Reals: x=-35.2  Maximum 19 significant figures  2.23e-3=2.23*10-3  Precision and formats: By defect, it uses a short format defect, but other formats can be used: >> format long (14 significant figures) >> format short (5 significant figures) >> format short e (exponential notation) >> format long e (exponential notation) >> format rat (rational approximation) See in File menu: Preferences Command Windows→
  • 23. Numbers and operations Numerical data:  They’re case sensitive: x=5, X=7  Information about the variables used and their dimensions (if they’re matrices): Workspace. Also typing >> who >> whos (gives more information)  To delete a variable (or several), run: >> clear variable1 variable2  To delete all the variables, run: >> clear  Characteristic constants: pi=π, NaN (not a number, 0/0), Inf=∞.  Complex numbers: i=sqrt(-1) (only i or j can be used), z=2+i*4, z=2+4i ◦ Careful not to use ‘i’ or “j” afterwards as a counter for a loop when working with complex numbers.
  • 24. Numbers and operations Basic Arithmetic Operations:  Addition: +, Substraction -  Multiplication: *, Division: /  Power: ^  Priority Order: Power, division and multiplication, and lastly addition and substraction. Use () to change the priority.
  • 25. Numbers and operationsNumbers and operations Matlab Functions:  exp(x), log(x) (base e), log2(x) (base 2), log10(x) (base 10), sqrt(x)  Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(x) (entre –pi & pi)  Hyperbolic functions: sinh(x), cosh(x), tanh(x), asinh(x), acosh(x), atanh(x)  Other functions: abs(x) (absolute value), int(x) (integer part ), round(x) (rounds to the closest integer), sign(x) (sign function)  Functions for complex numbers: real(z) (real part), imag(z) (imaginary part), abs(z) (modulus), angle(z) (angle), conj(z) (conjugated)  ceil, floor: Round toward infinities  fix: Round toward zero
  • 26. Vectors and matrices Defining vectors:  Row vectors; elements separated by spaces or comas >> v =[2 3 4]  Column vectors: elements separated by semicolon (;) >> w =[2;3;4;7;9;8]  Length of a vector w: length(w)  Generating row vectors: ◦ Specifying the increment h between the elements v=a:h:b ◦ Specifying the dimension n: linspace(a,b,n) (by default n=100) ◦ Elements logarithmically spaced logspace(a,b,n) (n points logarithmically spaced between 10a y 10b. By default n=50)
  • 27. Vectors and matrices Defining matrices:  It’s not needed to define their size before hand (a size can be defined and changed afterwards).  Matrices are defined by rows; the elements of one row are separated by spaces or comas. Rows are separated by semicolon (;). » M=[3 4 5; 6 7 8; 1 -1 0]  Empty matrix: M=[ ];  Information about an element: M(1,3), a row M(2,:), a column M(:,3).  Changing the value of an element: M(2,3)=1;  Deleting a column: M(:,1)=[ ], a row: M(2,:)=[ ];
  • 28. Vectors and matrices Defining matrices:  Generating the matrices: ◦ Generating a matrix full of zeros, zeros(n,m) ◦ Generating a matrix full of ones, ones(n,m) ◦ Initializing an identity matrix eye(n,m) ◦ Generating a matrix with random elements rand(n,m)  Adding matrices: [X Y] columns, [X; Y] rows
  • 29. Subscripting / Indexing 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 1 2 3 4 5 1 2 3 4 5 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) A(1:end,end) A(:,end) A(21:end)’
  • 30. Operations with vectors and matrices Operating vectors and matrices with scalars: v: vector, k: scalar:  v+k addition  v-k sustraction  v*k product  v/k divides each element of v by k  k./v divides k by each element of v  v.^k powers each element of v to the k-power  k.^v powers k to each element of v
  • 31. Operations with vectors and matrices Operating vectors and matrices  + addition  – subtraction  * matrix product  .* product element by element  ^ power  .^ power element by element  left-division  / right-division  ./ or . right and left division element by element  Transposed matrix: B=A’ (in complex numbers, it returns the conjugated transposed, to get only the trasposed: B=A.’)
  • 32. Functions for vectors and matrices  sum(v) adds the elements of a vector  prod(v) product of the elements of a vector  dot(v,w) vectors dot product  cross(v,w) cross product  mean(v) (gives the average)  diff(v) (vector whose elements are the differenceof the elements of v)  [y,k]=max(v) or min(v) maximum value or minimum valueof the elements of a vector (k gives the position) The maximum value of a matrix V is obtained with max(max(v)) and the minimum with min(min(v))  Some of these operations applied to matrices, give the result by columns.
  • 33. Functions for vectors and matrices  [n,m]=size(M) gives the number of rows and columns  Inverted matrix: B=inv(M), rank: rank(M)  diag(M): gives the diagonal of a matrix. sum(diag(M)) sums the elements of the diagonal of M. diag(M,k) gives the k-th diagonal.  norm(M) norm of a matrix (maximum value of the absolute values of the elements of M)  flipud(M) reorders the matrix, making it symmetrical over an horizontal axis.  fliplr(M) ) reorders the matrix, making it symmetrical over a vertical axis.  [V, landa]=eig(M) gives a diagonal matrix landa with the eigen values, and another V whose columns are the eigenvectors of M
  • 34. MATLAB Special Variables ans Default variable name for results pi Value of π eps Smallest incremental number inf Infinity NaN Not a number e.g. 0/0 i and j i = j = square root of -1 realmin The smallest usable positive real number realmax The largest usable positive real number
  • 35. Matrix Multiplication (Example) » a = [1 2 3 4; 5 6 7 8]; » b = ones(4,3); » c = a*b c = 10 10 10 26 26 26 » a = [1 2 3 4; 5 6 7 8]; » b = ones(4,3); » c = a*b c = 10 10 10 26 26 26 [2x4] [4x3] [2x4]*[4x3] [2x3] a(2nd row).b(3rd column) » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32 » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32 c(2,4) = a(2,4)*b(2,4) Array Multiplication
  • 36. - Continue … >> a = [1 2 3 4;5 6 7 8] a = 1 2 3 4 5 6 7 8 >> b = [1:4;1:4] b = 1 2 3 4 1 2 3 4 >> a.*b ans = 1 4 9 16 5 12 21 32
  • 37. Sample Program % Program to accept input for the matrix A rows = input('Enter the number of rows: '); cols = input('Enter the number of columns: '); for a = 1:rows for b =1:cols A(a,b)=input('Enter number: '); end; end;
  • 38. Sample Program transpose = transpose(A) rot90 = rot90(A) lowertriangle =tril(A) uppertriangle = triu(A) determinant =det(A) inverse =inv(A) eigenvalues=eig(A) rank=rank(A) disp(A)
  • 39. Sample Program Enter the number of rows: 3 Enter the number of columns: 3 Enter number: 12 Enter number: 10 Enter number: 14 Enter number: 5 Enter number: 6 Enter number: 7 Enter number: 8 Enter number: 9 Enter number: 15 The given matrix is: 12 10 14 5 6 7 8 9 15
  • 40. Sample Program transpose = 12 5 8 10 6 9 14 7 15 rot90 = 14 7 15 10 6 9 12 5 8 lowertriangle = 12 0 0 5 6 0 8 9 15
  • 41. Sample Program uppertriangle = 12 10 14 0 6 7 0 0 15 determinant = 92 inverse = 0.2935 -0.2609 -0.1522 -0.2065 0.7391 -0.1522 -0.0326 -0.3043 0.2391 eigenvalues = 29.0862 2.7732 1.1406 rank = 3
  • 42. String Array Concatenation » str ='Hi there,'; » str1='Everyone!'; » new_str=[str, ' ', str1] new_str = Hi there, Everyone! » str2 = 'Isn''t MATLAB great?'; » new_str2=[new_str; str2] new_str2 = Hi there, Everyone! Isn't MATLAB great? » str ='Hi there,'; » str1='Everyone!'; » new_str=[str, ' ', str1] new_str = Hi there, Everyone! » str2 = 'Isn''t MATLAB great?'; » new_str2=[new_str; str2] new_str2 = Hi there, Everyone! Isn't MATLAB great? 1x19 vector 1x9 vectorsUsing [ ] operator: Each row must be same length Row separator: semicolon (;) Column separator: space / comma (,) For strings of different length: • STRVCAT • char » new_str3 = strvcat(str, str2) new_str3 = Hi there, Isn't MATLAB great? » new_str3 = strvcat(str, str2) new_str3 = Hi there, Isn't MATLAB great? 2x19 matrix 2x19 matrix (zero padded) 1x19 vectors
  • 43. Working with String Arrays String Comparisons strcmp: compare whole strings strncmp: compare first ‘N’ characters findstr: finds substring within a larger string Converting between numeric & string arrays: num2str: convert from numeric to string array str2num: convert from string to numeric array
  • 44. Sample Program %Program for sring manipulations str1 = input('Enter first string ','s'); str2 = input('Enter second string ','s'); str3 = input('Enter third string ','s'); catstr = strcat(strcat(str1,str2),str3); disp('The concatenated string is') disp(catstr) if strcmp(str1,str2) disp('The first two strings are same') else disp('The first two strings are not same') end;
  • 45. Logical Operations » Mass = [-2 10 NaN 30 -11 Inf 31]; » each_pos = Mass>=0 each_pos = 0 1 0 1 0 1 1 » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = 0 1 0 1 0 0 1 » Mass = [-2 10 NaN 30 -11 Inf 31]; » each_pos = Mass>=0 each_pos = 0 1 0 1 0 1 1 » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = 0 1 0 1 0 0 1 = = equal to > greater than < less than >= Greater or equal <= less or equal ~ not & and | or isfinite(), etc. . . . all(), any() find Note: • 1 = TRUE • 0 = FALSE
  • 46. Polynomials Polynomials Roots (>> roots) Evaluation (>> polyval) Derivatives (>> polyder) Curve Fitting (>> polyfit) Partial Fraction Expansion (residue) eg. p = [1 2 3 7 10] p = 1 2 3 7 10
  • 47. Polynomials >>roots(p) ans = 0.5408 + 1.7419i 0.5408 - 1.7419i -1.5408 + 0.7951i -1.5408 - 0.7951i >> polyder(p) ans = 4 6 6 7
  • 48. Control Structures if (Conditional statement) Matlab Commands end if (Condition_1) Matlab Commands elseif (Condition_2) Matlab Commands elseif (Condition_3) Matlab Commands else Matlab Commands end if (Conditional statement) Matlab Commands else Matlab Commands end If Statement Syntax
  • 49. Sample Program – Selection (IF) % Program to accept 3 numbers and display the largest no. fn = input('Enter first number:'); sn = input('Enter Second number:'); tn = input('Enter third number:'); if ((fn > sn)& (fn > tn)) disp('The largest number is') disp(fn) elseif (sn > tn) disp('The largest number is') disp(sn) else disp('The largest number is') disp(tn) end;
  • 50. Structures of control condicionated: switch  switch is similar to a sequence of if...elseif switch_expresion=case_expr3 switch switch_expresion case case_expr1, actions1 case {case_expr2, case_expr3,case_expr4,...} actions2 otherwise, actions3 end
  • 51. Sample Program – Selection (switch) % Program to accept a choice from the user and perform addition, subtraction, multiplication and division testflag = 1; disp('1.Add') disp('2. Subtract') disp('3. Multiply') disp('4. Divide') fn = input('Enter first number:'); sn = input('Enter second number:'); choice = input('Enter Choice'); switch choice case 1 add = fn+sn; disp('add =') disp(add)
  • 52. Sample Program – Selection (switch) case 2 disp('sub =') sub = fn - sn; disp(sub) case 3 disp('mul =') mul = fn*sn; disp(mul) case 4 disp('div =') div = fn/sn; disp(div) otherwise disp('Invalid Choice') testflag = 0; end;
  • 53. For loop syntax for i=Index_Array Matlab Commands end MATLAB Program  Write a program to find the sum of even numbers between 0 and 21 using the for loop. %Program to use for loop %File name example2_for.m Sum=0; for j=0:2:21 Sum=Sum + j; end Sum
  • 54. While Loop Syntax while (condition) Matlab Commands end MATLAB Program  Write a program to find the sum of even numbers between 0 and 21 using the fro loop. %Program to use while loop %File name example3_while.m n=0; Sum=0; while n<21 Sum=Sum + n; n=n+2; end Sum
  • 55. Sample Program – Iteration (while) % Program to accept a choice from the user and perform addition, subtraction, multiplication and division testflag = 1; disp('1.Add') disp('2. Subtract') disp('3. Multiply') disp('4. Divide') fn = input('Enter first number:'); sn = input('Enter Second number:'); while (testflag == 1) choice = input('Enter Choice'); switch choice case 1 add = fn+sn; disp('add =') disp(add)
  • 56. Sample Program – Iteration (while) case 2 disp('sub =') sub = fn - sn; disp(sub) case 3 disp('mul =') mul = fn*sn; disp(mul) case 4 disp('div =') div = fn/sn; disp(div) otherwise disp('Invalid Choice') testflag = 0; end; end;
  • 57. Graphics Fundamentals Basic Plotting plot, title, xlabel, grid, legend, hold, axis Editing Plots Property Editor Mesh and Surface Plots meshgrid, mesh, surf, colorbar, patch, hidden
  • 58. 2-D Plotting Example 1 x=[2004 2005 2006 2007 2008 2009]; y=[85 100 90 95 85 90]; plot(x,y) Example 2 f=50; w=2*pi*f; t=0:1e-3:0.04; x=w*t; y=sin(x); plot(t,y);
  • 59. Basic Task: Plot the function sin(x) between 0≤x≤4π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Plot the y-array >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) 0 10 20 30 40 50 60 70 80 90 100 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
  • 60. Plot the function e-x/3 sin(x) between 0≤x≤4π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Calculate e-x/3 of the x-array Multiply the arrays y and y1 >>x=linspace(0,4*pi,100); >>y=sin(x); >>y1=exp(-x/3); >>y2=y*y1;
  • 61. Plot the function e-x/3 sin(x) between 0≤x≤4π Multiply the arrays y and y1 correctly Plot the y2-array >>y2=y.*y1; >>plot(y2) 0 10 20 30 40 50 60 70 80 90 100 -0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
  • 62. Display Facilities plot(.) stem(.) Example: >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) >>plot(x,y) Example: >>stem(y) >>stem(x,y) 0 10 20 30 40 50 60 70 80 90 100 -0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0 10 20 30 40 50 60 70 80 90 100 -0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
  • 63. - Continue title(.) xlabel(.) ylabel(.) >>title(‘This is the sinus function’) >>xlabel(‘x (secs)’) >>ylabel(‘sin(x)’) 0 10 20 30 40 50 60 70 80 90 100 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 This is the sinus function x (secs) sin(x) >>grid;
  • 64. Formatting a plot >>Plot(x, y, ‘linespecifier’, ‘propertyname’, propertyvalue’) Line specifier Line style Marker style Colour - Solid . Point y Yellow : Dotted o Circle m Magenta - Dash-dot x X-mark c Cyan -- Dashed + Plus r Red <none> No line * Star g Green s Square b Blue d Diamond w White v Triangle(down) k Black ^ Triangle(up) < Triangle(left) > Triangle(right) p Pentagram h Hexagram <none> No marker
  • 65. - Continue Property name and value  LineWidth  MarkerEdgeColor  MarkerFaceColor  Markersize E.g.: f=50; w=2*pi*f; t=0:1e-3:0.04; x=w*t; y=sin(x); plot(t, y, ‘- - rs’, ‘LineWidth’, 2.5, ‘MarkerEdgeColor’, ‘k’, ‘MarkerFaceColor’, ‘g’, ‘MarkerSize’, 8);
  • 66. Multiple Plots Using plot command  Plot the voltage (v=5sinwt) and current(i=2sin(wt-Φ)) flow through a circuit on the common axis. %Multiple plot using plot command %Filename Example1_mp t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3; v=5*sin(w*t); i= 2*sin((w*t)-phi); plot(t,v,t,i) title(“Multiple plot using plot command’); xlabel(‘Time(sec)’); ylabel(‘Voltage & Current’); grid;
  • 67. - Continue Using hold command %Multiple plot using hold command %Filename Example2_mp t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3; v1=sin(w*t); plot(t,v1) hold on; % Retain the current plot and certain axes properties gtext(‘v1 = sin(wt)’); v2=cos(w*t); plot(t,v2) hold off; % Reset axes properties to their defaults before drawing new plot gtext(‘v2 = cos(wt)’); title(‘Multiple plot using hold command’); xlabel(‘Time(sec)’); ylabel(‘V1 & V2’); grid;
  • 68. - Continue Using line command >>line (xdata, ydata, parameter_name, parameter_value) %Multiple plot using line command %Filename Example3_mp t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3; v1=sin(w*t); v2=cos(w*t); plot(t, v1, ‘- -’); gtext(‘v1 = sin(wt)’); line(t,v2); gtext(‘v2=cos(wt)’); title(‘Multiple plot using hold command’); xlabel(‘Time(sec)’); ylabel(‘V1 & V2’); grid;
  • 69. Adding legend to a plot >> legend(‘string1’, ‘string2’,… pos) Value Position Value Position -1 Outside axis on the right side MC Middle and centre 0 Auto placement with least interferes with data ML Middle and left 1 Upper right corner of the plot (default) MR Middle and right 2 Upper left corner of the plot BL Bottom left 3 Lower left corner of the plot BC Bottom centre 4 Lower right corner of the plot BR Bottom right
  • 70. Formatting the text in Title, Labels and Legends Modifier Effect Character String Greek Letter bf Bold fonts alpha α it Italic fonts beta β rm Normal fonts gamma γ fontname Type of font used theta θ fontsize Size of font used phi Φ - Subscript Delta Δ ^ Superscript delta δ omega ω Omega Ω sigma σ Sigma Σ infty ∞ circ º
  • 71. Special plots >>subplot(p, r, r) E.g.: subplot(2,1,1); plot(t,v); subplot(2,1,2); plot(t,i); >>semilogx(x, y); semilogy(x, y); loglog(x,y) % Logarithmic plot of a function % File name example4_sp x=linspace(0.1,60,1000); y=3.^(-0.2*x+10)-5; subplot(2,2,1), plot(x,y); title(‘plot(x,y)’); xlabel(‘Linear’); ylabel(‘Linear’); grid; subplot(2,2,2), semilogx(x,y); title(‘Semilogx(x,y)’); xlabel(‘Log’); ylabel(‘Linear’); grid; subplot(2,2,3), semilogy(x,y); title(‘Semilogy(x,y)’); xlabel(‘Linear’); ylabel(‘Log’); grid; subplot(2,2,4), loglog(x,y); title(‘Loglog(x,y)’); xlabel(‘Log’); ylabel(‘Log’); grid;
  • 72. - Continue >>bar(x,y); %Vertical bar chart >>barh(x,y); %Horizontal bar chart >>stairs(x,y); %Stairs plot >>stem(x,y); %Stem plot >>pie(x); % Pie plot >>pie(x, explode); %Pie plot with explode
  • 73. Specialized Plotting Routines bar; bar3h; hist; area; pie3; rose
  • 74. Plotting a complex data Both real and imaginary can be plotted with respect to time >> plot(t, real(x)); >>plot(t, imag(x)); Real part can be plotted versus imaginary part >>plot(x) Complex function can be directly plotted as a polar plot in terms of magnitude versus angle >>polar(angle(x), abs(x))
  • 75. - Continue…  E.g.: - x(t)=e-0.2t (sint + jcost) for (0≤t ≤ 2π) %Plot the complex function %File name example_cf % Real & Imaginary w.r.t time t=0: pi/20 : 2*pi; x=exp(-0.2*t) .* (sin(t) + i*cos(t)); figure(1); plot(t, real(x), ‘-.’); hold on; plot(t, imag(x), ‘r’); title(‘Plot of complex data versus time’); xlabel(‘bfTime’); ylabel(‘bfx(t)’); legend(‘real’, ‘imaginary’); grid;
  • 76. - Continue… % Real versus imaginary figure(2); plot(x); title(‘Plot of complex data’); xlabel(‘bfReal part’); ylabel(‘bfImaginary part’); grid; % Polar plot figure(3); polar(angle(x), abs(x)); title(‘Plot of complex data as polar plot’); grid;
  • 77. Plotting a function >> command(‘fun’, limits, linespecifiers) ◦ Command: ezplot or fplot ◦ fun: Function to be plotted ◦ limits: Limits of plot(optional) ◦ Linespecifiers: Type and colour of the line and marker (optional) E.g: - Plot the function f(x) = 0.2x+(sin(2x)/x) >>ezplot(‘(0.2*x)+(sin(2*x)/x)’); >> fplot(‘(0.2*x)+(sin(2*x)/x)’); >> fplot(‘(0.2*x)+(sin(2*x)/x)’, [-2*pi 2*pi]); >> fplot(‘(0.2*x)+(sin(2*x)/x)’, [-2*pi 2*pi –pi pi]);
  • 78. 3-D plotting >>Plot3(x, y, z, ‘linespeicifiers’, ‘propertyname’, ‘propertyvalue’) E.g.: x(t) = √tcos2t; y(t) = √tsin2t; %3-D plot %plot3 command % file name example_3d t=0: 0.1: 10; x=sqrt(t).*cos(2*t); y=sqrt(t).*sin(2*t); plot3(x,y,t); title(‘bf 3-D Plot’); xlabel(‘x’); ylabel(‘y’); zlabel(‘time’); grid;
  • 79. Surface plot Example x = 0:0.1:2; y = 0:0.1:2; [xx, yy] = meshgrid(x,y); zz=sin(xx.^2+yy.^2); surf(xx,yy,zz) xlabel('X axes') ylabel('Y axes') x = 0:0.1:2; y = 0:0.1:2; [xx, yy] = meshgrid(x,y); zz=sin(xx.^2+yy.^2); surf(xx,yy,zz) xlabel('X axes') ylabel('Y axes')
  • 80. 3-D Surface Plotting contourf; colorbar; plot3; waterfall; contour3; mesh; surf
  • 81. MATLAB Function Programming Functions and function files >>function[output_argument]=function_name(input_argument); >>function[output_argument1, output_argument2 …. ] =function_name(input_argument1, input_argument2….); E.g.: Write a program to solve the function By writing a function file with ‘fun_1’, with the input to the function is y and output f(y) for following values of x; a) f(y) for y=4 b) f(y) for y=2, 4, 6, 8, 10
  • 82. %Program to solve y(x) using function approach Y=input(‘Enter the value of Y:’); X=fun_1(Y); disp(X); %Function file fun_1 function X = fun_1(Y); X=(Y.^3.*sqrt(2*Y+4))./(Y.^3+1).^2;
  • 83. Differential equation solver ODE - Ordinary Differential Equations MATLAB ODE Solvers Solver Problem type /Accuracy Description ode23 Non-stiff /Medium One-step solver based on explicit Runge-Kutta (II and III) method. In general faster but less accurate than ode45 ode45 Non-stiff /Low One-step solver based on explicit Runge-Kutta (IV and V) method. In general moderate accuracy ode113 Non-stiff /Low to high Multi-step solver based on Adams method ode15s Stiff /Moderate Multi-step solver of variable order (I to V) ode23s Stiff /Low One-step low order solver based on a modified Rosenbrock formula of order two ode23t Moderately stiff /Low One-step solver based on trapezoidal rule ode23tb Stiff /Low A low order solver, more efficient than ode15s ode15i Solves fully implicit differential equations, variable order method
  • 84. ODE solver syntax ODE = dy/dt = f(t, y) >>[t, y] = solver_name(‘function’, tspan, y0); E.g.:1) for 1≤ t ≤ 2 with initial condition y1=2.3 at t=0 for 1≤ t ≤ 2 with initial condition y2=1.2 at t=0 % create function file function y1dot = ode_fun_1(t, y1) % Save file name ode_fun_1.m y1dot = (t^2-2*y1)/t; function y2dot = ode_fun_2(t, y2) % Save file name ode_fun_2.m y2dot = (t^2-2*t)/t; % Solve ODE >>[t, y1] = ode45(‘ode_fun_1’, [1:0.2:2], 2.3); >>[t, y2] = ode45(‘ode_fun_2’, [1:0.2:2], 1.2);
  • 85. - Continue  E.g.:2) Write a program to find the step response of RL circuit for the time range 0 to 1 sec with initial condition i=1 amps at t=0. V = iR + L (di/dt); di/dt = (V-iR) / L % Program to plot step response of series RL circuit close all; clear; clc; global R L V R = 2; L=100e-3; V=10; [t i] = ode45(‘RL_series’, [1:0.01:1], 1); plot(t, i); grid; xlabel (‘Time(sec)’); ylabel (‘Current(amps)’); %Function file RL_series function idot = RL_series (t, i) global R L V idot = (1/L)*(V-i*R);
  • 86. Calculus functions Differentiation >>diff(y) % dy/dx >>diff(y,x) % dy/dx >>diff(y,a) % dy/da >>diff(y,t,2) % d2 y/dt2 Integration >> int(y) >> int(y,t) >> int(y, a, b) >> int (y, t, a, b)
  • 87. Symbolic math functions Sym  x = sym(x) >>a=5; b=sqrt (sym(a)) >>a=2/3; b=3/4; x = sym(a) + sym(b) >>syms a b c; x = a^2 + 2*b + c >>subs(x, a, 2) >>subs(x, 2) >>findsym(x) >>findsym(x, 2)
  • 88. ASSIGNMENT – MATLABASSIGNMENT – MATLAB OVERVIEWOVERVIEW  Accept the roll number, name, 3 subject marks of a student and print the details of the student with total and average.  For problem (1), print the grade of the student as pass(average>=50) or fail (average<50). Use If statement  For problem (1), print the grade of the student as Distinction (average>=90), First Class (average >=80 and <90), Second Class(average >=70 and <80), Third Class (average>=60 and <70) otherwise Fail. Use nested if statement  Accept a number and based on the choice of the user display the square, cube, and quadruple of the number. Use Switch case  Count the number of Vowels in a given string Find the total number of characters in a given string
  • 89. - Continue …  Check whether the original string and the reversed string are same. If so, display palindrome string else not a palindrome string.  Generate the Fibonacci Series 0 1 1 2 3 5 8 …N  Check whether the given number is perfect square (Number divisible by 1 and itself)  List all Prime numbers between 1 and 100  Consider 3 subject marks for a student and use bar chart to represent.  Consider a subject mark for 5 students and use bar chart to represent  Perform Matrix Addition (Size mxn)  Find the roots and derivatives of the polynomial accepted from the user.  Concatenate two vectors and sort.