0% found this document useful (0 votes)
72 views17 pages

Conv

The document discusses implementing convolution in MATLAB without using the built-in conv function. It provides an example MATLAB code that takes two input sequences x and h, pads them with zeros if needed, and calculates the output sequence y by iterating through a convolution summation. The code is able to convolve two sequences and plot the result without using the conv function.

Uploaded by

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

Conv

The document discusses implementing convolution in MATLAB without using the built-in conv function. It provides an example MATLAB code that takes two input sequences x and h, pads them with zeros if needed, and calculates the output sequence y by iterating through a convolution summation. The code is able to convolve two sequences and plot the result without using the conv function.

Uploaded by

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

I am not

understand this
concept can
anybody
xplain me i am
using X as 3*3
matrix and h as
Comment only
3*3 matrix...I
runned the
aghil vinayak
program got
output but t is
1*6 matrix but
ishould be 3*3
18
May Dhrubajyoti
201 Das
5

Good

24
Sep Muhammad
201 Azeem
4

function y=my_conv(x,h)
x2=h;
lx=length(x);
lh=length(h);
if lx>lh
x2=[x2 zeros(1,lx-lh)];
else
x=[x zeros(1,lh-lx)];
end
y=zeros(1,lx+lh-1);
x=fliplr(x);
for i=1:length(y)
if i<=length(x)
y(i)=sum(x(1,length(x)-i+1:length(x)).*x2(1,1:i));
else
j=i-length(x);
y(i)=sum(x(1,1:length(x)-j).*x2(1,j+1:length(x2)));
end
end
figure
stem(y);

15 Sharifa
Mar Yasheen
201
4

I excuted Priya's written program but got error saying X


must be same length as Y and even in
subplot(2,2,1);stem(x1,x);

Comment
only

Comment
only

Please help me out where am going wrong


15
Mar Zulqadar
201 Hassan
4

good

23
Feb
Priya
201
4

clc
clear all
close all
x=input('Enter the first sequence: ');
l1=input('Enter the lower limit: ');
u1=input('Enter the upper limit: ');
x1=l1:1:u1;
h=input('Enter the second sequence: ');
l2=input('Enter the lower limit: ');
u2=input('Enter the upper limit: ');
h1=l2:1:u2;
l=l1+l2;
u=u1+u2;
n=l:1:u;
s=numel(n);
i=1;
for i=1:s
y(i)=0;
for k=1:numel(x)
if (i+1-k)<=0
y(i)=y(i)+(x(k)*0);
else if (i+1-k)>numel(h)
y(i)=y(i)+(x(k)*0);
else
y(i)=y(i)+(x(k)*h(i+1-k));
k=k+1;
end
end
end
i=i+1;
end
disp(y);
subplot(2,2,1);stem(x1,x);
title('First sequence');xlabel('n');ylabel('x(n)');
subplot(2,2,2);stem(h1,h);
title('Second Sequence');xlabel('n');ylabel('h(n)');
subplot(2,2,[3 4]);stem(n,y);
title('Convoluted sequence');xlabel('n');ylabel('y(n)');

Comment
only

28 assad
Jan
201
4

X = input('Enter x: '); %input vector X and H


H = input('Enter h: ') ;
LenX = length(X); %defining their lenghts
LenH = length(H);
y = zeros(1,LenX+LenH); %defing vector y of zeroes and of
size
% lenth of X + length of H
t = zeros(1,LenH); % definign a vector t of same length as H
for i = 1:LenH+LenX-1 % Running a for loop from 1 to
length of Y -1
if i<=LenX % till I IS Lesser then length of X i.e overlap
about to begin
t(1)= X(i); % put x(i) on t(1) later it is shifted forwards in the
vector t i.e. later t(2)=t(1)
for j = 1:LenH % in the if condition a for loop from 1 to
length of H
y(i) = y(i) + H(j)*t(j); % summing for all H(j)*t(j) and
putting it at y(1) or y(2) or Y(i) in first iteration
% i.e. for i=1 only firt multiplication would
% be non zero rest all zeroes.
end
for k = LenH:-1:2 % shifting old value of t(i) to t(i+1) now
there would me 1+ non zeroes values in t
% this cycle would continue until i is lesser then
% length X i.e. overlap increasing every iteration less
% and less non zero vales in t every iteration
t(k) = t(k-1);
end
else % now when all of the T is non zero which means 100%
overlap in else overlap would start to decrease between T
and H
% T is basically X
t(1)= 0;
for j = 1:LenH % Now we start filling up Zeroes in T i.e.
overlap began to decrease now and each iteration it would
decrease
% i.e T moving to left until there is no more
% over lap
y(i) = y(i) + (H(j)*t(j)); % in this for loop we multiply all
respective vales of h and t and add the
% putting it at y(1) or y(2) or Y(i) in first iteration
end

Comment
only

for k = LenH:-1:2 %% here just like similar loop above t


