Everytime I try to plot, I get a straight line, and not a sine wave:(

2 views (last 30 days)
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)');

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 23 Nov 2011
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 Comment
Karen
Karen on 24 Nov 2011
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.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 23 Nov 2011
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 Comment
Karen
Karen on 24 Nov 2011
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.

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!