Sie sind auf Seite 1von 22

decimate

Decimation — decrease sample rate by integer factor


collapse all in page

Syntax
y = decimate(x,r)
y = decimate(x,r,n)
y = decimate(x,r,'fir')
y = decimate(x,r,n,'fir')

Description
example
y = decimate(x,r) reduces the sample rate of x, the input signal, by a factor of r. The
decimated vector, y, is shortened by a factor of r so that length(y) = ceil(length(x)/r).
By default, decimate uses a lowpass Chebyshev Type I infinite impulse response (IIR) filter of
order 8.
example
y = decimate(x,r,n) uses a Chebyshev filter of order n.
y = decimate(x,r,'fir') uses a finite impulse response (FIR) filter designed using the
window method with a Hamming window. The filter has an order of 30.
example
y = decimate(x,r,n,'fir') uses an FIR filter of order n.
Examples
collapse all
Decimate Signal
Try This Example
Create a sinusoidal signal sampled at 4 kHz. Decimate it by a factor of four.
t = 0:.00025:1;
x = sin(2*pi*30*t) + sin(2*pi*60*t);
y = decimate(x,4);
Plot the original and decimated signals.
subplot 211
stem(0:120,x(1:121),'filled','markersize',3)
grid on
xlabel 'Sample number',ylabel 'Original'
subplot 212
stem(0:30,y(1:31),'filled','markersize',3)
grid on
xlabel 'Sample number',ylabel 'Decimated'
Decimate Signal Using Chebyshev Filter
Try This Example
Create a signal with two sinusoids. Decimate it by a factor of 13 using a Chebyshev IIR filter of
order 5. Plot the original and decimated signals.
r = 13;
n = 16:365;
lx = length(n);
x = sin(2*pi*n/153) + cos(2*pi*n/127);

plot(0:lx-1,x,'o')
hold on
y = decimate(x,r,5);
stem(lx-1:-r:0,fliplr(y),'ro','filled','markersize',4)

legend('Original','Decimated','Location','south')
xlabel('Sample number')
ylabel('Signal')
The original and decimated signals have matching last elements.
Decimate Signal Using FIR Filter
Try This Example
Create a signal with two sinusoids. Decimate it by a factor of 13 using an FIR filter of order 82.
Plot the original and decimated signals.
r = 13;
n = 16:365;
lx = length(n);
x = sin(2*pi*n/153) + cos(2*pi*n/127);

plot(0:lx-1,x,'o')
hold on
y = decimate(x,r,82,'fir');
stem(0:r:lx-1,y,'ro','filled','markersize',4)

legend('Original','Decimated','Location','south')
xlabel('Sample number')
ylabel('Signal')
The original and decimated signals have matching first elements.

Input Arguments
collapse all
x — Input signal
vector
Input signal, specified as a vector.
Data Types: double | single
r — Decimation factor
positive integer
Decimation factor, specified as a positive integer. For better results when r is greater than 13,
divide r into smaller factors and call decimate several times.
Data Types: double | single
n — Filter order
positive integer
Filter order, specified as a positive integer. IIR filter orders above 13 are not recommended
because of numerical instability. The function displays a warning in those cases.
Data Types: double | single

Output Arguments
collapse all
y — Decimated signal
vector
Decimated signal, returned as a vector.
Data Types: double | single
Algorithms
Decimation reduces the original sample rate of a sequence to a lower rate. It is the opposite of
interpolation. decimate lowpass filters the input to guard against aliasing and downsamples the
result. The function uses decimation algorithms 8.2 and 8.3 from [1].
1. decimate creates a lowpass filter. The default is a Chebyshev Type I filter designed
using cheby1. This filter has a normalized cutoff frequency of 0.8/r and a passband ripple
of 0.05 dB. Sometimes, the specified filter order produces passband distortion due to round-
off errors accumulated from the convolutions needed to create the transfer
function.decimate automatically reduces the filter order when distortion causes the
magnitude response at the cutoff frequency to differ from the ripple by more than 10–6.
When the 'fir' option is chosen, decimate uses fir1 to design a lowpass FIR filter with
cutoff frequency 1/r.
2. When using the FIR filter, decimate filters the input sequence in only one direction. This
conserves memory and is useful for working with long sequences. In the IIR
case, decimate applies the filter in the forward and reverse directions using filtfilt to
remove phase distortion. In effect, this process doubles the filter order. In both cases, the
function minimizes transient effects at both ends of the signal by matching endpoint
conditions.
3. Finally, decimate resamples the data by selecting every rth point from the interior of the
filtered signal. In the resampled sequence (y), y(end) matches x(end) when the IIR filter is
used, and y(1) matches x(1) when the FIR filter is used.

