- #1
- 8
- 0
Hi everyone,
So I have to solve a ODE (for dy/dt = K*(y-s) ) numerically in Matlab.
This is how I set it up:
K = 1;
s = 20;
y0 = 100;
npoints = 50;
dt = 0.1;
y = zeros(npoints,1); % this initializes the vector y to being all zeros
t = zeros(npoints,1);
y(1) = y0; % the initial condition
t(1) = 0.0;
for step=1:npoints-1 % loop over the timesteps
y(step+1) = y(step) + dt*K*(y(step)-s);
t(step+1) = t(step) + dt;
end
plot(t,y,'r'); %plots the numerical solution in red
hold on; %keep the previously plotted lines
My problem is that I have to "reset" the initial condition if the value of V(step+1)>150 with the initial condition (100). Then I have to let the loop continue with the new value.
I tried a bunch of combinations of the if statement in the for loop, but I can't make it work.
Any help would be really appreciated. Thanks!
So I have to solve a ODE (for dy/dt = K*(y-s) ) numerically in Matlab.
This is how I set it up:
K = 1;
s = 20;
y0 = 100;
npoints = 50;
dt = 0.1;
y = zeros(npoints,1); % this initializes the vector y to being all zeros
t = zeros(npoints,1);
y(1) = y0; % the initial condition
t(1) = 0.0;
for step=1:npoints-1 % loop over the timesteps
y(step+1) = y(step) + dt*K*(y(step)-s);
t(step+1) = t(step) + dt;
end
plot(t,y,'r'); %plots the numerical solution in red
hold on; %keep the previously plotted lines
My problem is that I have to "reset" the initial condition if the value of V(step+1)>150 with the initial condition (100). Then I have to let the loop continue with the new value.
I tried a bunch of combinations of the if statement in the for loop, but I can't make it work.
Any help would be really appreciated. Thanks!