how to simulate a function in a loop with ode45, lsim, sim with input taken depending on last state?
5 views (last 30 days)
Show older comments
I want to simulate a model in a for loop and at each time step a new input should be taken given by some function. How can i do it using the 'sim' command? It is not accepting any input. Is there any other way to do it? LSIM is not useful because it simulates from the beginning of time whenever i add a new input for next time step. How can i simulate step by step in for loop. ode45 and lsim are giving different results.
here is my system
0.63
exp(-9.83*s) * -----------
25.53 s + 1

3 Comments
Aquatris
on 30 Aug 2018
Edited: Aquatris
on 30 Aug 2018
You have couple options.
- Implement your own ode4 in script and do it that way where you have control over everything that goes in the equation and solution.
- Use simulink. Implement your system and input chooser function using "Matlab Function" blocks)
- Inside the function that you supply to ode45, include the input choosing function.
Example;
function xd = fun(t,x)
if x(2) < 0
u = 2;
elseif x(2) > 0
u = 3;
else
u=0;
end
A = [0 1;-7 -6];
xd = A*x + [0 1]'*u;
end
Then in script;
y = ode45(@fun,[0 10],[5 0]');
plot(y.x,y.y')
Bill Tubbs
on 16 May 2020
I asked a very similar question earlier this year and actually got a response from someone at Mathworks:
> "sim function doesn't support onetime step simulation as of now. I have brought this issue to the concerned people and it might be considered in any future release."
Answers (1)
Giovanni Fumai
on 29 Aug 2020
If you use ode, you can configure OutputFcn in the odeset, which are functions that ode evaluates at the end of each simulation step: in there, you can define and compute the input for the next step as a function of the present state (I used it once to simulate PID actions).
0 Comments
See Also
Categories
Find more on General Applications 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!