Faculty Upskilling Programme On: Mathematical Computation Using Matlab
Faculty Upskilling Programme On: Mathematical Computation Using Matlab
on
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.
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.
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.
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)
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])
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,
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.
19
x = [0:5:50];
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
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
g = -1:.1:1;
f = g.^3;
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);
30
31
Annotating Graphs for Presentation
Mark- comments
32
Programming
Flow control
33
Flow Control
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.
36
1. Find A >B or A<B or A=B using “elseif”
37
Find A >B or A<B or A=B using “elseif”
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?
40
Grading the marks obtained
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!.
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.
44
Print the values which are less than 20
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.
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.
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”
• “
• 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']
60
Create M-files using a text editor.
There are two kinds of M-files:
• Scripts,
• Functions.
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
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.
68
Quadratic eqn
D=
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
71
Nested Functions
Define functions within the body of another function. These are called
nested functions.
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.
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