How do I use a squarewave as an input?

I am trying to solve an ODE. Using a different tspan the ODE is solved, but I need to use a squarewave as an input. So far this is my code:
Rs= 17.5;
Csa= 0.01;
%Csv= 1.75;
%t= 5.5998 ;% Q
Psa = 99.9958; % Psa
Psv= 1.9999; % Psv
a=1:0.1:100;
y= square (a,50);
dPsadt= @(t,Psa)((t-((Psa - Psv)/ Rs)) /Csa);
ode45(dPsadt, [y], [0]);

Answers (1)

Try this:
Rs= 17.5;
Csa= 0.01;
%Csv= 1.75;
%t= 5.5998 ;% Q
Psa = 99.9958; % Psa
Psv= 1.9999; % Psv
a=1:0.1:100;
y= square (a,50);
idx = find(y>0); % Find Relevant Indices Into ‘y’
idxp = idx(find(diff(idx)>1)); % Find Relevant Indices Into ‘y’
idx = find(y<0); % Find Relevant Indices Into ‘y’
idxn = idx(find(diff(idx)>1)); % Find Relevant Indices Into ‘y’
ic = 0;
dPsadt= @(t,Psa)((t-((Psa - Psv)/ Rs)) /Csa) .* interp1(a,y,t);
for k = 1:numel(idxp)
tspan = a(idxp(k):idxn(k));
[tk,yk] = ode45(dPsadt, tspan, ic);
ic = yk(end);
tc{k,:} = tk;
yc{k,:} = yk;
end
tv = cell2mat(tc);
yv = cell2mat(yc);
figure
plot(a, y)
hold on
plot(tv, yv, '-r')
hold off
grid
The approach is to use the last value of the dependent variable as the initial condition for the next iteration, since numeric ODE solvers do not handle significant, abrupt transitions well (they are not differentiable). The interp1 call added to the ‘dPsadt’ function uses the square-wave ‘y’ as input to the function at every time ‘t’. Unforutnately, the integrated function descends to very high negative numbers. (Substituting 0 for ‘ic’ demonstrates that the code appears to work correctly.)
.

Categories

Find more on Chemistry in Help Center and File Exchange

Products

Tags

Asked:

on 22 Apr 2020

Answered:

on 22 Apr 2020

Community Treasure Hunt

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

Start Hunting!