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]
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.
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)]
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
this should pad it with zeros to the nearest power of 2 for an array a
:
a(2^ceil(log2(length(a))))=0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With