Hi! @Bilal sadiq
I understand you want to plot the "u" input forcing function along with the state variables "x1" and "x2".
You need to evaluate the "ui" function separately for each time step to get the "u" values.
Here is how you can modify your code to plot the "u" input:
function [xdot]=External_input(t,x)
x1 = x(1);
x2 = x(2);
m = 2;
g = 9.8;
k = 0.15;
J = 0.125;
x1dot = x2;
x2dot = ((m * g * k * sin(x1)) - ui(t)) / J;
xdot = [x1dot; x2dot];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc;
clear all;
close all;
t = linspace(0, 10, 1000);
x0 = [0 0];
[t, x] = ode45(@External_input, t, x0);
% Calculate the u values at each time step
u = arrayfun(@ui, t);
% Plot the results
subplot(3, 1, 1);
plot(t, x(:, 1), 'linewidth', 2);
grid on;
subplot(3, 1, 2);
plot(t, x(:, 2), 'linewidth', 2);
grid on;
subplot(3, 1, 3);
plot(t, u, 'linewidth', 2);
grid on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function u = ui(t)
% For impulse
eps = 0.1;
if t < eps
u = 1;
else
u = 0;
end
end
To plot "u", I have used the "arrayfun" function. This function applies a given function to each element of an array. To learn more about it, please refer to the following link:
Hope this helps.