Wednesday 19 March 2014

Convolution Function Matlab Code

This is the function of doing discrete convolution in matlab.  The problem with the existing "conv" function of Matlab is that it can not display the negative indexes of the resulted output sequence. But with this Function we can also calculate and can display the negative indexes of the output signal.

The other good thing about this function is that it automatically set the axis of the output ,input and impulse sequences in accordance with your given values and the resulted output.

This code is for purely learning purposes
Feel free to ask Questions





function [yyy,ny]=conv_m(x,nx,h,nh)            

nyb=nx(1)+nh(1);                            %take 1st value of index of x and add it with the first value of index of h
nye=nx(length(x))+nh(length(h));      %adding last indexes of both sequences by taking the length of seq
ny=[nyb:nye]                                   % concatenating above indexes to get the index of output



% Method of convolution used  is cross multiplication. In which we multiply each value of impulse sequence with input sequence i-e x. then at the we add them jus like simple multiplication

y1=h(length(h)).*x;                      %  multiplying element by element using " .* " operator    
y1=[zeros(1,length(h)-1),y1];       % doing zero padding in order to make the vectors of same length
y4=h(1).*x;
y4=[y4,zeros(1,length(h)-1)];

y0=length(h)+length(x)-1;
y=zeros(1,y0);

k=1;
j=2;

 for z=1:length(h)-2
    
y2=h(length(h)-k).*x;
y2=[zeros(1,length(h)-j),y2,zeros(1,k)];

y=y+y2;

k=k+1;
j=j+1;

 end

yyy=y+y4+y1

subplot(3,1,1)
stem(nx,x,'fill','linewidth',2)
axis([nx(1) nx(length(nx)) min(x) max(x)])
ylabel('x[n]')
xlabel('index of x')
legend('x[n]')

subplot(3,1,2)
stem(nh,h,'fill','linewidth',2)
axis([nh(1) nh(length(nh)) min(h) max(h)])
ylabel('h[n]')
xlabel('index of h')
legend('impulse h[n]')

subplot(3,1,3)
stem(ny,yyy,'fill','linewidth',2)
axis([ny(1) ny(length(ny)) min(yyy) max(yyy)])
ylabel('y[n]')
xlabel('index of y')
legend('y[n]=x[n]*h[n]')

end

No comments:

Post a Comment