How can I apply filter with loop-based function instaed of using filter( ) : built in MATLAB function?
20 views (last 30 days)
I'm trying to plot the generated signal x against filtered x with loop-based function, but I don't know how to do it. Can somebody instuct me how to do it? Here is my attached code. Thank you for your help in advance!
%% Applying the filter to data
% create time sequence n for 501 samples from 0 to 500
n = linspace(0, 500, 500+1);
% assume a signal x
x = 0.7*sin(0.02*pi*n) + sin(0.1*n)+ 0.1*sin(rand()*n);
%% Example : HPF
y[n] = 0.5x[n] + 0.4x[n-1] + 0.1x[n-2]
in a form of [a]y = [b]x
a_1 = 1; b_1 = [0.5 0.4 0.1];
% apply filter
y_hpf1 = filter(b_1,a_1,x);
% plot the generated signal x against filtered x
title("x with HPF")
Jan on 17 Sep 2022
Edited: Jan on 17 Sep 2022
You can find a Matlab function for filtering here: https://www.mathworks.com/matlabcentral/answers/9900-use-filter-constants-to-hard-code-filter#answer_13623 .
On the other hand: "y[n] = 0.5x[n] + 0.4x[n-1] + 0.1x[n-2]" is easy to implement and the question sounds like a homework assignement. Start with pre-allocating the output y, which has the same size as the input x:
y = zeros(size(x));
You cannot apply the formula to y(1), because there is no x(0) and x(-1). So use y(1) = 0.5 * x(1) and y(2) = 0.5 * x(2) + 0.4 * x(1). Then create a for loop to calculate the remaining elements.