Multiple unit steps in ode solver

9 views (last 30 days)
jnovv
jnovv on 6 Jan 2016
Answered: Walter Roberson on 6 Jan 2016
Hi there,
I am trying to run an odesolver where in the differential equation, there is a function that uses a for loop.
The code is something like this:
for N=1:10
Iapp=Io*(heaviside(20*N+2-t)-heaviside(20*N-t));
hold on
end
dydt(1,1) = Iapp/C;
Iapp is meant to generate multiple heaviside step functions that only lasts for 2s in each step. The number of step functions is controlled by the N.
I then created a separate file for the odesolver. Something like this:
x = [0,500];
[t,y] = ode15s(@filename,[x],[the IC]);
The problem I get after this is that the Iapp always comes out as 0. Thus not resulting in the result that I need.
I hope my issue is clear enough and I would be grateful if someone can help me with this, as I am very stuck.
Thanks in advance!

Answers (1)

Walter Roberson
Walter Roberson on 6 Jan 2016
"hold on" only has to with graphics routines.
When you have a "for" loop in which you are not using a reduction variable and you are not indexing the output, then each iteration of the "for" loop overwrites all of the output of the previous, giving a result that is the same as if only the last iteration had been run. Your
for N=1:10
Iapp=Io*(heaviside(20*N+2-t)-heaviside(20*N-t));
hold on
end
is the same as if you had written
for N=10
Iapp=Io*(heaviside(20*N+2-t)-heaviside(20*N-t));
end
Possibly you wanted
for N=1:10
Iapp(N)=Io*(heaviside(20*N+2-t)-heaviside(20*N-t));
end
but that would create a vector Iapp. I speculate that you want to sum all of them together,
dydt(1,1) = sum(Iapp)/C;
If so then you could write
N = 1 : 10;
Iapp = Io*(heaviside(20*N+2-t)-heaviside(20*N-t));
dydt(1,1) = sum(Iapp)/C;
with no loop.

Community Treasure Hunt

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

Start Hunting!