Your implementation has several errors:
- Looks like you are creating i as a vector and then using that for indexing in A(i)
- You are not using the k's properly
- You are not calculating k4 correctly (it should be a full step not a half step)
- You are using A as both a vector and a scalar when updating
- You are not saving the intermediate results in Aout and tout inside the loop
To make things simpler and easier to read and debug, I would suggest making a function handle for the derivative. Then construct your code using this function handle, indexing both Aout and tout inside the loop. E.g.,
f = @(t,A) A-exp(-2*t);
tout = zeros(n_out+1,1); tout(1) = t0;
Aout = zeros(n_out+1,1); Aout(1) = A0;
for i=1:n_out
k1 = f(tout(i) , Aout(i) );
k2 = f(tout(i)+h/2, Aout(i)+k1*h/2);
k3 = f(tout(i)+h/2, Aout(i)+k2*h/2);
k4 = f(tout(i)+h , Aout(i)+k3*h );
Aout(i+1) = Aout(i) + (h/6)*(k1 + 2*k2 + 2*k3 + k4);
tout(i+1) = tout(i) + h;
end
After the loop finishes, the answers are in the Aout and tout vectors. So you would
I am confused what the i_out is supposed to be used for. Can you clarify?
댓글 수: 0
댓글을 달려면 로그인하십시오.