Faculty Upskilling Programme
on
Mathematical Computation using
MATLAB
1
Basic Plotting Functions
Creating a Plot
Multiple Data Sets in a Graph -line styles and
colors
Plotting Lines and Markers
Adding Plots to an Existing Graph - Figure
Windows
Displaying Multiple Plots in One Figure
Controlling the Axes
Adding Axis Labels and Titles
Saving Figures
2
Different forms of plot function ---depending on the input
arguments.
If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y
versus the index of the elements of y.
If two vectors as arguments,
plot(x,y) produces a graph of x versus y.
3
Creating a Plot
Create a vector of ‘x’ values ranging from 0 to 2π, compute
the sine of these values, (i) plot the result and (ii) Label the
axes and add a title.
1.571Rad × 180/π = 90.05Deg
4
Multiple Data Sets in a Graph -
line styles and colors
Plotting Multiple Data Sets in One Graph
x = 0: pi/100: 2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
legend ('sin(x)','sin(x-.25)','sin(x-.5)'
5
Specifying Line Styles, Colors and
Markers
Specify color, line styles, and markers (such as plus signs or
circles)
plot command:
plot(x,y,'color_style_marker')
color_style_marker is a string (enclosed in single quotation
marks)
Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'.
correspond to cyan, magenta, yellow, red, green, blue, white,
and black.
6
Line Styles and Markers
• Line style strings are
'-' for solid,
'--' for dashed,
':' for dotted,
'-.' for dash-dot.
The marker types are
• '+', 'o', '*',and 'x',
Marker types 's' for square,
'd' for diamond,
'^' for up triangle,
'v' for down triangle,
'>' for right triangle,
'<' for left triangle,
'p' for pentagram,
'h‘ for hexagram,
none for no marker
7
plot(x,y,'k-s')----plots black squares at each data point,
with a line
.
8
x1 = 0: pi/100: 2*pi;
x2 = 0: pi/10: 2*pi;
plot (x1, sin(x1),'r-s', x2,cos(x2),'b-+')
9
Adding Plots to an Existing Graph
The hold on command enables you to add plots to an existing
graph
Type hold on
x1 = 0: pi/100:2*pi;
plot (x1, sin(x1),'r-')
hold on
x2 = 0: pi/10:2*pi;
plot (x2, cos (x2),'b+-')
10
To open a new figure window
figure(n) ----where n is the number in the figure title bar.
To open a new figure window - type figure
x1 = 0: pi/100: 2*pi;
figure
plot (x1, sin(x1),'r-')
figure
x2 = 0: pi/10: 2*pi;
plot (x2, sin(x2),'b+')
11
Multiple plots in the same window
subplot(m,n,p)
Enables to display multiple plots in the same
window.
Partitions the figure window into an m-by-n matrix
of small subplots
p- position of subplot.
12
Plot 2 graphs in a single window
x1 = 0: pi/100:2*pi;
y= sin(x1);
subplot (1,2,1)
plot (x1, y,'r.')
x2 = 0: pi/10:2*pi;
y2= cos(x2);
subplot(1,2,2)
plot (x2, y2,'b+-')
13
Setting Axis Limits -axis([xmin xmax ymin ymax])
Ex: axis([1 6 -1.5 1.5]) (use after plot command)
Setting Grid Lines
grid on (use after plot comment)
14
Plot a square wave of period 2 seconds, with step
0.01 second , amplitude from -2 to 2 and 50% duty
cycle?
function--> square(2*pi*f*t)
15
Plot a square wave of period 2 seconds, with step 0.01
second , amplitude from -2 to 2 and 50% duty cycle?
duty = 50;
t = 0 : 0.01 : 8;
f = 0.5;
x = 2*square(2*pi*f*t,duty);
plot(t,x, 'LineWidth',3)
axis([0 8 -2.5 2.5])
grid on
16
Bar & Pie chart
x=[1,2,3,4,5]
y=[10,20,30,40,50]
bar (x,y)
x= [2 3 4 5]
y= {'North','South','East','West'}
pie(x,y)
17
• Mesh plot
The mesh and surf plotting functions display
surfaces in three dimensions.
Evaluate the function over the range 0 < x < 1, 0 < y < 1,
[X,Y] = meshgrid (0:0.5:1);
R = sqrt(X.^2 + Y.^2) ;
mesh (X,Y,R)
colorbar
18
Tutorial
1. Plot the simple function y = x for the range of
values for x from 0 to 50, with an increment of 5.
2. Draw the graph of two polynomials
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
g(x) = 5x3 + 9x + 2
Let
x= [-10 : 0.01: 10]
3. Plot the simple function y = x3 for the range of
values for x from 0 to 20, with an increment of 2.
19
x = [Link];
y = x;
plot(x, y)
20
x = [-10 : 0.01: 10];
f = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;
plot(x, y, 'r', x, g, 'g')
21
Editing plots
Figure window----->Figure Toolbar
plot edit toolbar
Figure palette
plot browser
property editor
22
Editing plots
To enable edit plot , click the arrowhead in the figure
toolbar:
23
Using the Property Editor
24
Changing the Appearance of Lines and Markers
Line to no line g = -1:.1:1;
Marker to o (circle)
f = g.^3;
plot (f,g)
Marker size to 4.0
Marker fill color to red
Proprty editor-- >
double click the
waveform
25 Setline tonoline. SetMarkerfillcolortored.
SetMarkersizeto4.0.
Plotting Two Variables with Plotting Tools
Plot the function f = g3. Range of ‘g’ is -1 to 1.
g = -1:.1:1;
f = g.^3;
To start the plotting tools, type--> plottools in
command window
MATLAB displays a figure with plotting tools attached.
26
27
Adding More Data to the Graph
28
Changing the Type of Graph
Select Stem from the Plot Type menu
29 SelectStemasthePlotType.
Modifying the Graph Data Source
x = linspace(-3*pi, 3*pi, 50);
ys = sin(x);
yc = cos(x);
type--> plottools in command window
30
31
Annotating Graphs for Presentation
Mark- comments
32
Programming
Flow control
if, switch-case, for, while, continue
Data Structures
Multidimensional arrays, character and text data.
33
Flow Control
“Conditional Control – if, else, switch”
“Loop Control – for, while, continue
34
Conditional Control
if, else, and elseif
The if statement evaluates a logical expression and executes a
group of statements when the expression is true.
The optional elseif and else keywords provide for the execution
of alternate groups of statements.
An end keyword, which matches the if, terminates the last group
of statements.
If (condition)
Statement
else
Statement
end
35
Calculate the square root of the variable x only when the
value of x is non-negative.
x=input ('Enter the number=')
if x >= 0
y = sqrt (x)
end
36
1. Find A >B or A<B or A=B using “elseif”
2. Check whether the given number is less than or
greater than 10
3. Find whether the given number is odd or even?
4. Grading the marks obtained
37
Find A >B or A<B or A=B using “elseif”
A=input ('Enter the first number=')
B=input ('Enter the second number=')
if A > B
disp ('A is greater than B')
elseif A < B
disp ('A is less than B')
elseif A == B
disp ('A is equal to B')
end
38
Check whether the given number is less than
or greater than 10
a = 12
if ( a < 10 )
disp ( ' number is less than 10 ' )
else
disp ( ' number is larger than 10 ' )
end
39
Find whether the given number is odd or even?
n=input('Enter the number=')
if rem(n,2) == 0
disp ('The number is even')
else
disp ('The number is odd')
end
40
Grading the marks obtained
a = input('Enter the marks obtained=')
if ( a >= 91 ) && (a<=100)
disp ( 'Grade=O' )
elseif ( a >= 81 )
disp ( 'Grade=A' )
elseif ( a >= 71 )
disp ( 'Grade=B' )
elseif ( a >= 61 )
disp ( 'Grade=C' )
elseif ( a >= 51 )
disp ( 'Grade=D' )
else
disp ( 'Fail' )
end
41
for loop
Repeating a group of statements a fixed number of times
n=input('Enter the value of n=')
s = 0;
for k = 1:n
s = s + k^2;
end
disp (s)
42
Calculate the factorial n!.
n=input ('Enter the value of n=')
f = 1;
for k = [Link]n
f = f*k;
end
display(f)
3! = 1*2*3 =6
43
While Loop
Repeats a group of statements an indefinite
number of times under control of a logical
condition.
Termiated with end statement.
While is the keyword for while loop.
An expression is a condition that needs to be true for the
while loop to work.
44
Print the values which are less than 20
a = input('Enter the value of a')
while( a < 20 )
fprintf ('value of a: %d\n', a);
a = a + 1;
end
45
Find the factorial
n = 3;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(f)
46
SWITCH -CASE
Switch among several cases based on expression.
The switch statement executes groups of statements based on the value
of a variable or expression.
keywords- case and otherwise .
Only the first matching case is executed.
switch
case case_condition
statements_if_true
case case_condition
statements_if_true
...
Otherwise
Statements
end
47
Display the number with sign.
n = input('Enter a number: ');
switch n
case -1
disp('negative one')
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp ('other value')
end
48
1. Choose the type of plot (bar chart& pie chart)
2. Remarks for the grade obtained.
49
Choose the type of plot
x = [12 64 24];
plottype = input('Enter plot type=');
switch plottype
case 1
bar(x)
title('Bar Graph')
case 2
pie(x)
title('Pie Chart')
end
50
grade = input ('Enter grade=');
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Well done\n' );
case 'D'
fprintf('You passed\n' );
case ‘F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end
51
Read in angle and user choice or trig function
angleDegrees = input('Enter angle in degrees: ');
choice = input ('Enter the choice')
% result = 0;
type = "";
% compute selected trigonometric function
switch (choice)
case {1}
result = sind(angleDegrees);
type = "sin";
case {2}
result = cosd(angleDegrees);
type = "cos";
case {3}
result = tand(angleDegrees);
type = "tan";
end
52
fprintf('%s(%0.1f) = %0.2f\n',type, angleDegrees, result)
Continue statement
The continue statement passes control to the next iteration of
the for loop, skipping any remaining statements in the Body of the loop.
Display the multiples of 7 from 1 through 50.
If a number is not divisible by 7, use continue to skip the disp statement
and pass control to the next iteration of the for loop.
for n = 1:50
if mod (n,7) % mod-modulo operation
continue
end
disp(['Divisible by 7: ' num2str(n)])
end
53
Data Structures
Multidimensional Arrays”
• “
• “Characters and Text”
• A multidimensional array - an array with more than two dimensions.
• Matrix -two dimensions are represented by rows and columns.
• Each element is defined by two subscripts, the row index and the column index.
54
Create a 3-by-2-by-3 array of random numbers.
X = randn([3,2,3])
X(:,:,1) =
0.7394 -2.1384
1.7119 -0.8396
-0.1941 1.3546
X(:,:,2) =
-1.0722 1.4367
0.9610 -1.9609
0.1240 -0.1977
X(:,:,3) =
-1.2078 1.3790
2.9080 -1.0582
55 0.8252 -0.4686
To generate an array filled with a single constant value
B = repmat(5,[3 4 2])
B(:,:,1) =
5 5 5 5
5 5 5 5
5 5 5 5
B(:,:,2) =
5 5 5 5
5 5 5 5
5 5 5 5
56
57
s = whos(...) returns a structure with these fields
name variable name
size variable size
bytes number of bytes allocated for the array
class class of variable
Array concatenation
A = cat(3,[1 2 3;9 8 7;4 6 5],[0 3 2;8 8 4;5 3 5],[6 4 7;6 8
5;5 4 3]);
58
s=
Hello
Characters and Text
a=
s = 'Hello' 72 101 108 108 111
a = double(s) s=
s = char(a) Hello
h = [s, ' world']
v = [s; 'world']
joins the strings horizontally and produces
h = [s, ' world']
h= Hello world
v = [s; 'world']-joins the strings vertically and produces
v=
Hello
59
world
Program files
Scripts and Functions
• M-file
• pass string arguments to functions
• global variables declaration
(i) Scripts -simply execute a series of MATLAB statements,
(ii) functions - accept input arguments and produce output.
Both scripts and functions contain MATLAB code
Both are stored in text files with .m extension.
Functions are more flexible and more easily extensible.
60
Create M-files using a text editor.
There are two kinds of M-files:
• Scripts,
• Functions.
•Scripts- do not accept input arguments or return
output arguments.
• They operate on data in the workspace.
• Functions- can accept input arguments and return
output arguments.
61
Syntax for Function Definition
The first line of every function is the definition statement, which includes the
following elements
function keyword Use lowercase characters for the keyword.
(required)
Output arguments If function returns one output, you can specify the output
(optional) name after the function keyword.
function myOutput = myFunction(x)
If function returns more than one output, enclose the
output names in square brackets.
function [one,two,three] = myFunction(x)
If there is no output
function myFunction(x)
Or you can use empty square brackets.
function [] = myFunction(x)
62
Input arguments If function accepts many inputs, enclose their names
(optional) in parentheses after the function name.
Separate inputs with commas.
function y = myFunction(one,two,three)
63
Inbuilt functions
% rank of matrix
a=[1 2 3; 4 5 6; 7 8 9]
r = rank (a)
64
Calculate the square of the given number 'x'
function y = square(x)
y = x*x;
End
Save as ---square
Type square(5) in the command window
main program in a separate M-file
n=input('enter the value=')
y=square(n)
65
User defined function
66
%This function calculates the maximum of the five numbers as
input
function max = mymax (n1, n2, n3, n4, n5)
max = n1;
If (n2 > max)
max = n2;
end
If (n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end
File name- mymax
67 Type ---mymax (34, 78, 89, 23, 11) in Command window
Functions are M-files that can accept input arguments and
return output arguments.
Primary and Sub-Functions
Anonymous Functions
Nested Functions
68
Quadratic eqn
D=
Roots X1= -b+D/2a
X2= -b-D/2a
69
Primary and Sub-Functions
The function file quadratic.m will contain the primary
function quadratic and the sub-function disc, which calculates the
discriminant.
Create a function file quadratic.m and type the following code in it −
function [x1,x2] = quadratic(a,b,c)
d = disc (a,b,c);
x1 = (-b + d) / (2*a)
x2 = (-b - d) / (2*a)
end
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt (b^2 - 4*a*c);
end
Type – quadratic (2,4,-4) in command window
70
Anonymous Functions
Does not require an M-file.
It consists of a single MATLAB expression and
any number of input and output arguments.
can define it in the MATLAB command line, or
within an M-file function or script.
To execute the square function
a = sqr(5)
Ans a=25
Power
power(7, 3)
71
Nested Functions
Define functions within the body of another function. These are called
nested functions.
Create a function file quadratic2.m and type the following code in it −
function [x1,x2] = quadratic2(a,b,c)
d = sqrt(b^2 - 4*a*c);
function disc % nested function
end % end of function disc
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2
You can call the above function from command prompt as –
72
quadratic2(2,4,-4)
A nested function follows the following syntax −
function x = A(p1, p2)
...
B(p2)
function y = B(p3)
...
end
...
end
73
Global Variables
Global variables can be shared by more than one function.
Need to declare the variable as global in all the functions.
Create a script file and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
create a function file named average.m
f
When you run the file, it will display the following result −av = 35.500
74
The global declaration must occur before the
variable is actually used in a function.
Use capital letters for the names of global variables
to distinguish them from other variables.
75