How can I vectorize my code?

6 views (last 30 days)
Bob Meyes
Bob Meyes on 2 Apr 2024
Commented: Voss on 2 Apr 2024
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)');

Accepted Answer

Voss
Voss on 2 Apr 2024
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 Comments
Bob Meyes
Bob Meyes on 2 Apr 2024
Thanks. Also is there any way to use linspace to calculate frequency range?
Voss
Voss on 2 Apr 2024

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.

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics 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!