필터 지우기
필터 지우기

How can I vectorize my code?

조회 수: 1 (최근 30일)
Bob Meyes
Bob Meyes 2024년 4월 2일
댓글: Voss 2024년 4월 2일
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에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by