0% found this document useful (0 votes)
11 views

Advanced MATLAB Code

The document outlines a series of MATLAB programming tasks aimed at studying functions, flow control, and plotting. It includes specific objectives such as printing prime numbers, calculating areas and perimeters of circles, analyzing RLC circuits, and generating sine waves. Additionally, it provides examples of MATLAB code for each task along with the required software specifications.

Uploaded by

ersimohit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Advanced MATLAB Code

The document outlines a series of MATLAB programming tasks aimed at studying functions, flow control, and plotting. It includes specific objectives such as printing prime numbers, calculating areas and perimeters of circles, analyzing RLC circuits, and generating sine waves. Additionally, it provides examples of MATLAB code for each task along with the required software specifications.

Uploaded by

ersimohit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

EXPERIMENT NO.

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.

APPARATUS/ SOFTWARE REQUIRED:

SR.NO SOFTWARE SPECIFICATION QUANTITY


1 MATLAB MATLAB-2022 CAMPUS-WIDE LICENCE

3.A M-files: Scripts and functions

(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.

3.B MATLAB Functions

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.

Let us give a simple example.

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.

Remember to save your m-files in the current directory.

The first line of our function is called the function definition


function named fahr_to_kelvin, that has a single input parameter, ftemp, and a single output
parameter, ktemp. Anything following the function definition line is called the body of the
function. The keyword end
any code after end.

fahr_to_kelvin that converts temperatures from Fahrenheit to


Kelvin:
function ktemp = fahr_to_kelvin(ftemp)
%FAHR_TO_KELVIN Convert Fahrenheit to Kelvin

ktemp = ((ftemp - 32) * (5/9)) + 273.15;


end
Just as we saw with scripts, functions must be visible to MATLAB, i.e., a file containing a functi
on has to be placed in a directory that MATLAB knows about. The most convenient of those dire
ctories is the current working directory.
In common with MATLAB, Octave searches the current working directory and the path
for functions called from the command line.
We can call our function from the command line like any other MATLAB function:
>> fahr_to_kelvin(32)

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

% This section below is called the body of the function


out1 = something calculated;
out2 = something else;
end

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.5 Write a program to convert the temperature in degrees to Celsius.


Program:
function celsiustemp = fahr_to_celsius(ftemp)
%FAHR_TO_celsius Convert Fahrenheit to Celsius

celsiustemp = ((ftemp - 32) * (5/9)) ;


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

3.9 The function sin(x) can be written as a Taylor series by:

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:

a) Input the value of , , and


b) Calculate using the relation:

, if

1, if

c) Print the output as shown below:

4.4 Use a for-end loop in a script file (.m file) to calculate the sum of the first terms of
the series:

Execute the script file for 4 and 20.

4.5 Write a program to f in d the current I in the circuit shown below


a) By using conditional statements.
b) Without using any conditional statements.

SOFTWARE REQUIRED:

SR.NO SOFTWARE SPECIFICATION QUANTITY


1 MATLAB MATLAB-2022 CAMPUS-WIDE LICENCE

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:

The matrix A is beow:


a=11 3 14

8 6 2

10 13 1

Commands:
Clear all;

a=[11 3 14; 8 6 2; 10 13 1]; % Given matrix

MatMax=a(1,1); % MatMax is the first element of [a] for now.

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

if(a(k,m)>MatMax) % Comparison of the elements with MatMax

MatMax=a(k,m);% Updating the value of MatMax

end

end

end

disp('The maximum value present in the matrix [a]=');disp(MatMax);


%Displaying the %maximum value

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:

4.3 Write a MATLAB program in M -File to do the following steps:


a)Input the value of , , and
b)Calculate using the relation:

, if

1, if

c) Print the output as shown below:

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

%--------------------Computation of s begin here----------------------------


---%

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:

Execute the script file for 4 and 20.

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:

Fig: The required outputs at the command window

end

4.5 Write a program to f in d the current I in the circuit shown below


a) By using conditional statements.
b) Without using any conditional statements.

49
Program:

GIVEN RELATION:
(a) If switch is open then A
If switch is closed then and A

(b) , where when switch is closed and


when switch is open.
COMMANDS:

(a) By using conditional statements:


clear all;
while(1)% Infinite loop used which will ask the user the enter the value of switch
key=input('Enter the value of switch '); %Requesting user to enter the value of switch whether
it is on (=1) or off (=)
%--------------------Calculation of current begin here-------------------------------%
if(key==1) %Condition 1
Req=2.5+((5*5)/(5+5));
I=5/Req;
else %Condition 2
Req=2.5+5;
I=5/Req;
end
disp('Current, I=');disp(I) % Displaying value of I
end

