Sunteți pe pagina 1din 17

Table of Contents

Creating the time axis- ........................................................................... 2


Syntax: ................................................................................................. 2
Plotting a sinusoid .................................................................................. 3
Generate a ramp signal ........................................................................... 3
Taking the Fourier transform of the signal ............................................ 4
3-D plots ................................................................................................. 4
Analysis of transfer functions on the complex plane ............................. 6
Filter fundamentals ................................................................................. 7
Mathematical representation of LTI systems ......................................... 9
Analysis of feedback systems ................................................................ 9
Mathematical Representation of Images .............................................. 10
Histogram of an Image ......................................................................... 11
Histogram processing- Intensity transformations ................................ 11
UART based serial communication ..................................................... 14
Final Project- Ball following robot using MATLAB .......................... 15

Matlab Workshop

Creating the time axis-

For representation of signals, the reference axis is of prime importance. Here time
is the independent variable and it serves as the axis for representing time varying
signals.
Axes are created as row arrays in MATLAB, with each point in the array depicting
each instant of time.
For representing time, two main parameters are to be defined.
1. The span- indicates the length.
2. The precision- indicates the distance between two adjacent time points. (This
turns out to be the sampling period of the signal represented.
Syntax:
t=initial point : precision : final point ;
eg: t=0:0.001:1; %This generates a row array of the form 0, 0.001, 0.002, . ,
0.998, 0.999, 1

Plotting a sinusoid
A sinusoid is characterized by its frequency, amplitude and phase.
We generate an array which stores the value of the signal corresponding to each
instant of time defined earlier.
Eg:

t=0:0.001:1;
A=1; %Amplitude of 1
f=2; %frequency of 2 Hz
ph=pi/3; % a phase of 60 degrees
V=A*sin(2*pi*f*t+ph); %sinusoidal values stored in V

plot(t,V); grid on;


axis( [0 1 -2 2]);
xlabel( 'time(s)');
ylabel( 'amplitude');

Generate a ramp signal


A ramp signal is characterized by just its slope.
Eg;
Fs=44000;
t=0:1/Fs:1;
m=1; % A ramp signal is characterised by its slope.
V=m.*t;
plot(t,V); grid on;
axis( [0 1 -2 2]);
xlabel( 'time(s)');
ylabel( 'amplitude');

Taking the Fourier transform of the signal


The Fourier transform is a mathematical tool by which we may view continuous
time signals as linear combinations of sines and cosines of various frequencies.
Since MATLAB cannot process continuous time signals due to its digital nature,
we approximate it with the discrete approximation known as the DFT( Discrete
Fourier transform).

Eg.
%subplot
Fs=44000;
t=0:1/Fs:1-1/Fs;
N=length(t);% size of the array 't'
A=1; %Amplitude of 1
f=2; %frequency of 2 Hz
ph=0; % a phase of 60 degrees
V=A*sin(2*pi*f*t+ph); %sinusoidal values stored in V
Vf=fftshift(fft(V));
subplot(2,1,1); plot(t,V); grid on;
axis( [0 1 -2 2]);
xlabel( 'time(s)');
ylabel( 'amplitude');
faxis=-Fs/2:Fs/N:Fs/2-Fs/N;
subplot(2,1,2); plot(faxis,abs(Vf)/(N)); grid on; %complex number so
we plot magnitude spectrum
axis( [-Fs/2 Fs/2-Fs/N -0.1 0.6]);
xlabel( 'Frequency(Hz)');
ylabel( 'amplitude');

3-D plots
%3-D plots
clear all
close all
clc;
%Plotting a sphere of radius 4
%
X.^2+Y.^2+Z.^2=16, Z>0
[X Y]=meshgrid(-4:0.1:4);% generates all the (X,Y) points to be
plotted

Z=sqrt(16-X.^2-Y.^2);
Z=real(Z);
surf(X,Y,Z,'Linestyle', 'none');
axis([-5 5 -5 5 -5 5]);
%since functions allow only one output value for each (x,y)
coordinate, to %represent a sphere we need to plot 2 functions
simultaneously on the same %figure

Z2=-sqrt(16-X.^2-Y.^2);
Z2=real(Z2);
hold on;
surf(X,Y,Z2,'Linestyle', 'none');

Analysis of transfer functions on the complex plane


%Plotting s-domain transfer functions
%tf to be plotted ----->
%
s
%
--------------%
(s+1)(s+2)(s+3)
%NB: We are plotting the magnitude contours
clear all;
close all;
clc;
[X,Y]=meshgrid(-4:0.01:4);
G=(X.^2+Y.^2)./(((X+1).^2+Y.^2).*((X+2).^2+Y.^2).*((X+3).^2+Y.^2));
surf(X,Y,G,'Linestyle', 'none'); xlabel('x axis'); ylabel('y axis');
% axis([0 5 0 5]);

Now try viewing the contour along the y-axis. This gives G(jw) and verify
%Plotting s-domain transfer functions
%tf to be plotted ----->
%
s
%
--------------%
(s+1)(s+2)(s+3)
%NB: We are plotting the magnitude contours
clear all;
close all;
clc;
[X,Y]=meshgrid(0:0.01:4);
G=(X.^2+Y.^2)./(((X+1).^2+Y.^2).*((X+2).^2+Y.^2).*((X+3).^2+Y.^2));
surf(X,Y,G,'Linestyle', 'none'); xlabel('x axis'); ylabel('y axis');
% axis([0 5 0 5]);
figure;
X=0; Y=Y(:,1);
G2=(X.^2+Y.^2)./(((X+1).^2+Y.^2).*((X+2).^2+Y.^2).*((X+3).^2+Y.^2));
plot(Y,G2); grid on; xlabel('jw axis'); ylabel('G');

Filter fundamentals
The design of filters is simplified to a large extent by the use of mathematical tools
like MATLAB. Filters find application in diverse domains. We discuss the
implementation of discrete time filters of finite length.
%Digital Filter Impmlementation
%Filters are used to seperate out certain frequencies from a signal
and
%block other frequencies.
%They are of the types%Lowpass, Highpass, Bandpass, Bandreject
%A filter is described uniquely by its impulse response
%The filter design process involves the development of this impulse
%response satisfying our requirements

%Generate the input signal


l=length(t);
Fs=44000;
t=0:1/Fs:1;
A1=1; %Amplitude of 1
A2=0.5;
f1=500; %frequency of 5000 Hz
f2=5000; %frequency of 5000Hz
ph=0; % a phase of 60 degrees
V=A1*cos(2*pi*f1*t)+A2*cos(2*pi*f2*t); %sinusoidal values stored in V
Vf=fftshift(fft(V));
plot(t,V); grid on;
axis( [0 1 -2 2]);
xlabel( 'time(s)');
ylabel( 'amplitude');
faxis=-Fs/2:Fs/l:Fs/2-Fs/l;
figure;% generates new figure, otherwise older on over written
plot(faxis,abs(Vf)/(l)); grid on; %complex number so we plot magnitude
spectrum
axis( [-Fs/2 Fs/2-Fs/l -0.1 0.6]);
xlabel( 'Frequency(Hz)');
ylabel( 'amplitude');

%Initialize the length of the filter.


%Higher the length, better will be the freqeuncy selectivity but more
%length brings in more delay- a trade-off parameter

%Say we want to filter out all frequencies less than 1KHz.


N=100;%length of the filter
fc=1000; %cutoff frequency
Fc=fc/Fs;%Normalised frequency with respect to Fs
H=zeros(1,N);
for i=1:N
index=i-1;
if ((index/N < Fc) || (index/N> (1-Fc)))
H(i)=1;
else H(i)=0;
end
end
h1=ifft(H);
h=fftshift(h1);
figure;
stem(-N/2:N/2-1,h);xlabel( 'n ---->');ylabel( 'impulse response');
grid on;
r=conv(h,V);% convolve the input signal with the impulse response
r=r(N/2:length(r)-N/2);%truncate it to get relevant values
rf=fftshift(fft(r));% take the fft of the output signal
figure; plot(t,r); grid on;%plot the signal
axis( [0 1 -2 2]);
xlabel( 'time(s)');
ylabel( 'amplitude');
faxis=-Fs/2:Fs/l:Fs/2-Fs/l;
figure;% generates new figure, otherwise older one over written
plot(faxis,abs(rf)/(l)); grid on; %complex number so we plot magnitude
spectrum
axis( [-Fs/2 Fs/2-Fs/l -0.1 0.6]);
xlabel( 'Frequency(Hz)');
ylabel( 'amplitude');

Try implementing Bandpass filters and obtain output through the speakers using
audioplayer object.

Mathematical representation of LTI systems


Systems can be completely represented by its transfer function. Here we try to
represent various systems and observe how they respond to different inputs.
%we can use MATLAB to represent s-domain transfer function and
visualize
%various parameters.
clear all;
close all;
clc;
num=[1 9 1];%numerator coefficients
roots=[-1 -2 -3];% denominator poles
den=poly(roots); %denominator coefficients
G=tf(num,den); % define the transfer function
step(G); % output of the system to a step input
impulse(G);%output of the system to impulse input
bode(G);%bode plot magnitude and phase of the system
rlocus(G);%rootlocus plot

Analysis of feedback systems


Here we try to implement negative feedback in systems and observe its relevance
in introducing stability in the systems.
%we can use MATLAB to represent s-domain transfer function and
visualize
%various parameters.
clear all;
close all;
clc;
num=[1 9 1];%numerator coefficients
roots=[-1 -2 -3];% denominator poles
den=poly(roots); %denominator coefficients
G=tf(num,den); % define the transfer function
step(G); % output of the system to a step input
impulse(G);%output of the system to impulse input
bode(G);%bode plot magnitude and phase of the system

rlocus(G);%rootlocus plot
F=feedback(G,1,-1);
step(F); % output of the system to a step input
impulse(F);%output of the system to impulse input
bode(F);%bode plot magnitude and phase of the system

Mathematical Representation of Images


Digital images are represented as 2-D arrays with each element corresponding to
intensity values of the respective pixel at that location. In the case of colour
images, we have three such arrays each showing the contribution of the three
primary colours- R, G & B. In most modern systems, the intensities are represented
on a scale of 0 to 255 with 0 being absolute black and 255 being absolute white
and all shades of grey in between.
Eg.
clear all
close all
clc
x=imread('tire.tif'); % reads in an image to x

Now open the variable x to observe various intensity values.

10

Histogram of an Image
A histogram is a statistical measure, which indicates how many objects correspond
to a particular value in a function. Here, with reference to images, a histogram
gives the number of pixels corresponding to each intensity value.
%Function for finding the histogram of an image
%Here we define the function histogram() which accepts a grayscale
image
%and returns the histogram output array- each element corresponds to
the
%number of pixels having that intensity
function H=histogram(X)
[M N]=size(X); %M-> No. of Rows, N-> No. of columns
X2=double(X); % convert the data from uint8 to double float type
H=zeros(1,256);
for i=1:M
for j=1:N
H(X2(i,j)+1)=H(X2(i,j)+1)+1; %Calculating the histogram
end

end

Histogram processing- Intensity transformations


Intensity transformation refers to the process of mapping intensities of the input
image to that of the output image by means of a mapping function. This technique
is used for image enhancement and to obtain visually pleasing images.
The mapping function can be of any form, square-law, square-root law,
exponential, logarithmic etc.
A good image is characterized by a uniform histogram. i.e. all the intensity values
have more or less the same no. of pixels in the image.
Here our aim is to find a mapping function that would result in a uniform
histogram output image.

11

We see from theory that such a mapping function turns out to be the Cumulative
Distribution Function(CDF) of the histogram. Once the CDF is used to transform
the image, we get better contrast and more details can be picked up from the
image. (Kindly refer notes for more details).
Eg.
% A square law intensity transform.
clear all
close all
clc
x=imread('tire.tif'); % reads in an image to x
%histogram of the input image
H_x=histogram(x);
stem(H_x);
y=sqroot_law(x);
H_y=histogram(y); %histogram of the output image
figure;
stem(H_y);
figure;
subplot(1,2,1); imshow(x);
subplot(1,2,2); imshow(y);

%Function defined for finding the square of each pixel intensity value
%A factor to be noted is that the square law function should be scaled
such that 0 maps to 0 and 255 maps to 255.
%Other similar functions may be defined such as square-root,
logarithmic, exponential etc.
function Y=square_law(X)
[M N]=size(X);
x2=double(X);
Y=[];
for i=1:M
for j=1:N
Y(i,j)=1/255*x2(i,j)*x2(i,j);
end
end
Y=uint8(Y);
end

Eg.2 Histogram Equalization the mapping function is the CDF of the input image
histogram
12

clear all
close all
clc
x=imread('tire.tif'); % reads in an image to im
%histogram of the image
H_x=histogram(x);
stem(H_x);
y=sqroot_law(x);
H_y=histogram(y);
figure;
stem(H_y);
figure;
subplot(1,2,1); imshow(x);
subplot(1,2,2); imshow(y);
cdf_x=cdf_img(x);
figure;
plot((0:255), cdf_x); grid on;

%Histogram Equalization
[M N]=size(x);
x2=double(x);
x_equalised=[];
for i=1:M
for j=1:N
x_equalised(i,j)=cdf_x(x2(i,j)+1);
end
end
x_equalised=uint8(x_equalised);
figure;
subplot(1,2,1); imshow(x);
subplot(1,2,2); imshow(x_equalised);
H_xeq=histogram(x_equalised);
figure;
subplot(2,1,1); stem(H_x);
subplot(2,1,2); stem(H_xeq);

13

UART based serial communication


UART stands for Universal Asynchronous Receiver/Transmitter. Its not a
communication protocol like SPI and I2C, but a physical circuit in a
microcontroller, or as a separate IC. A UARTs main purpose is to transmit and
receive serial data.
In UART communication, two UARTs communicate directly with each other. The
transmitting UART converts parallel data from a controlling device like a CPU
into serial form, transmits it in serial to the receiving UART, which then converts
the serial data back into parallel data for the receiving device. Only two wires are
needed to transmit data between two UARTs. Data flows from the Tx pin of the
transmitting UART to the Rx pin of the receiving UART:

UARTs transmit data asynchronously, which means there is no clock signal to synchronize the
output of bits from the transmitting UART to the sampling of bits by the receiving UART.
Instead of a clock signal, the transmitting UART adds start and stop bits to the data packet being
transferred. These bits define the beginning and end of the data packet so the receiving UART
knows when to start reading the bits.
When the receiving UART detects a start bit, it starts to read the incoming bits at a
specific frequency known as the baud rate. Baud rate is a measure of the speed of data
transfer, expressed in bits per second (bps). Both UARTs must operate at about the same baud
rate. The baud rate between the transmitting and receiving UARTs can only differ by about 10%
before the timing of bits gets too far off.
Both UARTs must also be configured to transmit and receive the same data packet structure.

14

Final Project- Ball following robot using MATLAB


Here we try to implement a color detection algorithm. This algorithm detects red
round objects and issues commands to the Microcontroller to make necessary
movements. This is communicated via the UART serial communication protocol.
The video input is taken from the webcam connected to the device.
Code:
%ser=fopen('output2.txt','a');
serial('COM36','Baudrate',9600);
fopen(ser);
vid=videoinput('winvideo',1,'YUY2_320x240');
set(vid,'ReturnedColorSpace','rgb');
preview(vid);
pause(2);
while 1
pause(1);
im1=getsnapshot(vid);
% Now to track red objects in real time
% we have to subtract the red component
% from the grayscale image to extract the red components in the
image.
im2= imsubtract(im1(:,:,1), rgb2gray(im1));
%Use a median filter to filter out noise
im3 = medfilt2(im2, [3 3]);
% Convert the resulting grayscale image into a binary image.
im3 = im2bw(im3,0.28);
imshow(im3);
[C M O]=bwboundaries(im3,'noholes');
a=regionprops(M,'centroid');
if O==0
else
if(O==1)
c=(a.Centroid(1,1));
if(c<=90)
display('L');
fwrite(ser,'L');
pause(0.35);
elseif(c>90)
if(c>=190)
display('R');
fwrite(ser,'R');
pause(0.35);
else

15

display('F');
fwrite(ser,'F');
pause(0.3);
end
end
end
end
end

16

Notes

17

S-ar putea să vă placă și