Reputation: 203
I have the following system of differential equations to simulate in a .m
file:
function dx = odefun(t,x)
% display(x(1));
% y = 5;
dx = [x(2); - y - 3*x(2) - 2*x(1)];
end
I am simulating the system running another .m
file with the code below:
[t,x] = ode45(@odefun, [0 10], [0;0]);
% display(x(:,1));
plot(t,x(:,1));
My problem is that I want the value of y
parameter, which happens to be the output of my system, to change in each time step while the ode(...)
function is executing. I tried by sending another argument like this:
[t,x] = ode45(@odefun, [0 10], [0;0], [some_elements]);
function dx = odefun(t,x,y)
but I get the error: Not enough input arguments.
Truth is that I want y
parameter to take one value at each time step from a vector with a hundred elements. Any help would be greatly appreciated.
Upvotes: 1
Views: 2714
Reputation: 203
For those interested I post here the way I finally managed to get what I want. I have a 1x100 vector representing the input to a system and I want to take back a 1x100 vector consisting of the values of the output of my system. I wanted one value as output for each value of my input.
global f
t = 0.1:0.1:10.0;
f = @create_signal;
[t,x] = ode45(@odefun, t, [0;0]);
and the odefun
function is like this:
function dx = odefun(t,x)
global f
m = 15;
b = 0.2;
k = 2;
u = f(t);
dx = [x(2); u/m - (b/m)*x(2) - (k/m)*x(1)];
end
and lastly the function that creates the values of the input:
function u = create_signal(t)
u = 5*sin(t) + 10.5;
end
I applied the create function handle feature of MATLAB. Here is the link of mathworks help: https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html
Upvotes: 0
Reputation: 2699
Not tested on Matlab but just to help and mainly wrapped up from https://fr.mathworks.com/help/matlab/ref/ode45.html#bu00_4l_sep_shared-options ODE with Time-Dependent Terms
function dx = odefun(t,x,y,yt)
f = interp1(yt,y,t);
dx = [x(2); - f - 3*x(2) - 2*x(1)];
end
%define your array (or even function) y(yt)
yt = 0.0:0.1:10.0;
y = array; % array being your array of input values. (should contain the corresponding value for 0.0:0.1:10.0
[t,x] = ode45(@(t,x) odefun(t,x,y,yt), [0.0 10.0], [0;0]);
or try the following if you want specific time steps included in your result :
[t,x] = ode45(@(t,x) odefun(t,x,y,yt), yt, [0;0]);
You can also do, to be sure to have your solution corresponding to 0.0:0.1:10.0,
x100 = interp1(t,x,yt);
Upvotes: 0