How to make sinewives with array input and for-loop?

3 views (last 30 days)
if true
% code
function output = analog_filter1(input)
%
% Simulated analog filter used in Problem 1.3
%
Ts = .001;
N = 1000;
t = (0:999)*Ts;
make_an_array = [2 10 15 20 30 40 50 60 80 90 100 150 200 300 400];
f = make_an_array;
for i=1:length(t)
input(i)=sin(2*pi*f(1)*t(i));
end
[b,a] = butter(4,.02,'High');
[b1,a1] = butter(2,0.12);
input = filter(b1,a1,input);
output = filter(b,a,input);
for i=1:length(output)
G(i) = 20*log(output/f(1));
end
semilogx(f,G,'x')
xlabel('frequency in Hz')
ylabel('Gain dB')
A = max(output);
grid on
disp(A)
end
This is a brief explaination about what I am trying to find: 1. Amplitude of the output with max operator (variable A) 2. Sine wives using input frequencies in an array (variable f) and use a for-loop (input (i)) 3. Plot the 20 log of the output values against the frequency array using the semilogx. 4. I dont know about how to 'store the maximum values of the flter’s output in an array for plotting'. And then, I got error message "Subscripted assignment dimension mismatch."

Answers (1)

Himanshu
Himanshu on 23 Oct 2024 at 7:13
Hi Venya,
Here is a revised version of your code.
function output = analog_filter1()
% Simulated analog filter used in Problem 1.3
Ts = 0.001;
N = 1000;
t = (0:N-1) * Ts;
make_an_array = [2 10 15 20 30 40 50 60 80 90 100 150 200 300 400];
f = make_an_array;
max_values = zeros(1, length(f)); % Array to store maximum values
for i = 1:length(f)
input = sin(2 * pi * f(i) * t); % Generate sine wave for each frequency
[b, a] = butter(4, 0.02, 'high');
[b1, a1] = butter(2, 0.12);
input = filter(b1, a1, input);
output = filter(b, a, input);
max_values(i) = max(output); % Store the maximum value of the output
end
G = 20 * log10(max_values); % Calculate 20 log of the maximum values
semilogx(f, G, 'x');
xlabel('Frequency in Hz');
ylabel('Gain (dB)');
grid on;
disp(max_values); % Display the maximum values
end
Key Changes:
  1. The input parameter has been reomved and the function now generates the input internally.
  2. Generate sine waves for each frequency in the array with the help of a loop.
  3. Use an array max_values to store the maximum output values for each frequency.
  4. Calculate the 20 log of the maximum values and plot them using semilogx.
Explanation:
  1. For each frequency in the array f, a sine wave is generated.
  2. The sine wave is filtered using two Butterworth filters.
  3. The maximum value of the filtered output is stored in the max_values array.
  4. The 20 log of the maximum values is plotted against the frequency array using semilogx.
I have confirmed on my end that the above changed resolve the “Subscripted assignment dimension mismatch” error and correctly plot the desired graph.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!