Clear Filters
Clear Filters

How to plot forcing function in matlab

7 views (last 30 days)
Bilal sadiq
Bilal sadiq on 18 Jul 2018
Answered: Siraj on 29 Jul 2024 at 9:04
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,u]=ode45(@External_input,t,x0);
% x1=x(1);
% x2=x(2);
subplot(211);plot(t,x(:,1),'linewidth',2);grid on ;title('Pos')
subplot(212);plot(t,x(:,2),'linewidth',2);grid on ;title('Vel')
figure(2)
plot(t,u)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%f
function u=ui(t)
% For impulse
eps=0.1;
if t<eps
u=1;
else
u=0;
end
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%5 Question is %%%%%%%%%%%%%%%%%%%%%
i also want to plot u input ,,,but i am unable to plot it ...can some one guide me how can i plot the u input forcing function (which i have written in a separate function )
thanks

Answers (1)

Siraj
Siraj on 29 Jul 2024 at 9:04
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.

Categories

Find more on Graphics Objects in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!