How to set initial condition t=0 for Simulink integrator loop - matlab

I have a differential equation: dx/dt = a * x. Using Matlab Simulink, I need to solve this equation and output it using Scope block.
The problem is, I don't know how to specify an initial condition value t = 0.
So far I have managed to create a solution that looks like this:
I know that inside integrator, there is a possiblity to set "Initial condition" but I can't figure out how that affects the final result. How can I simply set the value of x at t = 0; e.i. x(0) = 6?

Let's work this problem through analytically first so we know if the model is correct.
dx/dt = a*x % Seperable differential equation
=> (1/x) dx = a dt % Now we can integrate
=> ln(x) = a*t + c % We can determine c using the initial condition x(0)
=> ln(x0) = a*0 + c
=> ln(x0) = c
=> x = exp(a*t + ln(x0)) % Subbing into 3rd line and taking exp of both sides
=> x = x0 * exp(a*t)
So now we have an idea. Let's look at this for t = 0 .. 1, x0 = 6, a = 5:
% Plot x vs t using plain MATLAB
x0 = 6; a = 5;
t = 0:1e-2:1; x = x0*exp(a*t);
plot(t,x)
Now let's make a Simulink model which acts as a numerical integrator. We don't actually need the Integrator block for this application, we simply want to add the change at each time step!
To run this, we must first set a couple of things up. In Simulation > Model Configuration Parameters, we must set the time step to match the time step we've used to switch between dx/dt and dx (2nd Gain block).
Lastly, we must set the initial condition for x0, this can be done in the Memory block
Setting the end time to 1s and running the model, we see the expected result in the Scope. Because it matches our analytical solution, we know it is correct.
Now we understand what's going on, we can re-introduce the integration block to make the model more flexible. Using the integrator means that dt is automatically calculated, and we don't need to micro-manage the Gain block, in fact we can get rid of it. We still need a Memory block though. We now also need intial conditions in both the integrator, and the memory block. Put scopes in different locations and just complete the first few time steps to work out why!
Note that the initial conditions are less clear when using the integrator block.

The way to think about the integrator blocks is either completely in the Laplace picture, or as representing the equivalent integral equation for the IVP
y'(t)=f(t,y(t)), y(0) = y_0
is equivalent to
y(t) = y_0 + int(s=0 to t) f(s,y(s)) ds
The feed-back loop in the block diagram realizes almost literally this fixed-point equation for the solution function.
So there is no need for complicated constructions and extra blocks.

Related

No output while using "gmres" in Matlab

I want to solve a system of linear equalities of the type Ax = b+u, where A and b are known. I used a function in MATLAB like this:
x = #(u) gmres(A,b+u);
Then I used fmincon, where a value for u is given to this expression and x is computed. For example
J = #(u) (x(u)' * x(u) - x^*)^2
and
[J^*,u] = fmincon(J,...);
withe the dots as matrices and vectors for the equalities and inequalities.
My problem is, that MATLAB delivers always an output with information about the command gmres. But I have no idea, how I can stop this (it makes the Program much slower).
I hope you know an answer.
Patsch
It's a little hidden in the documentation, but it does say
No messages are displayed if the flag output is specified.
So you need to call gmres with at least two outputs. You can do this by making a wrapper function
function x = gmresnomsg(varargin)
[x,~] = gmres(varargin{:});
end
and use that for your handle creation
x = #(u) gmresnomsg(A,b+u);

Experiment data correlation in Modelica/Dymola

Firstly I am a relatively new user.I am trying to correlate a physical test data with the model I built using Dymola/Modelica. In this model "variable 1" has a initial value based on which "variable 2,3 and 4" are calculated and these variables(2,3 & 4) are used to re-calculate "variable 1" and this value of "variable 1" has to be used for the next time step and subsequent recalculations has to be done.
I am not sure how to pass this "updated variable 1" as an input to the model every time step?Can someone please help me on how to approach this problem?
Thanks.
If I understood well the question you have an equation system which you want to solve de-coupled, i.e. solve one set of equations using some initial values or values of the system at previous time step, let's call this equation set A, then with its results as an input solve equation set B at the next time step and so on. Below an example of a decoupled system that is discrete, in which the decoupling is obtained with a clock period shift:
And then the same system that is solved in a coupled way, so at every time instant, all the equations are solved synchronously:
To reply to your comment you can also implement your model into equation section inside a when statement using the pre operator that is used to refer to last value of a discrete variable during an event.
model test
parameter Real timeStep = 0.1;
Real T_i[4];
Real K[4];
Real M[4];
initial equation
T_i = {1,2,3,4}; //starting value of a T
K = T_i .* 1.1 .+ 4;
M = K .* 1.1 .+ 4;
equation
when sample(timeStep,timeStep) then
K = T_i .* 10 .+ 4;
M = K .* 10 .+ 4;
T_i = pre(M) + pre(K);
end when;
end test;
I hope this helps

