Matlab ode45 internal step - matlab

I'm having doubts at how to use ode45 since I know it uses an internal variable step size. For instance, in my particular case I have a model of ODE's and I use a sampling time of 5 minutes. Hence, inside my main simulation loop I have the following line to obtain the output of my model by solving it using ode45:
[T,X] = ode45(#(t,x) model(t,x,u,data),[t t+scenario.Ts],x0);
Where u are inputs of the model, data is a structure with parameters, x0 are the initial conditions at the current time step and [t t+scenario.Ts] is the initial and final time. My doubt is that between t and t+scenario.Ts the ode45-solver uses variable time steps and thus the way I introduce my input actions u may be affected. Hence, I understand that a value of a particular input u is kept constant through the internal time steps between [t t+scenario.Ts]. Then, if I have for instance a flux, i.e. water into a tank, the time step has a direct effect to this u.
Let me explain this a little more with an example. If over [t t+scenario.Ts] I know that u(1) = 10. Then the real input I should use is u(1)=10/(# of time steps between [t0 tend]). However, since the internal step is variable which input do I have to use?
I hope you understand my problem and can help me out.

You should formulate the inputs such that it is independent of the time- discretization. This shouldn't be a problem if your equations are formulated in continuous time. If the control variable is not constant, then you should be make it explicitly dependent of t and write a function u(t).
If my answer is not sufficient to help you out, please add more details about your application, especially the dynamical model that you are simulating. Then we can help you further.

Related

Simulink S-Functions - Retrieve Initial Values from another S-Function

I'm trying to model the respective processes of an internal combustion engine. My current modelling approach is to have different sub functions which model the different processes.
Within each sub function is a Level 2 S-Function which solves the ODEs to give the in cylinder state (pressure, temperature, etc).
The problem that I'm having is that each sub function is enabled depending on the current crank angle which is computed from the current timestep in Simulink. The first process works fine as I manually set the initial values, but then I can't pass the latest in-cylinder state (the output from the first sub function) to the second sub function to use as the initial conditions (it insists on using the initial values I set at the beginning of the simulation).
Is there any way round this? Currently I'm going along a path of global data stores, but haven't had any joy so far.
There are a lot of different ways to solve this problem.
I'll show some of them as examples.
You can create additive output with Unit dalay block like this:
So you can get value of your crank angle from previous timestep and USE IT in formula for solving you equations.
Also you can use some code like this:
if (t == 0)
% equations with your initial values
sred = 0;
else
% equations with other values
y = uOld + myCoeef;
end
Another idea: sometimes I use persistent variables in Matlab function to save values of some variable from previous step. But I think it makes calculation slower.
One more idea - if you have Stateflow you can create chart with two states: first for initial moment with your coefficient and second to solve new equations.
If I understood you in wrong way you can show your code and we'll offer some new ideas!
P.S. Example of my using of S-Function:
My S-Function needs 2 values: Q is calculated in simulink at every step, ro is initial I took from big matrix I loaded from workspace in table and took necessary value depending of time.
So there is no any initial values in S-Function - all needed values I transmit into it from simulink!

Reading a file that corresponds to time step in solving ODE

I'm trying to solve an ODE in Matlab and I have the following problem:
my code is as bellow:
xinit=[0.19;25;0;7];
t=0:768:76800; %% 101 cells
[t1,y]=ode45(#Model_Bio,t,xinit);
In the function #Model_Bio I have a parameter that I need to read its corresponding values for each time step (101 values)!
So, My #Model_Bio is somehow as bellow:
load 'mydata'
a=mydata;
.....
the problem is that, when I execute the ode45(#Model_Bio,t,xinit), it calls my function with an automated time step (for example 50 times!) and my problem is that I cannot assign the values for each of my time step (101)!
Also, I think its not a good idea to change the time step of the ode the same as my 101 steps!
Anyone that help me on this is really appreciated!
It seems like you need to provide a wrapper of your data that interpolates it for arbitrary t, for example
my_interp = #(t) interp1(my_data_t, my_data_x, t)
http://se.mathworks.com/help/matlab/ref/interp1.html
and then implement your RHS (#Model_Bio) in terms of my_interp

MATLAB: Vectorize for loop in MATLAB

I wanted to vectorize this piece of code. Is it possible to do this? I tried finding a solution, but I was not able to find any good result on google.
for pos=length1+1:length
X1(pos) = sim(net1, [demandPred(pos), demand(pos-1), X1(pos-1), X1(pos-2)]')';
X2(pos) = sim(net1, [demandPred(pos), demand(pos-1), X2(pos-1), X2(pos-2)]')';
end
Thanks in advance. :)
Edit 1:
The model which I am going to simulate is a simple GRNN.
net1 = newgrnn([demand(169:trainElem), demand(169-1:trainElem-1), X1(169 - 1:trainElem - 1), X1(169 - 2:trainElem - 2)]', 0.09);
Can Simulink models be vectorized? Sometimes.
Can your Simulink model be vectorised? It's impossible to tell without seeing the model -- and how it is being called from m-code (as you've shown in your question) is no indication.
An example of vectorization would be: consider a model with signal s1 that gets added to constant K, and assume that you need to run the models for different values if K. You could use a loop (like the m-code you show) and run the model for each individual required value for K. Alternatively, you can make K a vector, in which case all values would get added to s1 and the result would be a vector of signals s1+K(1), s1+K(2),..., s1+K(n), and the model only needs to be executed once for all of these summations to occur.
But, whether that sort of thing can be done in your model cannot be determined without seeing the model.

Using coupled system of PDEs in modelica

Just few questions, i hope someone will find time to answer :).
What if we have COUPLED model example: system of n indepedent variables X and n nonlinear partial differential equations PDEf(X,PDEf(X)) with respect to TIME that depends of X,PDEf(X)(partial differential equation depending of variables X ). Can you give some advice? Here is one example:
Let’s say that c is output, or desired variable. Let’s say that r is independent variable.Partial differential equation looks like:
∂c/∂t=D*1/r+∂c/∂r+2(D* (∂^2 c)/(∂r^2 ))
D=constant
r=0:0.1:Rp- Matlab syntaxis, how to represent same in Modelica (I use integrator,but didn't work)?
Here is a code (does not work):
model PDEtest
/* Boundary conditions
1. delta(c)/delta(r)=0 for r=0
2. delta(c)/delta(r)=-j*d for r=Rp*/
parameter Real Rp=88*1e-3; // length
parameter Real initialConc=1000;
parameter Real Dp=1e-14;
parameter Integer np=10; // num. of points
Real cp[np](start=fill(initialConc,np));
Modelica.Blocks.Continuous.Integrator r(k=1); // independent x1
Real j;
protected
parameter Real dr=Rp/np;
parameter Real ts= 0.01; // for using when loop (sample(0,ts) )
algorithm
j:=sin(time); // this should be indepedent variable like x2
r.u:=dr;
while r.y<=Rp loop
for i in 2:np-1 loop
der(cp[i]):=2*Dp/r.y+(cp[i]-cp[i-1])/dr+2*(Dp*(cp[i+1]-2*cp[i]+cp[i-1])/dr^2);
end for;
if r.y==Rp then
cp[np]:=-j*Dp;
end if;
cp[1]:=if time >=0 then initialConc else initialConc;
end while;
annotation (uses(Modelica(version="3.2")));
end PDEtest;
Here are more questions:
This code don’t work in OpenModelica 1.8.1, also don’t work in Dymola 2013demo. How can we have continuos function of variable c, not array of functions ?
Can we place values of array cp in combiTable? And how?
If instead “algorithm” stay “equation” code can’t be succesfull checked.Why? In OpenModelica, error is :could not flattening model :S.
Is there any simplified way to use a set of equation (PDE’s) that are coupled? I know for PDEs library in Modelica, but I think they are complicated. I want to write a function for solving PDE and call these function in “main model”, so that output of function be continuos function of “c”.I don’t know what for doing with array of functions.
Can you give me advice how to understand Modelica language, if we “speak” like in Matlab? For example: Values of independent variable r,we can specife in Matlab, like r=0:TimeStep:Rp…How to do same in Modelica? And please explain me how section “equation” works, is there similarity with Matlab, and is there necessary sequancial approach?
Cheers :)
It's hard to answer your question, since you assuming that Modelica ~ Matlab, but that's not the case. So I won't comment your code, since it's really wrong. Let me give you an example model to the burger equation. Maybe you could use it as starting point.
model burgereqn
Real u[N+2](start=u0);
parameter Real h = 1/(N+1);
parameter Integer N = 10;
parameter Real v = 234;
parameter Real Pi = 3.14159265358979;
parameter Real u0[N+2]={((sin(2*Pi*x[i]))+0.5*sin(Pi*x[i])) for i in 1:N+2};
parameter Real x[N+2] = { h*i for i in 1:N+2};
equation
der(u[1]) = 0;
for i in 2:N+1 loop
der(u[i]) = - ((u[i+1]^2-u[i-1]^2)/(4*(x[i+1]-x[i-1])))
+ (v/(x[i+1]-x[i-1])^2)*(u[i+1]-2*u[i]+u[i+1]);
end for;
der(u[N+2]) = 0;
end burgereqn;
Your further questions:
cp is an continuous variable and the array is representing
every discretization point.
Why you should want to do that, as far as I understand cp is
your desired solution variable.
You should try to use almost always equation section
algorithm sections are usually used in functions. I'm pretty
sure you can represent your desire behaviour with equations.
I don't know that library, but the hard thing on a pde is the
discretization and the solving it self. You may run into issues
while solving the pde with a modelica tool, since usually
a Modelica tool has no specialized solving algorithm for pdes.
Please consider for that question further references. You could
start with Modelica.org.

Getting the solver type and step size (for fixed step solvers)

we are trying to integrate a simulation model into Simulink as a block. We have a custom continuous block which loads an m file that contains the functions Derivatives, Outputs etc.
My question is: is there a way to find out which solver is used currently and with which parameters? Our model won't be able to support variable time solvers and I would like to give a warning. Similarly, the model requires the fixed step time for initialization.
Thanks in advance.
You can get the current solver name using
get_param('modelName', 'SolverName');
Some of the other common solver parameters are
AbsTol
FixedStep
InitialStep
ZcThreshold
ExtrapolationOrder
MaxStep
MinStep
RelTol
SolverMode
You can find other parameters you may wish to query by opening the .mdl file in your favorite text editor and digging through it.
If I'm understanding your use case correctly, you are trying to determine the type of solver (and other solver params) for the top-level simulink system containing your block.
I think the following should give you what you want:
get_param(bdroot, 'SolverType'); % //Returns 'Variable-step' or 'Fixed-step'
get_param(bdroot, 'FixedStep'); % //Returns the fixed step size
Notice that for purposes of generality/reusability, this uses bdroot to identify the top-level system (rather than explicitly specifying the name of this system).
If you want to find out more about other model parameters that you can get/set, I would check out this doc.
Additionally, I'm interested to know why it is that your model doesn't support a variable-step solver?