where we were filling up t with vales of x
%now we are filling up zeroos in t i.e. over lap decreasing
t(k) = t(k-1);
end
end
end
ly=length(y)
indices=[ly]
for i=1:ly
indices(i)=i;
end
disp (y); %displays vector y.
disp (indices); % displays vector indices.
stem(y);
ylabel('Y[n]');
xlabel('[n]');
title('Convolution without conv function');
23 Aghil Vinayak
Sep
x = input('Enter x: ');
201
h = input('Enter h: ') ;
3
Ni = length(x);
Nh = length(h);
y = zeros(1,Ni+Nh);
t = zeros(1,Nh);
for i = 1:Ni+Nh-1
if i<=Ni
t(1)= x(i);
for j = 1:Nh
y(i) = y(i) + h(j)*t(j);
end
for k = Nh:-1:2
t(k) = t(k-1);
end
else
t(1)= 0;
for j = 1:Nh
y(i) = y(i) + (h(j)*t(j));

Comment
only

end
for k = Nh:-1:2
t(k) = t(k-1);
end
end
end
stem(y);
30
Mar
sonali
201
3
21
Feb Rama Krishna
201 Tata
3
function [y] = myconv( x,h )

17
Feb Abdul-Rauf
201 Mujahid
3

m=length(x);
n=length(h);
x=[x,zeros(1,n)];
h=[h,zeros(1,m)];
for i=1:n+m-1
y(i)=0;
for j=1:m
if(i-j+1>0)
y(i)=y(i)+x(j)*h(i-j+1);
end
end
end

26
Dec
Aiman Sultan thanx :)
201
2
22
Nov
Nirjhar Roy nice
201
2
15 Mohammad
Comment
Nov reza nilchiyan good Job man, how can we put this code in the box with the only

201
2

rectangular shape input in simulink?

28
May muskan
201 kanwal
2
24
Apr
can you make it using function so that we should give two
tehseen sattar
201
input argument to the function and we return the output ...
2

Comment
only

12
Thank-you Duane, exactly what I was looking for.
Apr
Jos(10584) this program is very useful to me, so your
chiangmai4121
201
comment is wrong. Thanks again Duane, keep ignoring
2
haters like Jos
20
Jan
Mohit Gaur
201
2
12
Oct Tim
2011
23
Sep hamsa dhia
2011
30
jyotibasu
Jun
yaranal
2011
14
Jul ROHIT
201 ALHAT
0
27
Mar
imran shezad
200
9
24
Mar
Jos (10584)
200
9
23 Duane
Mar Hanselman
200
9

Why are there two inputs, x and h?


good gob well done
fine..

good job man.....

A typical example of a file that has no use for others, written


in poor C-style code. Do not bother to download!
The content of the M-file is:
% A GENERALAZED CONVOLUTION COMPUTING
CODE IN MATLAB WITHOUT USING MATLAB

Comment
only

BUILTIN FUNCTION conv(x,h)


close all
clear all
x=input('Enter x: ')
h=input('Enter h: ')
m=length(x);
n=length(h);
X=[x,zeros(1,n)];
H=[h,zeros(1,m)];
for i=1:n+m-1
Y(i)=0;
for j=1:m
if(i-j+1>0)
Y(i)=Y(i)+X(j)*H(i-j+1);
else
end
end
end
Y
stem(Y);
ylabel('Y[n]');
xlabel('----->n');
title('Convolution of Two Signals without conv function');

Otro*****************************************
function conv_322(x,x_start,h,h_start,delta);
% conv_322(x,x_start,h,h_start,delta);
%
% Convolution support function for the Signals and Systems course,
% EE-322 at the United States Naval Academy {EE Department}.
% Calculates and plots the numeric convolution integral, y(t) =
x(t)*h(t).
% The input, x(t), and the impulse response, h(t), are also plotted.
% For the result to be accurate ... delta must be sufficiently small.
%
% x
- sampled version of the input function
% x_start - input function start time (in seconds)
% h
- sampled version of the impulse response function
% h_start - impulse response function start time (in seconds)
% delta - time interval between samples (in seconds) ... delta t

%
% 7 September 1998, last rev 23 September 1998
% copyright (c) 1998, written by CDR Thad Welch {USNA}
% w/ help from Midshipman 2/C Trevor Laughter
expand=0.1;
total_length=length(x)+length(h)-1;
t=x_start+h_start+delta*(0:total_length-1);
t_min=min([x_start h_start t]);
t_max=max([x_start+delta*length(x) h_start+delta*length(h) t]);
y=delta*conv(x,h);
y_min=min([x h y]);
y_max=max([x h y]);
tmin=t_min-expand*(t_max-t_min);
tmax=t_max+expand*(t_max-t_min);
ymin=y_min-expand*(y_max-y_min);
ymax=y_max+expand*(y_max-y_min);
x_time=x_start+delta*(0:length(x)-1);
h_time=h_start+delta*(0:length(h)-1);
subplot(3,1,1)
plot([tmin t(1)-delta t tmax],[0 0 y 0],'b')
grid
title('Convolution of x(t) and h(t)')
ylabel('output, y(t)')
%axis([tmin tmax ymin ymax])
subplot(3,1,2)
plot([tmin x_time(1)-delta x_time x_time(length(x_time))+delta tmax],[0 0
x 0 0],'r')
grid
ylabel('input, x(t)')
%axis([tmin tmax ymin ymax])
subplot(3,1,3)
plot([tmin h_time(1)-delta h_time h_time(length(h_time))+delta tmax],[0 0
h 0 0],'g')
grid
xlabel('time (seconds)')
ylabel('impulse response, h(t)')
%axis([tmin tmax ymin ymax])

