Initial Value of y(0)=0
6 次查看(过去 30 天)
显示 更早的评论
How does one write a code for the IVP of y(0) = 0? The program won't accept the following. Also, can someone check my syntax for the equations I've entered? Thanks!
function ystar = Eulermethod201(n)
a=0;
b=5;
h=(b-a)/n;
t=0:h:5;%Initialize time variable
clear ystar;%wipe out old variable
ystar(0)=0;%Initial condition (same for approximation)
for i=0:length(t), %Set up "for" loop
%Calculate the derivative
k1=(-0.5*exp(t(i)/2)*sin(5*t(i))+5*exp(t(i)/2)*cos(5*t(i))-ystar(i));
ystar(i+1)=ystar(i)+h*k1;%Estimate new value of y
end
%Exact solution
y=(exp(t/2))*(sin(5*t));
%Error calculation
percent_error=100*abs(y-ystar)./y;
disp(percent_error);
%Plot approximate and exact solutions
plot(t,ystar,'b--',t,y,'r-',t,percent_error,'g');
legend('Approximate','Exact','Error');
title('Euler Approximation n=50');
xlabel('Time');
ylabel('y*(t), y(t)');
0 个评论
采纳的回答
Fangjun Jiang
2011-11-23
Unlike C language, MATLAB uses 1-based index for vector and matrix. So if you define a 10x1 vector, a=rand(10,1), you refer it as a(1), a(2) till a(10).
If you have the need to indicate some value at time==0, you will need to use some kind of offset to deal with it.
2 个评论
Fangjun Jiang
2011-11-24
Yes. You can't use y(0)=0 in MATLAB. You will need to do something like this for example
t=0:9;
y=10:10:100;
For any index number i, y(i) always corresponds to t(i), where i is a number from 1 to 10.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!