How I can plot input signal in ode45

4 次查看(过去 30 天)
I want to plot the control signal (u) when we solve the equation with ode45. how I can plot control signal (u) in the following code.
tspan = 0:1:10000;
y0 = [0.2,0.3];
[t,y] = ode45(@(t,y) odefcn(t,y), tspan, y0);
%
function dx = odefcn(t,x)
dx = zeros(2,1);
u=[2 -2]*x(1:2)+1;
dx(1)=x(1)-2*x(2)
dx(2)=-x(2)+u
end

采纳的回答

Star Strider
Star Strider 2023-10-12
Create a second output for ‘u’ (ode45 will ignore it during the integration) and then return it using a for loop after the integration finishes.
Try this —
tspan = 0:0.001:15;
y0 = [0.2,0.3];
[t,y] = ode45(@(t,y) odefcn(t,y), tspan, y0);
for k = 1:numel(t)
[dx,u(k)] = odefcn(t(k),y(k,:).');
end
figure
plot(t,y(:,1), 'DisplayName','y_1(t)')
hold on
plot(t,y(:,2), 'DisplayName','y_2(t)')
plot(t,u, 'DisplayName','u(t)')
hold off
grid
legend('Location','best')
% set(gca,'XScale','log')
function [dx,u] = odefcn(t,x)
dx = zeros(2,1);
u=[2 -2]*x(1:2)+1;
dx(1)=x(1)-2*x(2);
dx(2)=-x(2)+u;
end
I changed ‘tspan’ because with a long vector, the details of the initial transient disappear from the plot.
.
  1 个评论
Dyuman Joshi
Dyuman Joshi 2023-10-12
Nice answer, @Star Strider.
Just a small suggestion to preallocate u and negate the output dx if it is needed.

请先登录,再进行评论。

更多回答(1 个)

Sam Chak
Sam Chak 2023-10-13
Your initial query has already been addressed. To achieve step profile tracking using your designed gain matrix, you should multiply the reference input (xref) by a scaling factor (sf). In doing so, the blue curve will consistently attain its steady-state position .
tspan = 0:0.001:10;
x0 = [0.2, 0.3];
[t, x] = ode45(@odefcn, tspan, x0);
% Computing the control signal u from the ode solution
u = [2 -2]*x.' + (-0.5)*(1); % sf = -0.5; xref = 1;
plot(t, x(:,1), 'DisplayName', 'x_1(t)'), hold on
plot(t, x(:,2), 'DisplayName', 'x_2(t)')
plot(t, u, 'DisplayName', 'u(t)'), hold off, grid on
xlabel('Time, (seconds)')
title('Step Response')
legend('location', 'SE', 'fontsize', 12)
% Dynamics
function [dx, u] = odefcn(t, x)
dx = zeros(2,1);
xref = 1; % reference input
sf = -0.5; % scaling factor
u = [2 -2]*x + sf*xref; % control signal
dx(1) = x(1) - 2*x(2); % x'
dx(2) = - x(2) + u; % x"
end

类别

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

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by