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)');

采纳的回答

Fangjun Jiang
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 个评论
Karen
Karen 2011-11-24
Yes, I do need to get familiar with it. I would like to take a Matlab class. My DE prof assigned us this programming assignment and I've learned enough Matlab to get into trouble. Thank you very much for your help. My graph looks perfect now.

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
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".
  1 个评论
Karen
Karen 2011-11-24
I put it into the "for" loop too, but it didn't work that way either. Thank you for your description of the "i". It will halp me visualize what I'm doing.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by