how to make this function periodic in MATLAB?

I have wrote this code in MATLAB editor and want this function to be periodic (period = 0.8s)
HR=75;
E_max=2.0;
E_min=0.06;
t_c=60/HR;
T_max=0.2+0.15*t_c;
t=0:0.0001:t_c;
t_n=t/T_max;
E_n=1.55*(((t_n/0.7).^1.9)./(1+(t_n/0.7).^1.9)).*(1./(1+(t_n/1.17).^21.9));
E=(E_max-E_min)*E_n+E_min;
plot(t,E)
I want to use the function in simulink as a voltage source. so i do not need a point but the whole function. so I need a function that takes the overall time (for example 20 secs) and gives the output CONTINUSELY (like a Sin function).
the function and it's shape is:
http://tinypic.com/r/2641a1s/8
Create your data in the MATLAB base workspace by running your code in MATLAB before running your Simulink model. Then use the Repeating Sequence Block. Use your variable t as the Time Values and E as the Output Values. You'll also need to make sure that the maximum step size that the solver takes is min(diff(t)), which in the case of your data is 0.0001.
Well you are confusing the Matlab vector and a function
The function gives a value for any query in the domain of the function.
i.e. if the domain is [-1,2] then f(x) where x in [-1,2] should give and only give one value. such as y = 3x + 2.
If you want The function then you should make the script into a function.
cardiac.m
function y = cardiac(x,cropPeriod,period)
t_n = mod(x*cropPeriod/period,cropPeriod);
y=1.55*(((t_n/0.7).^1.9)./(1+(t_n/0.7).^1.9)).*(1./(1+(t_n/1.17).^21.9));
end
Then, save the file as cardiac.m and will give you the function.
And call the function as cardiac(x,0.8) then this will give you the value you want
demo.m
t = 0:0.01:10; % choose arbitrary range.
p = 0.8; % period
cropPeriod = 4; % explained below
y = cardiac(t,cropPeriod,p);
plot(t,y);
It is clear that the equation given in http://tinypic.com/view.php?pic=j75jzk&s=8#.U7iH43VdXJ8 is different from the plot on the image. Since I don't know the period of the function, you can simply choose appropriate number cropPeriod until you are satisfied.
Example Plot
If you just want to make it to have period p
MATLAB plot is nothing but a series of data point. when you call plot(t,E), MATLAB plots a points in position (t(1),E(1)) and (t(2),E(2)) ... Thus, if you want to scale it just type
plot(p * t,E);
xlabel('sec(s)'); % Give x axis label
ylabel('E(t)')
where p = 0.8

convolution of experimental data with a singular function in Matlab

