Applying a filter on an input sequence in matlab

Given a input sequence $$x = {x_1, ... x_n}$$ and a filter with l elements $$h = [h_1, ..., h_l]$$ with l < n. We want to filter the input sequence with the specified filter.

My first thought was to compute the convolution between $$x$$ and $$h$$:

$$y = \sum_{k=0}^{l-1} x(k) h(n - k)$$

For this to work I'll have to pad x with zeros.

x = [ zeros(1, l) x zeros(1, l - 1)];

And then

for i = 1:length(x) - 2 y(k) = h * x(k:k + l)'; end 

Is this the right approach for this problem ?

• you forget to "flip" h. Also, there's a "convolve" function. – Marcus Müller Jan 27 '19 at 19:06
• Hey, You're right h should be $h = [h_l, ..., h_1]$. Other than that the approach is right, yes ? – Tony Wilson Jan 27 '19 at 19:24
• mathematically, yes, I guess. But please, never ever write such matlab code in practice: Matlab's interpreter is stupidly slow, and there's an existing function for convolution, so aside from the "finger practice", this code shouldn't exist. – Marcus Müller Jan 27 '19 at 19:27