I noticed a few areas in the MATLAB code that we can improve upon to get it running :
- In MATLAB, we need to define functions like `Gx(f)` in a specific way. Instead of defining it within the script, let's set it up as an anonymous function to ensure it works correctly.
- To properly evaluate `Gx(f)`, we'll need to create a frequency vector `f`. This will allow us to analyse the function over a specified range of frequencies.
- When using the `find` function, you have to be careful to handle cases where it might return an empty array, as this could lead to errors when trying to access array elements.
Here is the revised code for the same:
% Clear the workspace and command window
clc;
clear all;
% Define a frequency range to analyze the signal
f = linspace(0, 2*10^6, 1000); % This is an example range from 0 to 2 MHz.
% Set up the signal function as an anonymous function for flexibility
Gx = @(f) 10^-4 .* (sin(pi.*(f-10^6).*10^-4) ./ (pi.*(f-10^6).*10^-4));
% Compute the magnitude spectrum for our signal
Gf = Gx(f);
% Now, let's calculate the bandwidths according to the different definitions
hp_bw = half_power_bw(f, Gf);
nn_bw = null_to_null_bw(f, Gf);
p99_bw = power_bw(f, Gf, 0.99);
att_bw = attenuation_bw(f, Gf, 35);
% We'll display the results in a reader-friendly format
disp(['Half-power Bandwidth: ', num2str(hp_bw)]);
disp(['Null-to-Null Bandwidth: ', num2str(nn_bw)]);
disp(['99% Power Bandwidth: ', num2str(p99_bw)]);
disp(['Bandwidth beyond 35 dB attenuation: ', num2str(att_bw)]);
% Here are the function definitions
function Bw = half_power_bw(f, Gf)
% ... your existing code for half_power_bw ...
end
function Bw = null_to_null_bw(f, Gf)
% ... your existing code for null_to_null_bw ...
end
function Bw = power_bw(f, Gf, power_fraction)
% ... your existing code for power_bw ...
end
function Bw = attenuation_bw(f, Gf, attenuation_dB)
% ... your existing code for attenuation_bw ...
end
Refer to the following Mathworks Documentation for usage of anonymous functions & function handles :
- https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html
- https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html
- https://www.mathworks.com/help/matlab/ref/find.html
Best regards,
Chetan Verma