this is likely a few lines of code but I cannot figure it out...
I need to perform a convolution operation of experimental data with an analytical function which is singular at the beginning of the integration range. So if I use "conv" it won't work...
I have two experimental vectors, phi(time) and time
then want to calculate T(t)
T = \int_{0}^{t}\phi \left ( t-\tau \right )\frac{\textup{d}\tau}{\tau ^{1/2}}
So the the singularity at tau = 0 makes "conv" not work. I've been fiddling with anonymous functions and using quadgk to handle the singularity and the like, but can't make anything work. I would have bet anything that this is a solved problem but can't find anything like it. Any help is very much appreciated.
EDIT: solved it this way:
function T = TCalc(time, power)
warning off MATLAB:quadgk:NonFiniteValue %suppress warning at the zero point
T=zeros(size(time));
for par = 1:numel(time)
T(par) = s1(time(par));
end
function y = r1(t)
y = interp1q(time,power,t');%notice that t is transposed! to make interp1q work.
y = y';
end
function y = s1(tfin)
y = quadgk(#(t) (r1(tfin-t))./t.^(0.5),0,tfin,'RelTol',1.e-2);
end
end
I guess, the inelegant trick here is to make Matlab think the experimental data is an analytical function by passing through interp1, and using quadgk to tolerate a singularity at the limit of integration. About one second for 1000-point vectors. Ignoring or setting the tau = 0 point to a small value doesn't work, it still perceives a singularity and the result is wrong.

Matlab: if statements and abs() function in variable-step ODE solvers

I was reading this post online where the person mentioned that using "if statements" and "abs()" functions can have negative repercussions in MATLAB's variable-step ODE solvers (like ODE45). According to the OP, it can significantly affect time-step (requiring too low of a time step) and give poor results when the differential equations are finally integrated. I was wondering whether this is true, and if so, why. Also, how can this problem be mitigated without resorting to fix-step solvers. I've given an example code below as to what I mean:
function [Z,Y] = sauters(We,Re,rhos,nu_G,Uinj,Dinj,theta,ts,SMDs0,Uzs0,...
Uts0,Vzs0,zspan,K)
Y0 = [SMDs0;Uzs0;Uts0;Vzs0]; %Initial Conditions
options = odeset('RelTol',1e-7,'AbsTol',1e-7); %Tolerance Levels
[Z,Y] = ode45(#func,zspan,Y0,options);
function DY = func(z,y)
DY = zeros(4,1);
%Calculate Local Droplet Reynolds Numbers
Rez = y(1)*abs(y(2)-y(4))*Dinj*Uinj/nu_G;
Ret = y(1)*abs(y(3))*Dinj*Uinj/nu_G;
%Calculate Droplet Drag Coefficient
Cdz = dragcof(Rez);
Cdt = dragcof(Ret);
%Calculate Total Relative Velocity and Droplet Reynolds Number
Utot = sqrt((y(2)-y(4))^2 + y(3)^2);
Red = y(1)*abs(Utot)*Dinj*Uinj/nu_G;
%Calculate Derivatives
%SMD
if(Red > 1)
DY(1) = -(We/8)*rhos*y(1)*(Utot*Utot/y(2))*(Cdz*(y(2)-y(4)) + ...
Cdt*y(3)) + (We/6)*y(1)*y(1)*(y(2)*DY(2) + y(3)*DY(3)) + ...
(We/Re)*K*(Red^0.5)*Utot*Utot/y(2);
elseif(Red < 1)
DY(1) = -(We/8)*rhos*y(1)*(Utot*Utot/y(2))*(Cdz*(y(2)-y(4)) + ...
Cdt*y(3)) + (We/6)*y(1)*y(1)*(y(2)*DY(2) + y(3)*DY(3)) + ...
(We/Re)*K*(Red)*Utot*Utot/y(2);
end
%Axial Droplet Velocity
DY(2) = -(3/4)*rhos*(Cdz/y(1))*Utot*(1 - y(4)/y(2));
%Tangential Droplet Velocity
DY(3) = -(3/4)*rhos*(Cdt/y(1))*Utot*(y(3)/y(2));
%Axial Gas Velocity
DY(4) = (3/8)*((ts - ts^2)/(z^2))*(cos(theta)/(tan(theta)^2))*...
(Cdz/y(1))*(Utot/y(4))*(1 - y(4)/y(2)) - y(4)/z;
end
end
Where the function "dragcof" is given by the following:
function Cd = dragcof(Re)
if(Re <= 0.01)
Cd = (0.1875) + (24.0/Re);
elseif(Re > 0.01 && Re <= 260.0)
Cd = (24.0/Re)*(1.0 + 0.1315*Re^(0.32 - 0.05*log10(Re)));
else
Cd = (24.0/Re)*(1.0 + 0.1935*Re^0.6305);
end
end
This is because derivatives that are computed using if-statements, modulus operations (abs()), or things like unit step functions, dirac delta's, etc., will introduce discontinuities in the value of the solution or its derivative(s), resulting in kinks, jumps, inflection points, etc.
This implies the solution to the ODE has a complete change in behavior at the relevant times. What variable step integrators will do is
detect this
recognize that they won't be able to use information directly beyond the "problem point"
decrease the step, and repeat from the top, until the problem point satisfies the accuracy demands
Therefore, there will be many failed steps and reductions in step size near the problem points, negatively affecting the overall integration time.
Variable step integrators will continue to produce good results, however. Constant step integrators are not a good remedy for this sort of problem, since they are not able to detect such problems in the first place (there's no error estimation).
What you could do is simply split the problem up in multiple parts. If you know beforehand at what points in time the changes will occur, you just start a new integration for each interval, each time using the output of the previous integration as the initial value for the next one.
If you don't know beforehand where the problems will be, you could use this very nice feature in Matlab's ODE solvers called event functions (see the documentation). You let one of Matlab's solvers detect the event (change of sign in the derivative, change of condition in the if-statement, or whatever), and terminate the integration when such events are detected. Then start a new integration, starting from the last time and with initial conditions of the previous integration, as before, until the final time is reached.
There will still be a slight penalty in overall execution time this way, since Matlab will try to detect the location of the event accurately. However, it is still much better than running the integration blindly when it comes to both execution time and accuracy of the results.
Yes it is true and it happens because of your solution is not smooth enough at some points.
Assume you want to integrate. y'(t) = f(t,y). Then, what happens in f is getting integrated to become y. Thus, if in your definition of f there is
abs(), then f has a kink and y is still smooth and 1 times differentiable
if, then f has a jump and y a kink and no more differentiability
Matlab's ODE45 presumes that your solution is 5 times differentiable, and tries to ensure an accuracy of order 4. Nonsmooth points of your function are misinterpreted as stiffness what leads to small stepsizes and even to breakdowns.
What you can do: Because of the lack of smoothness you cannot expect a high accuracy anyways. Thus, ODE23 might be a better choice. In the worst case, you have to stick to first-order schemes.