How can I vectorize my code?

6 次查看(过去 30 天)
I know vectorizing code in Matlab makes it more efficent? How do I vectorize (or approach vectorizing) my code below?
% Ask for user input
L = input('Enter the inductance (mH): ');
C = input('Enter the capacitance (nF): ');
R = input('Enter the resistance (Ohms): ');
V = input('Enter the voltage (mV): ');
% Convert unit
L = L * 1e-3; %mH to H
C = C * 1e-9; %nF to F
V = V * 1e-3; %V to V
% Calculate resonant frequency
f0 = 1 / (2 * pi * sqrt(L * C)); % in Hz
fprintf('Resonant Frequency: %.2f Hz\n', f0);
%Define the frequency scale from 0 to 10,00,000 Hz (1 Mhz)
f = 0:1:2000000;
%Vrms equation calculation to be graphed
Vrms = zeros(1,length(f));
for i=1:length(f)
w = 2 * pi * f(i);
%display;
Vrms(i) = V * R / (sqrt(R^2 + ( w*L - 1 / (w * C))^2));
end
%display graph
plot(f,Vrms);
%label the axis and title for graph
title('Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Volts (V)');

采纳的回答

Voss
Voss 2024-4-2
Vectorizing involves using element-wise operations (a.k.a. array operations), e.g., .*, ./, .^, rather than matrix operations, e.g., *, /, ^, in order to operate on all elements of an array at once rather than one element at a time (e.g., in a for loop). Sometimes (e.g., multiplying an array by a scalar) it doesn't matter whether you use the element-wise operator or the matrix operator; when in doubt, use the element-wise operator.
Below, I assume L, C, R, and V are scalars:
% Ask for user input
% L = input('Enter the inductance (mH): ');
% C = input('Enter the capacitance (nF): ');
% R = input('Enter the resistance (Ohms): ');
% V = input('Enter the voltage (mV): ');
L = 1;
C = 10;
R = 100;
V = 1;
% Convert unit
L = L * 1e-3; %mH to H
C = C * 1e-9; %nF to F
V = V * 1e-3; %V to V
% Calculate resonant frequency
f0 = 1 / (2 * pi * sqrt(L * C)); % in Hz
fprintf('Resonant Frequency: %.2f Hz\n', f0);
Resonant Frequency: 50329.21 Hz
%Define the frequency scale from 0 to 10,00,000 Hz (1 Mhz)
f = 0:1:2000000;
%Vrms equation calculation to be graphed
w = 2 * pi * f; % <- w is a vector the same size as f
Vrms = V * R ./ (sqrt(R^2 + ( w*L - 1 ./ (w * C)).^2)); % <- Vrms is a vector the same size as w (and therefore f)
%display graph
plot(f,Vrms);
%label the axis and title for graph
title('Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Volts (V)');
  2 个评论
Bob Meyes
Bob Meyes 2024-4-2
Thanks. Also is there any way to use linspace to calculate frequency range?
Voss
Voss 2024-4-2

You're welcome!

Yes, you can use linspace:

f = linspace(0,2e6,2e6+1);

I used 2000001 points there because that's how many are in the original.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by