References
[1] Digital Signal Processing Committee of the IEEE® Acoustics, Speech, and Signal Processing
Society, eds. Programs for Digital Signal Processing. New York: IEEE Press, 1979.

See Also
cheby1 | downsample | filtfilt | fir1 | interp | resample

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

downsample
Decrease sample rate by integer factor
collapse all in page

Syntax
y = downsample(x,n)
y = downsample(x,n,phase)

Description
example
y = downsample(x,n) decreases the sample rate of x by keeping the first sample and then
every nth sample after the first. If x is a matrix, the function treats each column as a separate
sequence.
y = downsample(x,n,phase) specifies the number of samples by which to offset the
downsampled sequence.
Examples
collapse all
Decrease Sample Rates
Try This Example
Decrease the sample rate of a sequence by a factor of 3.
x = [1 2 3 4 5 6 7 8 9 10];
y = downsample(x,3)
y = 1×4

1 4 7 10

Decrease the sample rate of the sequence by a factor of 3 and add a phase offset of 2.
y = downsample(x,3,2)
y = 1×3

3 6 9

Decrease the sample rate of a matrix by a factor of 3.


x = [1 2 3;
4 5 6;
7 8 9;
10 11 12];
y = downsample(x,3)
y = 2×3

1 2 3
10 11 12

Input Arguments
collapse all
x — Input array
vector | matrix
Input array, specified as a vector or matrix. If x is a matrix, the function treats the columns as
independent channels.
Example: cos(pi/4*(0:159)) + randn(1,160) specifies a sinusoid embedded in white
Gaussian noise.
Example: cos(pi./[4;2]*(0:159))' + randn(160,2) specifies a two-channel noisy
sinusoid.
Data Types: single | double
Complex Number Support: Yes
n — Downsampling factor
positive integer
Downsampling factor, specified as a positive integer.
Data Types: single | double
phase — Offset
0 (default) | positive integer
Offset, specified as a positive integer from 0 to n – 1.
Data Types: single | double

Output Arguments
collapse all
y — Downsampled array
vector | matrix
Downsampled array, returned as a vector or matrix.

Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
See Also
decimate | interp | interp1 | resample | spline | upfirdn | upsample

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear, clc, close all

% signal parameters
fs = 50;
f0 = 10;
T = 0.5;
xlen = round(fs*T);

% time vector
t = (0:xlen-1)/fs;

% signal generation
x = sin(2*pi*f0*t + pi/4);

% interpolation factor
intfact = 10;

% interpolation
xhat = interpolate(x, intfact);

% new time vector


xhatlen = length(xhat);
that = (0:xhatlen-1)/(fs*intfact);

% plot the two signals


figure(1)
plot(t, x)
grid on
hold on
plot(that, xhat, '.r')
set(gca, 'FontName', 'Times New Roman', 'FontSize', 14)
axis([0 T -1.2 1.2])
xlabel('Time, s')
ylabel('Amplitude')
title('Interpolation of a signal')
legend('Original signal', 'Interpolated signal')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Signal Interpolation via Spectral Processing %
% with MATLAB Implementation %
% %
% Author: M.Sc. Eng. Hristo Zhivomirov 06/01/14 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function xhat = interpolate(x, intfact)

% function: xhat = interpolate(x, intfact)


% x - original singnal
% intfact - interpolation factor
% xhat - interpolated signal

% determine the signal size


sz = size(x);

% represent x as column-vector
x = x(:);

% length of the signal


xlen = length(x);

% number of unique fft points


NUP = ceil((xlen+1)/2);

% FFT
X = fft(x(:));

% calculate the number of the padding zeros


zerolen = round(xlen*(intfact - 1));

% form a new spectrum


Xhat = [X(1:NUP); zeros(zerolen, 1); X(NUP+1:end)];

% check for Nyquist point and make correction


if ~rem(xlen, 2)
Xhat(NUP) = Xhat(NUP)/2;
Xhat(NUP+zerolen) = Xhat(NUP);
end

% IFFT
xhat = real(ifft(Xhat));

% correction of the amplitude


xhat = xhat*intfact;

% represent the interpolated signal in the form of the original one


if sz(2) > 1
xhat = xhat';
end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

intfilt
Diseño de filtro de la interpolación del abeto
colapso en página

