Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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)');

Akzeptierte Antwort

Fangjun Jiang
Fangjun Jiang am 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 Kommentar
Karen
Karen am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 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 Kommentar
Karen
Karen am 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.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by