Advanced MATLAB Code
Advanced MATLAB Code
3
OBJECTIVE: Study about the function and sub-function and write the MATLAB program to
perform the following tasks:
3.1 Write a code to print the prime numbers from one to hundred.
3.2 Write a function which accepts the radius of the circle as input and returns the area and
perimeter of the circle.
3.3 Write a code which will compute sum of integers ranging from 1 to 100.
input to the code should be (i)
Weight and (ii) Height of the person. The output of t
.
3.5 Write a program to convert the temperature in degrees to Celsius.
3.6 Write a program to check whether the given string (word) is
palindrome or not?
3.7 Find the roots of the polynomial
3.8 Analyze the RLC Circuit using suitable value of R L and C.
3.9 Analyze the function using Taylor series.
(and Sometimes complex) sequences of statements. This can be done by writing the
-
be
for these files to be interpreted by MATLAB.
There are two types of m-files: script files and function files. Script files contain a sequence
of usual MATLAB commands, that are executed (in order) once the script is called within
40
MATLAB. For example, if such a file has the name compute.m , then typing the command
compute at the MATLAB prompt will cause the statements in that file to be executed.
Script files can be very useful when entering data into a matrix.
Function files, on the other hand, play the role of user defined commands that often have input and
output. You can create your own commands for specific problems this way, which will have the
same status as other MATLAB commands.
The text below is The name of that file saved in a file called fahr_to_kelvin.m and it is used to
convert temperature in Fahrenheit to kelvin. Function name must be the same as the function
defined inside it. The name must start with a letter and cannot contain spaces.
41
ans = 273.15
When we pass a value, like 32, to the function, the value is assigned to the variable ftemp so that
it can be used inside the function. If we want to return a value from the function, we must assign
that value to a variable named ktemp in the first line of our function, we promised that the
output of our function would be named ktemp.
Outside of the function, the variables ftemp and ktemp
function body to refer to the input and output values.
This is one of the major differences between scripts and functions: a script can be thought of as
automating the command line, with full access to all variables in the base workspace, whereas a
function can only read and write variables from the calling workspace if they are passed as
arguments i.e. a function has its own separate workspace.
A function can have multiple input and outp
any of either. The general form of a function is shown in the pseudo-code below:
function [out1, out2] = function name (in1, in2)
%FUNCTION_NAME Function description
3.1 Write a code to print the prime numbers from one to hundred.
Program:
function [Prime] = PrimeNum (N, M)
N =input('Enter num1 value ');
M =input ('Enter num2 value ');
n = N: M;
p = isprime(n);
[Prime]= n(p);
end
3.2 Write a function which accepts the radius of the circle as input and returns the area
and perimeter of the circle.
Program:
function [Circumference, area] = circle(r)
Circumference = 2*pi*r;
area = pi*r.^2;
end
42
3.3 Write a code which will compute sum of integers ranging from 1 to 100.
Program:
function out = num(M,N);
M= input('enter the first number =');
N= input('enter the second number =');
D=M: N;
out = sum(D);
end
Program:
function bmi = bodymassindex(height, weight)
height = input('height in meters = ') ;
weight = input('weight in kg = ') ;
bmi = weight/(height^2);
end
3.6 Write a program to check whether the given string (word) is palindrome or not?
Program:
function output = isPalindrome(yourString)
lastIndex=floor(length(yourString)/2);
for k=1:lastIndex
if yourString(k)~=yourString(end+1-k)
output = false;
else
output = true;
end
end
43
3.7 Find the roots of the polynomial
Program:
function polyroots = polynomial(x)
x= [3 15 0 10 0 4 0];
polyroots = roots(x);
end
3.8 : An R-L-C circuit has R = 180 ohms, C = 1/280 farads, L = 20 H and an applied voltage
E(t) = 10 sin t. Assuming that no charge is present but an initial current of I ampere is flowing
at t = 0 when the voltage is first applied, find q and at any time t. q is given by the
differential equation.
Program:
function [qSol,i]=rlc(L,R,C)
syms q(t)
L=input('enter Inductance value in henry L=');
R=input('enter Resistance value in ohms R=');
C=input('enter Capacitance value in farad C=');
Dq = diff(q,t);
eqn = L*diff(q,t,2)+ R*Dq+ (1/C)*q == 10*sin(t);
cond = [q(0)==0, Dq(0)==5];
qSol(t) = dsolve(eqn,cond);
i = diff(qSol,t);
end
Write a user-defined function file that calculates sin(x) by using the Taylor series.
Program:
function siny = taylorseries_sin(x)
n = input('Enter number of iiterations (n): ' );
for i = 0:n
y(i+1) = (-1)^i*x^(2*i+1)/factorial(2*i+1);
end
siny = sum(y);
end
44
EXPERIMENT NO. 4
OBJECTIVE: Study about the flow control and file and write the MATLAB program to
perform the following tasks:
4.1. Without using the max command, find the maximum value of matrix (a) where a=[11
3 14; 8 6 2; 10 13 1];
4.2 Prove that y is not the inverse matrix of x
4.3. Write a MATLAB program in M -File to do the following steps:
, if
1, if
4.4 Use a for-end loop in a script file (.m file) to calculate the sum of the first terms of
the series:
SOFTWARE REQUIRED:
45
4.1. Without using the max command, find the maximum value of matrix (a) where a=[11
3 14; 8 6 2; 10 13 1];
Program:
8 6 2
10 13 1
Commands:
Clear all;
for k=1:length(a(:,1)) %The for loop will traverse through each row
for m=1:length(a(1,:)) % The for loop will traverse through each element
present in a row
end
end
end
Results:
46
4.2 Prove that y is not the inverse matrix of x
Let x=[2 6; 1 8], prove that y=[8 -0.3; -0.1 0.2] is not the inverse matrix of x.
Program:
clear all;
x=[2 6; 1 8
y=[8 -0.3;-0.1 0.2];
xinv=inv(x); % The MATLAB command for finding the inverse of a matrix
compareresult=(xinv==y); % Rational comparison operator to check whether
two given %matrices are equal or not
disp('The inverse matitix of [x] is:'); disp(xinv);
disp('The given matrix [y] is:'); disp(y);
disp('The logical matrix showing the result of comparison of y and
[xinv]:'); disp(compareresult); % Displaying the logical matrix showing the
result of the %comparison
Output:
, if
1, if
47
Program:
clear all;
x=input('Enter the value of x '); %Input is the Matlab function used for
requesting %user to enter the value of x
y=input('Enter the value of y '); %Requesting user to enter the value of y
z=input('Enter the value of z '); %Requesting user to enter the value of z
if(y<=4*x*z) %Condition 1
s=sqrt(y^2-4*x*z);
else %Condition 2
s=1;
end
disp('x=');disp(x) % Displaying value of x
disp('y=');disp(y) % Displaying value of y
disp('z=');disp(z) % Displaying value of z
disp('s=');disp(s) % Displaying value of s
Output:
4.4 Use a for-end loop in a script file (.m file) to calculate the sum of the first terms of the
series:
48
Program:
GIVEN RELATION:
, for 4
, for 20
COMMANDS:
clear all;
n=[4 20]; % The given values of n
for i=1:length(n) %This loop will consider the values of n one by one
sum=0; % Initialize the variable sum=0
for k=1:n(i) % For loop to compute sum of the series with limit 1 to n
sum=sum+(((-1)^k)*k)/(2^k); % Computation of sum of the series
end
sumfinal(i)=sum; %Storing sum of the series corresponding to each value
of n in the %variable sumfinal
end
fprintf('The sum of the given series for n = %1.0f is: %f\n', n(1),
sumfinal(1)); %Displaying the sum using the fprintf function
fprintf('The sum of the given series for n = %1.0f is: %f\n', n(2),
sumfinal(2)); %Displaying the sum using the fprintf function
Output:
end
49
Program:
GIVEN RELATION:
(a) If switch is open then A
If switch is closed then and A
50
%Enter ctrl+C to terminate the while loop
RESULTS:
51
EXPERIMENT NO. 5
OBJECTIVE: Study about the plotting and simulink and write the MATLAB program to
perform the following tasks:
5.1. The expression for sine wave is given by x( ¢) = Asin(27ft + ¢) .Write a code which
accepts the input as (i ) Amplitude (A) (ii) Frequency (f) and (iii) Phase(¢ )and generates
the sine wave. Plot the sine wave
5.2 Write a program to convert the sine wave to (i) Half wave rectified sinewave and (ii) Full
wave rectified sine wave
5.3 Write a program which converts the sine wave to a square wave Equivalent to that of
-
5.4. Write a program to generate three-phase sinusoidal signal. The students Should know what
is the phase difference between three phases in a three-phase sinusoidal signal and the
importance of three phase power
5.5. Design a Simulink block for power electronic circuits
SOFTWARE REQUIRED:
5.A Introduction to different types of plot and steps to follow to plot the graphs.
5.A.1 To plot the graph of a function, you need to take the following steps
Define x, by specifying the range of values for the variable x, for which the function is to
be plotted
Define the function, y = f(x)
Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y = x for the
range of values for x from 0 to 100, with an increment of 5.
52
Create a script file and type the following code
x = [0:5:100];
y = x;
plot(x, y)
x = [-100:5:100];
y = x.^2;
plot(x, y)
5.A.2 Adding Title, Labels, Grid Lines and Scaling on the Graph
MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust
the axes to spruce up the graph.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The title command allows you to put a title on the graph.
53
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale factors and the
spaces on both axes.
The axis square command generates a square plot.
x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
5.A.3 Example
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
54
5.A.4 Example
Let us draw the graph of two polynomials
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
g(x) = 5x3 + 9x + 2
55
plot(x, y, 'r', x, g, 'g')
5.A.5 Example
x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])
56
Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is called a subplot.
The subplot command is used for creating subplots.
subplot(m, n, p)
clc
clear all
close all
n=-10:1:10;
x=zeros(1,length(n));
u=zeros(1,length(n));
x(n==0)=1;
subplot(2,2,1)
stem(n,x);
xlabel('time')
ylabel('Amplitude')
title('Impuse Signal \delta(n)')
u(n>=0)=1;
subplot(2,2,2)
stem(n,u);
xlabel('time')
ylabel('Amplitude')
title('Unit Step Signal u(n)')
r=n.*u;
57
subplot(2,2,3)
stem(n,r);
xlabel('time')
ylabel('Amplitude')
title('Unit ramp Signal r(n)')
p=n.^2/2.*u;
subplot(2,2,4)
stem(n,p);
xlabel('time')
ylabel('Amplitude')
title('Unit Parabolic Signal p(n)')
This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will
58
5.A.6 Drawing Bar Charts
The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate
the idea.
5.A.7 Example
Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by
these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this
data.
x = [1:10];
y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
bar(x,y), xlabel('Student'),ylabel('Score'),
title('First Sem:')
print -deps graph.eps
When you run the file, MATLAB
Drawing Contours
A contour line of a function of two variables is a curve along which the function has a constant
value. Contour lines are used for creating contour maps by joining points of equal elevation above
a given level, such as mean sea level.
MATLAB provides a contour function for drawing contour maps.
59
5.A.8 Example
Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This
function has two variables. So, we will have to generate two independent variables, i.e., two data
sets x and y. This is done by calling the meshgrid command.
The meshgrid command is used for generating a matrix of elements that give the range over x
and y along with the specification of increment in each case.
60
Three Dimensional Plots
Three-dimensional plots basically display a surface defined by a function in two variables, g = f
(x,y).
As before, to define g, we first create a set of (x,y) points over the domain of the function using
the meshgrid command. Next, we assign the function itself. Finally, we use the surf command
to create a surface plot.
5.A.9 Example
Let us create a 3D surface map for the function g = xe-(x2 + y2)
Create a script file and type the following
[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g)
When you run the file, MATLAB displays the following 3-
61
You can also use the mesh command to generate a three-dimensional surface. However,
the surf command displays both the connecting lines and the faces of the surface in color,
whereas, the mesh command creates a wireframe surface with colored lines connecting the
defining points.
62
The definition of a block is only complete with its inputs and outputs defined; this task relates to
the goal of the model. For example, the cart velocity may be a natural choice as an output if the
modeling goal does not involve its location.
Simulink provides block libraries that are collections of blocks grouped by functionality. For
example, to model a megaphone that multiplies its input by a constant, we use a Gain block from
the Math Operations library.
A sound wave goes into the megaphone as its input, and a louder version of the same wave comes
out as its output.
The > signs denote the inputs and outputs of a block, which can be connected to other blocks.
We can connect blocks to other blocks to form systems and represent more complex
functionality. For example, an audio player turns a digital file into sound. A digital representation
is read from storage, is interpreted mathematically, and then turned into physical sound. The
software that processes the digital file to compute the sound waveform can be one block; the
speaker that takes the waveform and turns it into sound can be another block. A component that
generates the input is another block. To model the sine, wave input to the megaphone in Simulink,
include a Sine Wave source.
The primary function of Simulink is to simulate behaviour of system components over time. In its
simplest form, this task involves keeping a clock, determining the order in which the blocks are to
be simulated, and propagating the outputs computed in the block diagram to the next block.
Consider the megaphone. At each time step, Simulink must compute the value of the sine wave,
propagate it to the megaphone, and then compute the value of its output.
63
At each time step, each block computes its outputs from its inputs. Once all of the signals in a
diagram are computed at a given time step, Simulink determines the next time step (based on the
model configuration and numerical solver algorithms) and advances the simulation clock. Then
each block computes their output for this new time step.
In simulation, time progresses differently from a real clock. Each time step takes as much time as
it takes to finish the computations for that time step, whether that time step represents a fraction
of a second or a few years.
Often, the effect of a component's input on its output is not instantaneous. For example, turning on
a heater does not result in an instant change in temperature. Rather, this action provides input to a
differential equation. The history of the temperature (a state) is also a factor. When simulation
requires solving a differential or difference equation, Simulink employs memory and numerical
solvers to compute the state values for the time step.
Simulink handles data in three categories:
Signals Block inputs and outputs, computed during simulation
States Internal values, representing the dynamics of the block, computed during simulation
Parameters Values that affect the behaviour of a block, controlled by the user
At each time step, Simulink computes new values for signals and states. By contrast, we specify
parameters when we build the model and can occasionally change them while simulation is
running.
64
5.B.1 Create a Simple Model
We can use Simulink to model a system and then simulate the dynamic behaviour of that system.
The basic techniques we use to create a simple model in this tutorial are the same as those we use
for more complex models. This example simulates simplified motion of a car. A car is typically in
motion while the gas pedal is pressed. After the pedal is released, the car idles and comes to a stop.
A Simulink block is a model element that defines a mathematical relationship between its input
and output. To create this simple model, we need four Simulink blocks.
65
Simulating this model integrates a brief pulse twice to get a ramp. The results display in a Scope
window. The input pulse represents a press of the gas pedal 1 when the pedal is pressed and 0
when it is not. The output ramp is the increasing distance from the starting point.
5.B.2 Open New Model
Use the Simulink Editor to build models.
1. Start MATLAB®. From the MATLAB tools trip, click the Simulink button .
66
2. Click the Blank Model template.
The Simulink Editor opens.
3. From the Simulation tab, select Save > Save as. In the File name text box, enter a name for
model. For example, simple_model. Click Save. The model is saved with the file
extension .slx.
Open Simulink Library Browser
67
Simulink provides a set of block libraries, organized by functionality in the Library Browser. The
following libraries are common to most workflows:
Continuous Blocks for systems with continuous states
Discrete Blocks for systems with discrete states
Math Operations Blocks that implement algebraic and logical equations
Sinks Blocks that store and show the signals that connect to them
Sources Blocks that generate the signal values that drive the model
2. Set the Library Browser to stay on top of the other desktop windows. On the Simulink Library
Browser toolbar, select the Stay on top button .
To browse through the block libraries, select a category and then a functional area in the left pane.
To search all of the available block libraries, enter a search term.
For example, find the Pulse Generator block. In the search box on the browser toolbar, enter pulse,
and then press Enter. Simulink searches the libraries for blocks with pulse in their name or
description and then displays the blocks.
68
Get detailed information about a block. Right-click the Pulse Generator block, and then
select Help for the Pulse Generator block. The Help browser opens with the reference page for
the block.
Blocks typically have several parameters. We can access all block parameters by double-clicking
the block.
5.B.3 Add Blocks to a Model
To start building the model, browse the library and add the blocks.
1. From the Sources library, drag the Pulse Generator block to the Simulink Editor. A copy of
the Pulse Generator block appears in our model with a text box for the value of
the Amplitude parameter. Enter 1.
69
Block Library Parameter
3. Add a second Outport block by copying the existing one and pasting it at another point using
keyboard shortcuts.
4. Our model now has the blocks we need.
5. Arrange the blocks by clicking and dragging each block. To resize a block, drag a corner.
3. Connect the output port of the Gain block to the input port on the Integrator, Second-
Order block.
4. Connect the two outputs of the Integrator, Second-Order block to the two Outport blocks.
5. Save our model. In the Simulation tab, click the Save button.
70
We can open the scope at any time by double-clicking the icon.
5.B.6 Run Simulation
After We define the configuration parameters, We are ready to simulate Our model.
1. In the Simulation tab, set the simulation stop time by changing the value in the toolbar.
The default stop time of 10.0 is appropriate for this model. This time value has no unit. The
time unit in Simulink depends on how the equations are constructed. This example simulates
the simplified motion of a car for 10 seconds other models could have time units in
milliseconds or years.
71
5.B.7 Refine Model
This example takes an existing model, moving_car.slx, and models a proximity sensor based on
this motion model. In this scenario, a digital sensor measures the distance between the car and an
obstacle 10 m (30 ft) away. The model outputs the sensor measurement and the position of the car,
taking these conditions into consideration:
The car comes to a hard stop when it reaches the obstacle.
In the physical world, a sensor measures the distance imprecisely, causing random numerical
errors.
A digital sensor operates at fixed time intervals.
5.B.8 Change Block Parameters
View MATLAB Command
To start, open the moving_car model. At the MATLAB command line, enter:
open_system('moving_car.slx')
We first need to model the hard stop when the car position reaches 10 . The Integrator, Second-
Order block has a parameter for that purpose.
1. Double-click the Integrator, Second-Order block. The Block Parameters dialog box appears.
2. Select Limit x and enter 10 for Upper limit x. The background color for the parameter
changes to indicate a modification that is not applied to the model. Click OK to apply the
changes and close the dialog box.
Add New Blocks and Connections
Add a sensor that measures the distance from the obstacle.
1. Modify the model. Expand the model window to accommodate the new blocks as necessary.
o Find the actual distance. To find the distance between the obstacle position and the vehicle
position, add the Subtract block from the Math Operations library. Also add
the Constant block from the Sources library to set the constant value of 10 for the position of
the obstacle.
o Model the imperfect measurement that would be typical to a real sensor. Generate noise by
using the Band-Limited White Noise block from the Sources library. Set the Noise
power parameter to 0.001. Add the noise to the measurement by using an Add block from
the Math Operations library.
72
o Model a digital sensor that fires every 0.1 seconds. In Simulink, sampling of a signal at a given
interval requires a sample and hold. Add the Zero-Order Hold block from the Discrete library.
After We add the block to the model, change the Sample Time parameter to 0.1.
o Add another Outport to connect to the sensor output. Keep the default value of the Port
number parameter.
2. Connect the new blocks. The output of the Integrator, Second-Order block is already connected
to another port. To create a branch in that signal, left-click the signal to highlight potential
ports for connection, and click the appropriate port.
Annotate Signals
Add signal names to the model.
1. Double-click the signal and type the signal name.
73
1. Create and connect a Scope Viewer to the actual distance signal. Right-click the signal and
select Create & Connect Viewer > Simulink > Scope. The name of the signal appears in the
viewer title.
2. Add the measured distance signal to the same viewer. Right-click the signal and
select Connect to Viewer > Scope1. Make sure that we are connecting to the viewer we
created in the previous step.
3. Run the model. The Viewer shows the two signals, actual distance in yellow and measured
distance in blue.
74
4. Zoom into the graph to observe the effect of noise and sampling. Click the Zoom button .
Left-click and drag a window around the region we want to see more closely.
75
From the plot, note that the measurement can deviate from the actual value by as much as 0.3 m.
This information becomes useful when designing a safety feature, for example, a collision
warning.
5.1. The expression for sine wave is given by x( ¢) = Asin(27ft + ¢) .Write a code which
accepts the input as (i ) Amplitude (A) (ii) Frequency (f) and (iii) Phase(¢ )and
generates the sine wave. Plot the sine wave .
Program:
clc
clear all
close all
A=2;
fm=50;
fs=20*fm;
ts=1/fs;
t=-1/fm:ts:5/fm;
x=A*sin(2*pi*fm*t);
plot(t,x)
xlabel('time');
ylabel('Amplitude');
title('Generation of Sine signal')
76
5.2 Write a program to convert the sine wave to (i) Half wave rectified sinewave and (ii) Full
wave rectified sine wave
Program:
clc
clear all
close all
A=2;
fm=50;
fs=20*fm;
ts=1/fs;
t=-1/fm:ts:5/fm;
x=A*sin(2*pi*fm*t);
subplot(3,1,1)
plot(t,x)
xlabel('time');
ylabel('Amplitude');
title('Generation of Sine signal')
grid on
x_h=zeros(1,length (t));
for i=1:length(t)
if x(i)>=0
77
x_h(i)=x(i);
else
x_h(i)=0
end
end
subplot(3,1,2)
plot (t,x_h,'r')
xlabel('time');
ylabel('Amplitude');
title('Generation of halfwave sine signal')
y=abs(x);
subplot(3,1,3)
plot (t,y,'k')
xlabel('time');
ylabel('Amplitude');
title('Generation of full wave sine signal')
Output:
78
5.3 Write a program which converts the sine wave to a square wave Equivalent to that of
-
Program:
clc
clear all
close all
A=2;
fm=50;
fs=20*fm;
ts=1/fs;
t=-1/fm:ts:5/fm;
x=A*sin(2*pi*fm*t);
subplot(2,1,1)
plot(t,x)
xlabel('time');
ylabel('Amplitude');
title('Generation of Sine signal')
%%---Converting Sine to Square using Comparator------
y=sign(x)
subplot(2,1,2)
plot(t,y)
xlabel('time');
ylabel('Amplitude');
title('Generation of Square signal')
Output:
79
5.4. Write a program to generate three-phase sinusoidal signal. The students Should know
what is the phase difference between three phases in a three-phase sinusoidal signal and
the importance of three phase power
Program:
clc
clear all
close all
t=0:0.002:0.04;
y=sin(2*pi*50*t);
plot(t,y)
hold on
t1=0.01:0.002:0.05;
y1=sin(2*pi*50*t);
plot(t1,y1)
t2=0.035:0.002:0.075;
y2=sin(2*pi*50*t);
plot(t2,y2)
grid;
80
xlabel('time(s)');
ylabel('amplitude');
title('three phase sine wave');
Output:
81
82