Everytime I try to plot, I get a straight line, and not a sine wave:(
2 次查看(过去 30 天)
显示 更早的评论
I get a sine curve for the aproximated Euler method, but the exact solution comes out as a straight line with an error message reading "Inner matrix dimensions must agree." SOmething must be going wrong within the exact formula, or with the "i's". I feel so close to the correct solution, but it doesn't graph correctly. Here is my code:
function ystar = Eulermethod202(n)
a=0;
b=5;
h=(b-a)/n;
t=1:h:5;
%Initialize time variable
clear ystar;
%wipe out old variable
ystar(1)=0;
%Initial condition (same for approximation)
clear k1;
%Set up "for" loop
for i=1:length(t)-1;
%Calculate the derivative
k=(-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*k;%Estimate new value of y*
end
%Exact solution
y=exp(t(i)/2)*sin(5*t(i));
%Plot approximate and exact solutions
plot(t,ystar,'b',t,y,'r');
legend('Approximate','Exact');
title('Euler Approximation');
xlabel('Time');
ylabel('y*(t), y(t)');
0 个评论
采纳的回答
Fangjun Jiang
2011-11-23
For the exact value y, you need to do
y=exp(t/2).*sin(5*t)
t is a vector, t(i) is the individual element depending on the value of i. MATLAB is a MATrix LABoratory. Many operations can be done on a vector or matrix. You need to get familiar with it.
更多回答(1 个)
Walter Roberson
2011-11-23
Your line
y=exp(t(i)/2)*sin(5*t(i));
is after the "for" loop, which should lead you to question what the value of "i" will be when the loop ends.
You can predict, though, that "i" will have a single value (whatever that value is), which is going to lead to the two subexpressions having a single value, which is going to lead to "y" having a single value. And then you try to plot that single value against the array "t".
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!