Sintaxis de
b = intfilt(l,p,alpha)
b = intfilt(l,n,'Lagrange')

Descripción
b = intfilt(l,p,alpha) diseña un filtro FIR de fase lineal que realiza interpolación ideal
pasa-banda con la más cercana 2*p distinto de cero muestras, cuando se utiliza en una
secuencia de intercalado con l-1 consecutivos ceros de cada muestras de l . Supone un
original bandlimitedness de alfa veces la frecuencia de Nyquist. El filtro devuelto es idéntico al
utilizado por interp. b es la longitud de 2 *l*p-1.
alfa es inversamente proporcional a la anchura de banda de transición del filtro y también
afecta el ancho de banda de las regiones de atención no en el stopband. Especificación de alfa
le permite especificar cuántas del intervalo de Nyquist de la señal de entrada ocupa. Esto es
beneficioso, particularmente para las señales a ser interpolados, ya que le permite incrementar
el ancho de banda de transición sin afectar a la interpolación y resulta en mejor atenuación del
stopband dado l y p. Si establece alfa 1, la señal se supone que ocupan el intervalo de Nyquist
completo. Alfa ajuste a menos de un permite a regiones de atención no en el stopband. Por
ejemplo, si su entrada ocupa la mitad del intervalo de Nyquist, se podría establecer alfa a 0.5.
b = intfilt(l,n,'Lagrange') diseña un filtro FIR que realiza nth-orden Interpolación
polinómica de Lagrange en una secuencia de intercalado con l-1 ceros consecutivos cada
muestras r . b tiene longitud (n+1)*l para n uniforme y de longitud (n+1)*l-
1 para n impar. Si n y l están incluso, el filtro no es fase lineal.
Ambos tipos de filtros son básicamente paso bajo y tienen una ganancia de l en la banda
pasante.

Ejemplos
contraer todo
Filtro de interpolación digital
Probar este ejemplo
Diseño de un filtro de interpolación digital que muestra una señal siete, utilizando el método de
pasa-banda. Especificar un factor de "bandlimitedness" de 0.5 y utilizar muestras en la
interpolación.
upfac = 7;
alpha = 0.5;
h1 = intfilt(upfac,2,alpha);
El filtro funciona mejor cuando la señal original es pasa-banda alpha veces la frecuencia de
Nyquist. Generar 200 números aleatorios gaussianos y la secuencia de filtrado con un filtro de
paso bajo de abeto de 40-orden para crear una señal de ruido de pasa-banda. Reiniciar el
generador de números aleatorios para obtener resultados reproducibles.
lowp = fir1(40,alpha);

rng('default')
x = filter(lowp,1,randn(200,1));
Aumentar la frecuencia de muestreo de la señal mediante la inserción de ceros entre cada par
de muestras de x.
xr = upsample(x,upfac);
Utilice la función filter para producir una señal interpolada.
y = filter(h1,1,xr);
Compensar el retardo introducido por el filtro. Parcela las señales originales e interpoladas.
delay = mean(grpdelay(h1));

y(1:delay) = [];

stem(1:upfac:upfac*length(x),x)
hold on
plot(y)

xlim([400 700])
intfilt también realiza Interpolación polinómica de Lagrange.

 Interpolación polinomial de primer orden es interpolación sólo lineal, que se logra con un filtro
triangular.
 Interpolación de la zeroth-orden se logra con un filtro de media móvil y se asemeja a la salida
de indicación de muestreo y retención.
Interpolación de la señal original y el resultado del recubrimiento.
h2 = intfilt(upfac,1,'Lagrange');

y2 = filter(h2,1,xr);
y2(1:floor(mean(grpdelay(h2)))) = [];

plot(y2)
hold off
Algoritmos de
El método de pasa-banda utiliza firls para diseñar un filtro FIR de interpolación. El método
polinómico utiliza la fórmula de Interpolación polinómica de Lagrange en muestras igualmente
espaciadas para construir el filtro apropiado.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Interpolation/Up sampling MATLAB


source code
This section of MATLAB source code covers interpolation or up
sampling matlab code. It covers basics of interpolation/up sampling.
Interpolation refers to adding samples in between the existing vector of
values. By doing so sample rate of the signal or vector will increase
hence it is referred as up sampling the signal.

The best approach is to insert approximate values of two samples for


adding the in between sample values. There are various techniques such
as nearest, linear,spline,cubic etc.
Setting up exponential vector to be
upsampled
clc;
clear all;
n=input('enter length of input sample sequence:');
l=input('enter the value of up-sampling factor:');

