Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero pad a matlab array?

Tags:

matlab

What is the easiest way to (zero) pad a matlab array?
i.e. given [1,2,3,4] and length 6 return [1,2,3,4,0,0]

Background

I have a data array which I would like to apply a windowing function to before running fft on the data.

I use to pass data directly to fft which would zero pad to the next power of 2, but now I need it zero padding before the fft so I can multiply by the window function.

fs = 100;                          % Sample frequency (Hz)
t = 0:1/fs:10-1/fs;                % 10 sec sample
x = (1.3)*sin(2*pi*15*t) ...       % 15 Hz component
  + (1.7)*sin(2*pi*40*(t-2)) ...   % 40 Hz component
  + (2.5)*randn(size(t));          % Gaussian noise;

m = length(x);          % Window length
n = pow2(nextpow2(m));  % Transform length
w = barthannwin( n );   % FFT Window

y = fft(data, n);       % DFT

windowed_data = x*w ; % Dimensions do not match as x not padded
y = fft(windowed_data, n); % DFT

I am aware of padarray as part of the Image Processing Toolbox, which I do not have.

like image 485
Morgan Avatar asked Feb 15 '13 16:02

Morgan


3 Answers

EDIT

This method is probably even better for vectors as it does not break when they are transposed, note that it will change the original vector which may not be desirable:

myVec = 1:7;
myVec(end+3)=0

Alternately you can just concatenate zeros and the vector that you have and create a new variable with it.

myVec = 1:7;
requiredpadding = 10-7;
myVecPadded=[myVec zeros(1,requiredpadding)]
like image 143
Dennis Jaheruddin Avatar answered Sep 27 '22 19:09

Dennis Jaheruddin


There is no built in function to do padding, but here is a little function to pad vector x given a minimum length n.

function y = pad(x, n)
y = x;
if length(x) < n
    y(n) = 0;
end
like image 25
shoelzer Avatar answered Sep 27 '22 19:09

shoelzer


this should pad it with zeros to the nearest power of 2 for an array a:

a(2^ceil(log2(length(a))))=0;

like image 22
ZZZ Avatar answered Sep 27 '22 20:09

ZZZ