How to plot the a figure to show the gain of filter

16 views (last 30 days)
i want to plot a figure to compare the gain(H = tf([R*C,0], [R*C,1])) of filter at each of the two frequeencies to the theory like this (green line), how to do that
could you please write code like this (lack part codes):
H = tf([R*C,0], [R*C,1]);
[mag,phas,wout] = bode(H);
y_vec = lsim(H,x_vec,t_vec);
% Compute the input and outputs in the frequency domain
in_f = fft(x_vec)/length(x_vec);
out_f = fft(y_vec)/length(x_vec);
resp = out_f./in_f;
resp(abs(out_f)<1e-4) = nan;
theory_resp_F1 = interp1(wout,mag,2*pi*F1);
theory_resp_F2 = interp1(wout,mag,2*pi*F2);
some variables are mean as follows: x_vec in this figure combine two signals, but i just want to plot a figure that the gain changes with frequency

Answers (1)

MULI
MULI on 16 Feb 2024
To compare the gain of the filter at two frequencies with the theoretical gain where the theoretical Bode plot and actual gain plotted on semilogarithmic scale using “semilogx”.
You may refer to this link for more information on this function.
Matlab code and output is given below.
% Define the parameters
R = 1e3; % Resistance in ohms
C = 1e-6; % Capacitance in farads
F1 =100; % Frequency 1 in Hz
F2 = 4e3; % Frequency 2 in Hz
% Define the transfer function H
H = tf([R*C, 0], [R*C, 1]);
% Calculate the Bode plot for H
[mag, ~, wout] = bode(H);
% Convert magnitude to linear scale
mag = squeeze(mag);
% Interpolate the theoretical response at specific frequencies F1 and F2
theory_resp_F1 = interp1(wout, mag, 2*pi*F1, 'linear', 'extrap');
theory_resp_F2 = interp1(wout, mag, 2*pi*F2, 'linear', 'extrap');
% Plot the theoretical Bode magnitude plot
figure;
semilogx(wout/(2*pi), 20*log10(mag), 'g'); % Convert to Hz and dB
hold on;
% Plot the actual gain at frequencies F1 and F2
actual_gains = [theory_resp_F1, theory_resp_F2];
actual_freqs = [F1, F2];
semilogx(actual_freqs, 20*log10(actual_gains), 'ro');
% Set plot properties
xlabel('Frequency (Hz)');
ylabel('Gain (dB)');
title('Response of RC circuit');
legend('Theoretical Gain', 'Measured response');
grid on;
% Release the plot hold
hold off;

Community Treasure Hunt

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

Start Hunting!