Extracting an intermediate vector from ode45

3 views (last 30 days)
Hello,
I have done search in the forum and found how to exract a variable from a ODE45 function. I'm trying to do the same, though, I'm not able to do it. I need some help on this. s, u and z variables they are suposed to be arrays but I dont know why I can only extract a single value from them. How can I take the whole array from them?
close all;
clc;
%% CONTEXT
% create an observer that estimates x2 while sliding variable and x1,x2
% tends to 0
% x1'=x2 x1(0)=x10
% x2'= u + f(x1,x2,t) x2(0)=x20
% y = x1
% injection term (sliding mode observer)
% v = x1' = x2 = -r1*sign(z1)
% auxiliar sliding variable is the error estimation
% z1= x1s - x1
%% INIT
t0=0;
tfinal= 8;
% solving the ode
tspan = linspace(t0, tfinal, 8e4);
x0 = [1 -2 0 0];
[t, x] = ode45(@(t,x) smc_obsv(t,x), tspan, x0);
%
[~, s,u,z] = smc_obsv(t, x);
%% plotting the solution
figure()
plot(t,x(:,3),'k', 'LineWidth',2)
set(gca,'FontSize',12)
hold on
plot(t,x(:,4),'r', 'LineWidth',2)
grid on
title("speed stimation")
xlabel('time(s)','fontweight','bold','FontSize',12)
ylabel('x2 and x2s ','fontweight','bold','FontSize',12)
legend('x2','x2s')
minPlot = min(x(:,4));
maxPlot = max(x(:,4));
ylim([minPlot, maxPlot]);
figure()
plot(t,s,'k', 'LineWidth',2)
set(gca,'FontSize',12)
grid on
title("Sliding variable")
xlabel('time(s)','fontweight','bold','FontSize',12)
ylabel('s','fontweight','bold','FontSize',12)
legend('sigma')
minPlot = min(sp);
maxPlot = max(sp);
ylim([minPlot, maxPlot]);
figure()
plot(t,x1(1:end-1),'k', 'LineWidth',2)
hold on
plot(t,x2s(1:end-1),'r', 'LineWidth',2)
set(gca,'FontSize',12)
grid on
title("x1 and x2 trough time")
xlabel('x1 and x2s','fontweight','bold','FontSize',12)
ylabel('t','fontweight','bold','FontSize',12)
legend('x1','x2')
xlim([0 8])
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% describing the ode
function [xdot,s,u,z] = smc_obsv(t, x)
xdot = zeros(4, length(t));
% parameters
f = sin(2*t); % disturbance
c = 1.5; %
r = 2; % criterion: r > max(f)
s = c*x(1) + x(4); % sliding surface
u = - r*tanh(s/0.001) - c*x(4); % control input
r1 = 10; % high gain
z = x(3) - x(1); % estimation error
v1 = - r1*tanh(z/0.001); % rate of xhat_1
LPF = 1/0.01; % adapatation rate
v2 = (v1 - x(4))*LPF; % rate of xhat_2
xdot(1) = x(2);
xdot(2) = f + u;
xdot(3) = v1;
xdot(4) = v2;
end

Accepted Answer

Torsten
Torsten on 19 Apr 2023
Use
s = zeros(numel(t),1);
u = s;
z = s;
for i = 1:numel(t)
[~, s(i),u(i),z(i)] = smc_obsv(t(i), x(i,:));
end
instead of
[~, s,u,z] = smc_obsv(t, x);

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!