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.
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.
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
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;
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
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
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;
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
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 º
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]);
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.