Vectors must be the same length

5 次查看(过去 30 天)
Hello,
Although my code is at a beginner's level (see below), I can't get rid of the error you see in the attached photo.
I haven't really understood the problem, so I can't find a way to correct the length of these vectors.
Maybe there's an easier way to write my code.
Thanks for helping me out ;)
% --------------
% | EXERCISE 3 | - RLC Circuit
% --------------
% DE useful to describe the behaviour of the
% RLC Circuit's components over time
%********************************************************
% Non-homogeneous equation
% | ay''(t) + by'(t)+cy(t) = u(t) |
% Kirchhoff's voltage law in RLC Circuits
% | Lq''(t) + Rq'(t) + 1/Cq(t) = u(t) |
% with L Inductance (Henry H)
% R resistor's resistance (ohms)
% C capacitor's capacitance (Farads F)
% q(t) capacitor's charge at a time t (Coulombs C)
% i(t) current through the circuit at time t (Amperes A)
% u(t) applied voltage (Volts V)
% Remove all variables and functions from the memory
clear;
close all;
disp('start');
start
% Given parameters
R = 1;
L = 0.2;
C = 0.5;
U = 1;
T = 3; % Time span
% Initial conditions
q0 = 0; % Initial capacitor's charge
q_dot_0 = 0; % Initial charge's derivative, = current
% Time span for plotting
tspan = linspace(0, T, 100);
% Solve the DE with ODE45
[t, q] = ode45(@(t, q) (U - (R * q) / L - q / (L * C)), tspan, [q0, q_dot_0]);
% Calculate current and voltages
i = diff(q(:, 1)) ./ diff(t); % Current derivative
U_R = R * i; % Resistor's voltage
U_L = L * diff(i); % Coil's voltage
U_C = q(:, 1) / C; % Capacitor's voltage
% Plot Graph
figure;
plot(t, U_R, 'LineWidth', 1.5);
Error using plot
Vectors must be the same length.
hold on;
plot(t, U_L, 'LineWidth', 1.5);
plot(t, U_C, 'LineWidth', 1.5); % Remove the initial value to match lengths
hold off;
titleText = sprintf('Evolution of the voltage in the components of a RLC-circuit (R = %.2f, L = %.2f, C = %.2f, U = %.2f)', R, L, C, U);
title(titleText);
xlabel('Time t');
ylabel('Voltage (V)');
legend({'U_R', 'U_L', 'U_C'}, 'FontSize', 12);
grid on;
disp('done');

采纳的回答

Matt J
Matt J 2024-3-15
编辑:Matt J 2024-3-15
i = gradient(q(:, 1),t); % Current derivative
U_R = R * i; % Resistor's voltage
U_L = L * gradient(i,t); % Coil's voltage
disp('done');
done

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by