otro*****************************

Convolution without using conv in MATLAB


LINEAR SYSTEMS :
A system is linear, if it satisfies the superposition principle i.e. response of the system to a
weighted sum of signals is equal to the corresponding weighted sum of responses (outputs)
of the system to each of the individual input signals. Mathematically, if

x[n]=ax1[n]+bx2[n]
The response of the linear system is :

y[n]=ay1[n]+by2[n]
TIME INVARIANT SYSTEMS :
A system is time invariant if its input/output characteristic does not change with time. A
system is time invariant or shift invariant if and only if

x[n]y[n]
x[nk]y[nk]
LINEAR CONVOLUTION :
Convolution is a mathematical operation just like multiplication, integration and addition
etc. The addition operation takes two numbers and produces a third one, while convolution
takes two signals and produce a third signal. For Linear Time Invariant systems (LTI), the
convolution operation can be defined as :

y[n]=x[n]h[n]
where * denotes the convolution operation.
or

y[n]=k=x[k]h[nk]
where

x[n] = input signal

h[n] = impulse response of the LTI system

y[n]= output signal

h[n k] = impulse response shifted in time by a value k

If the input x[n] to the LTI system is [n] (delta) i.e. x[n] = [n] , the output y[n] of the
LTI system is the impulse response of the LTI system i.e. y[n] = h[n] . The delta
function has a value of one at n = 0, while it is zero for n 0.

The
impulse response of the LTI system is denoted by h[n] i.e.

CONVOLUTION PROCESS :

EXAMPLE : Write MATLAB code to implement the convolution process without


using the conv command ?
Answer :
x=input('Enter x: ');
h=input('Enter h: ');
n=length(x);
k=length(h);
x1=[x, zeros(1,k)]; h1=[h,zeros(1,n)]; % zero padding of both x[n] and
h[n] if size of x[n] size of h[n]
for r =1: n+ k -1
y(r) = 0;
for i=1:n
if(r - i+1> 0)
y(r) = y(r) + x1(i)*h1(r -i+1);
m(r) = y(r);
else
end
end
end
display('Output is:' ); m
stem(m); grid;
ylabel('y[n]');
xlabel('n');
title('Convolution without using conv function');

OUT PUT :

Enter x: [ 8 3 1 2]
Enter h: [ 2 7 1 3 1]
Output is:
m =
16

62

31

38

32

PLOT OF CONVOLUTION :

CONVOLUTION USING BUILT IN FUNCTION conv :


The result of above example can be obtained by using the built in function conv. The
MATLAB code is given as :
N1=input('Enter Length of x=');
N2=input('Enter Length of h=');
x=input('Enter Sequence x[n]=');
h=input('Enter Sequence h[n]=');
y=conv(h,x)
stem(y); grid;
ylabel('y[n]');
xlabel('n');
title('Convolution using conv function');

OUTPUT :
Enter
Enter
Enter
Enter

Length of x= 4
Length of h= 5
Sequence x[n]= [ 8 3 1 2]
Sequence h[n]= [ 2 7 1 3 1]

y =
16

62

31

38

32

PLOT OF CONVOLUTION USING conv :

Otro**************************
function = convol2(I, K)
I = double(I);
%Se obtiene el tamao en n,m y n1,m1 respectivamente, de la imagen (Ima) y
del kernel (K).
[n m]=size(I);
[n1 m1]=size(K);
%Verifica que el tamao del kernel sea mayor a la imagen.
if n>n1 && m>m1
%Se calcula el padding de cada kernel.
pad=(n1-1)/2;
%Rota el kernel a 180.
K=rot90(K,2);
%Se crea una matriz que contendr a la imagen, para insertarle ceros
alrededor dependiendo del padding.
zIm=zeros(n+(pad*2), m+(pad*2));
zIm(pad+1:n+pad,pad+1:m+pad)=I;
[n m] = size(zIm);
%Se crean variables auxiliares

I0 = zeros();
for x = pad+1: n-pad
for y=pad+1: m-pad
aux1 = zIm(x-pad: x+pad, y-pad: y+pad);

aux2 = aux1 .* K;

I0(x,y) = sum(aux2(

);

end
nd %Devuelve la imagen a su tamao original, quitandole el padd
ng. I = I0(pad+1: n-pad,pad+1: m-p
d); I = uint8

%Error que envia al ser mayor el kernel que la ima


en.
lse display('erro
');
nd
nd Les anexo una pequea funcin para hacer la convolucin en matlab, au
nque ya hay una predefinida. Espero les si
a.

You might also like