m=0:n-1;
a=input('enter the value of base of exponent function:');
x=a.^m;
Upsampling the exponential vector
y=zeros(1,l*length(x));
y([1:l:length(y)])=x;
%figure,plot(x);
%figure,plot(y);
figure,stem(m,x);xlabel({'Time
n';'(a)'});ylabel('Amplitude');title('Interpolation input');
figure,stem(m,y(1:length(x)));xlabel({'Time
n';'(b)'});ylabel('Amplitude');title('upsampled output');
Upsampling using resample matlab
function
xi=x;
yi = resample(xi,l,1);
figure,stem(m,yi(1:length(x)));xlabel({'Time
n';'(b)'});ylabel('Amplitude');title('upsampled output using matlab function');
Other MATLAB function for interpolation or upsampling is 'interp1' .

Input and Output


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

VERIFICATION OF INTERPOLATION AND


DECIMATION USING MATLAB
PROGRAM TO VERIFY DECIMATION
AND INTERPOLATION OF A GIVEN
SEQUENCE
Introduction
% Software Used: Matlab Version 7.6.0.324
% Submitted by : GG

Initial Command (Closing and Clearing)


clc; % clears the command window
close all; % closes all the previously open window
clear all; % clears previously stored values

Generating Input Sequence


fm = 10; % input signal frequency
Fs = 140; % sampling frequency
t = 0:1/Fs:0.5; % time range for the input sequence
x = sin(2*pi*fm*t); % input sinusoidal signal
figure(1)
subplot(4,1,1)
stem(x); % Discrete plot of the input sequence,...
... where x-axis corresponds to the number of samples
xlabel('No. of samples'); % labelling x-axis
ylabel('Amplitude'); % labelling y-axis
title('input discrete sinusoidal sequence'); % giving title to the plot

% Inference: A sinsoidal input signal was generated with the signal


% frequenccy of 10 Hz and was again sampled using the sampling frequency of
% 140 Hz which is well above to satisfy the nyquist criterion.So, we
% obtained 72 samples from 0 to 0.5 sec when sampled at 140 Hz. The
% obtained sinusoidal sequence was subjected to discrete plot using
% stem plot option which plots the sampled signal amplitude with respect
% to the number of samples. The first plot of the figure corresponds to
% the generated sinusoidal sequence

Decimation of the Input Sequence


M = 2; % factor by which the input sequence is decimated
xd = decimate(x,M); % resamples the sample in x with a rate (1/M) times the original rate
subplot(4,1,2)
stem(xd) % Discrete plot of the input sequence,...
... where x-axis corresponds to the number of samples
xlabel('No. of samples'); % labelling x-axis
ylabel('Amplitude'); % labelling y-axis
title('Decimated Sinusoidal Sequence'); % giving title to the plot

% Inference: The obtained sinusoidal sequence was subjected for the


% decimation by the factor M = 2. The process of decimation involves
% resampling the sequence in low data rate after the process of low pass
% filtering.Since the given sequence is decimated by the factor 2,
% the resultant sequence after the decimation should have exactly
% half the number of samples than that of the original sequence.
% It is clearly seen in the plot that the decimated sequence has
% 36 samples in comarison to 72 of the original sample. Hence
% the decimation of a sequence is verified.

Interolation of the Input Sequence


L = 2; % factor by which the input sequence is interpolated
xI = interp(x,L); % resamples the sample in x with a rate L times the original rate
subplot(4,1,3);
stem(xI); % Discrete plot of the input sequence,...
... where x-axis corresponds to the number of samples
xlabel('No. of samples'); % laeblling x-axis
ylabel('Amplitude'); % labelling y-axis
title('Interpolated Sinuoidal Sequence') % giving title to the plot

% Inference: The obtained sinusoidal sequence was also subjected for the
% interpolation by the factor L = 2. The Process of interpolation involves
% resampling the sequence at higher sampling rate using low pass filter.
% Since the interpolation factor is 2, the samples in interpolated signal
% must double than that of the original signal and it can be verfied from
% the plots obtained. Hence the interpolation is also verfied.

Interpolation of the Decimated Signal


L = 2; % coefficient by which the singal is interpolated
xI = interp(xd,L); % resamples the sample in x with a rate L times the original rate
subplot(4,1,4)
stem(xI); % Discrete plot of the input sequence,...
... where x-axis corresponds to the number of samples
xlabel('No. of samples'); % labelling x-axis
ylabel('Amplitude'); % labelling y-axis
title('Original Signal Obtained After Interpolating the Decimated Signal'); % giving title to the
graph

% Inference: When a sequence is decimated by a certain factor and then


% again subjected to the interpolation by the same factor, original
% sequence can be recovered. This has been verified by the 4th plot
% on the figure, which is the interpolation of the decimated signal in the
% 2nd plot. The 4th plot obtained is similar to the input sequence. So,
% interpolating a decimated signal or decimating a interpolated signal
% gives the original signal.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Upsampling is a process of inserting zero-amplitude samples between original samples to increase the
sampling rate. (also called zero stuffing) whereas Interpolation is the process of upsampling followed by
filtering(Low Pass) to create in between samples from the original spaced samples.It can be just viewed that
we are adding the average value of the original sample in place of zero valued samples.
Up-sampling & Interpolating of Original Signal using MATLAB : MATLAB code for Upsampling & Interpolation
MATLAB code for Up-sampling & Interpolation
clc;
close all;
clear all;
n=input('Enter length of input sequence:');
l=input('Enter up-sampling factor:');

m=0:n-1; %making a vector m from the lenght of input sequence


a=input('Enter Slope of Ramp Signal:');
x = (0:n-1)*a; % for generating ramp signal x with a slope of a
%replace your own signal/sequence with the variable x

figure,stem(m,x);
xlabel('Time N');
ylabel('Amplitude');
title('Input Signal');

lx = n;
y = 0;
y(1) = x(1);
for i=2:lx
c = [zeros(1,l-1),x(i)]; %inserting zeros in between original samples
y = [y,c];
end

nm=0:length(y)-1;
figure,stem(nm,y); %Upsampled version of signal
xlabel('Time N');
ylabel('Amplitude');
title('Up-Sampled Output of Signal');

xi=x;
yi = interp(xi,l);
nn=0:length(yi)-1;
figure,stem(nn,yi); %interpolation output
xlabel('Time N');
ylabel('Amplitude');
title('Interpolator Output');

Sample Input through MATLAB command Window:


Enter length of input sequence:10
Enter up-sampling factor:2
Enter Slope of Ramp Signal:2

Output of above Inputs:

Original Input Signal : MATLAB Plot


Up-sampled Version of the signal : MATLAB Plot
Up-sampled & Interpolated Version of the signal : MATLAB Plot

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
I had a real digital signal with digital frequency f1=1/5.Changed
the sample rate by a factor of 5/8 through a combination of
filtering,decimation and interpolation.

Then I plotted the power spectrum of the original signal and then
the changed signal.The signal seemd to have been attenuated (apart
from the effects of interpolation,decimation i had expected) why?

Here is my code: amp = 1; %The amplitude


numSam = 64; %Number of samples
freq = 1; %Frequency
Fs = 5; %Sampling frequency
Ts =1/Fs;
t = (0:Ts:(numSam-1)*Ts);

%Getting the cos wave


cosine = amp*cos(2*pi*freq*t);

%Getting the fourier transform of the signal and calculating


%the power spectrum.
fourier = fft(cosine);
PowerSpectrum = (abs(fourier)).^2;

%Converting the power spectrum to dB.


PowerSpectrum_DB = 10.*log10(PowerSpectrum);
Fd = (0:(numSam-1))/numSam; %Getting the digital frequency
Fd1 = (0:(numSam*5/8-1))/(numSam*5/8);

resampledSignal = resample(cosine,5,8);
resampledSignal_fft = fft(resampledSignal);
resampledSignal_Power = (abs(resampledSignal_fft)).^2;
resampledSignal_Power_dB = 10.*log10(resampledSignal_Power);
figure(1)
subplot(2,1,1);

stem(Fd(1:(numSam)/2),PowerSpectrum_DB(1:((numSam)/2)),'b') grid on;


xlabel('Digital Frequency');
ylabel('Power Spectrum ');
title('\bfPower Spectrum Vs Digital Frequency');
subplot(2,1,2)
resampledSignal = resample(cosine,5,8);
resampledSignal_fft = fft(resampledSignal);
resampledSignal_Power = (abs(resampledSignal_fft)).^2;
resampledSignal_Power_dB = 10.*log10(resampledSignal_Power);
stem(Fd1(1:(numSam)/2),resampledSignal_Power_dB(1:((numSam)/2)),'r')
grid on;

Das könnte Ihnen auch gefallen