How can I apply filter with loop-based function instaed of using filter( ) : built in MATLAB function?

36 vues (au cours des 30 derniers jours)
Hello
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);
plot(n,x)
%% Example : HPF
%{
Difference Equation
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
figure();
plot(n,x);
title("x with HPF")
xlabel('\omega (rad)');
hold();
plot(n,y_hpf1);

Réponses (1)

Jan
Jan le 17 Sep 2022
Modifié(e) : Jan le 17 Sep 2022
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.
  3 commentaires
Krittanai
Krittanai le 18 Sep 2022
Also, I have to use "y[n] = 0.5x[n] + 0.4x[n-1] + 0.1x[n-2]" & "y[n] = 0.5x[n] - 0.4x[n-1] - 0.1x[n-2]" as the problem states.
Jan
Jan le 18 Sep 2022
Modifié(e) : Jan le 18 Sep 2022
@Krittanai: "but I can't" - please mention, what this means. It is easier to solve a problem than to guess, what the problem is. So if you get an error message, read it and if you do not understand it, post a copy of the complete copy here. If the result differ from your expectations, explain the difference.
The simple method myFilter assumes, that the filter parameters a and b have the correct dimensions:
a = [2, 0, 0]; % Not just a = [2]
b = [0.5 0.4 0.1];
You find a version on the linked page, which cares for scalar a also (Link)
"I have to use "y[n] = 0.5x[n] + 0.4x[n-1] + 0.1x[n-2]" " - then simply convert this to Matlab:
for k = 3:length(x)
y(k) = 0.5 * x(k) + 0.4 * x(k-1) + 0.1 * x(k-2);
end
I've inserted * for the multiplication and converted [ and ] to ( and ). You see, this is not magic.
I've mentioned before, that the first 2 elements of y need extra care.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Signal Generation and Preprocessing dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by