2 January 2010 0 Comments

Matlab Tips in Signal Processing

Moving average filter

To compute an N-sample moving average of x with zero padding:

y=filter(ones(N,1)/N,1,x); 

For large N, it is faster to use

x = [1:0.2:4]';
N = 5;
windowSize = 5;
y1 = filter(ones(1,N)/N,1,x);

y2=cumsum(x)/N;
y2(N+1:end)=y2(N+1:end) - y2(1:end-N);

Locating zero-crossings and extrema

To obtain the indices where signal x crosses zero:

i=find(diff(sign(x))); % The kth zero crossing lies between x(i(k)) and x(i(k)+1)

Linear interpolation can be used for subsample estimates of zero-crossing locations:

i=find(diff(sign(x)));
i=i-x(i)./(x(i+1)-x(i)); % Linear interpolation

Since local maximum and minimum points of a signal have zero derivative,their locations can be estimated from the zero-crossings of diff(x),provided the signal is sampled with suffciently fine resolution. For a coarsely sampled signal,a better estimate is

iMax=find(sign(x(2:end-1) - x(1:end 2))...
            +sign(x(2:end 1) x(3:end)) > 0)+1;
iMin=find(sign(x(2:end-1) - x(1:end 2))...
            +sign(x(2:end 1) x(3:end)) < 0)+1;

FFT-based convolution

This line performs FFT-based circular convolution,equivalent to

y=filter(b,1,x)

except near the boundaries,provided that length(b) < length(x):

y=ifft(fft(b,length(x)).*fft(x));

For FFT-based zero-padded convolution,equivalent to

y=filter(b,1,x)

,

N=length(x)+length(b) 1;
y=ifft(fft(b,N).*fft(x,N));
y=y(1:length(x));

In both code snippets above, y will be complex-valued,even if x and b are both real.To force y to be real,follow the computation with

y=real(y)

.If you have the Signal Processing Toolbox,it is faster to use fftfilt for FFT-based,zero-padded filtering.
26

Tags: ,