50
%Enter ctrl+C to terminate the while loop

(b) Without using conditional statements:


clear all;
while(1)% Infinite loop used which will ask the user the enter the value of switch
key=input('Enter the value of switch '); %Requesting user to enter the value of switch whether
it is on (=1) or off (=0)

%--------------------Calculation of current begin here-------------------------------%


Req=2.5+key*((5*5)/(5+5))+(1-key)*5;
I=5/Req;
disp('Current, I=');disp(I) % Displaying value of I
end

%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:

SR.NO SOFTWARE SPECIFICATION QUANTITY


1 MATLAB MATLAB-2022 CAMPUS-WIDE LICENCE

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

Drawing Multiple Functions on the Same Graph


You can draw multiple graphs on the same plot. The following example demonstrates the concept

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

x = [-10 : 0.01: 10];


y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;

55
plot(x, y, 'r', x, g, 'g')

Setting Axis Scales


The axis command allows you to set the axis scales. You can provide minimum and maximum

axis ( [xmin xmax ymin ymax] )

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

Drawing bar charts


Drawing contours
Three dimensional plots

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.

[x,y] = meshgrid( 5:0.1:5, 3:0.1:3);


Lastly, we need to assign the function. Let our function be: x2 + y2

[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables


g = x.^2 + y.^2; % our function
contour(x,y,g) % call the contour function
print -deps graph.eps

Let us modify the code a little to spruce up the map


[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables
g = x.^2 + y.^2; % our function
[C, h] = contour(x,y,g); % call the contour function
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
print -deps graph.eps

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.

5.B Introduction to Simulink Modeling in MATLAB


Simulink is a block diagram environment for multi-domain simulation and Model-Based
Design. It supports system-level design, simulation, automatic code generation, and continuous
test and verification of embedded systems. Simulink provides a graphical editor, customizable
block libraries, and solvers for modeling and simulating dynamic systems. It is integrated with
MATLAB, enabling we to incorporate MATLAB algorithms into models and export simulation
results to MATLAB for further analysis.
Simulink is a graphical modeling and simulation environment for dynamic systems. We can create
block diagrams, where blocks represent parts of a system. A block can represent a physical
component, a small system, or a function. An input/output relationship fully characterizes a block.
Consider these examples:
A faucet fills a bucket Water goes into the bucket at a certain flow rate, and the bucket gets
heavier. A block can represent the bucket, with flow rate as the input and its weight as the output.
We use a megaphone to make our voice heard The sound produced at one end of the megaphone
is amplified at the other end. The megaphone is the block, the input is the sound wave at its source,
and the output is the sound wave as we hear it.
We push a cart and it moves The cart is the block, the force we apply is the input, and the cart's
position is the output.

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.

Block Name Block Purpose Model Purpose

Pulse Generator Generate an input signal for the Represent the


model
accelerator pedal

Gain Multiply the input signal by a Calculate how pressing the


constant value
accelerator affects the car
acceleration

Integrator, Integrate the input signal twice Obtain position from


Second-Order
acceleration

Out port Designate a signal as an output from Designate the position as


the model
an output from the model

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

1. From the Simulation tab, click the Library Browser button .

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.

Parameter values are held throughout the simulation.


2. Add the following blocks to our model using the same approach.
Block Library Parameter

Gain Simulink/Math Gain: 2


Operations

69
Block Library Parameter

Integrator, Second- Simulink/Continuous Initial


Order condition: 0

Outport Simulink/Sinks Port number: 1

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.

5.B.4 Connect Blocks


Connect the blocks by creating lines between output ports and input ports.
1. Click the output port on the right side of the Pulse Generator block.
The output port and all input ports suitable for a connection are highlighted.

2. Click the input port of the Gain block.


Simulink connects the blocks with a line and an arrow indicating the direction of signal flow.

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.

5.B.5 Add Signal Viewer


To view simulation results, connect the first output to a Signal Viewer.
Click the signal. In the Simulation tab under Prepare, click Add Viewer. Select Scope. A viewer
icon appears on the signal and a scope window opens.

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.

2. To run the simulation, click the Run button .


The simulation runs and produces the output in the viewer.

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.

2. To finish, click away from the text box.


3. Repeat these steps to add the names as shown.

Compare Multiple Signals


Compare the actual distance signal with the measured distance signal.

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.

we can repeatedly zoom in to observe the details.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy