필터 지우기
필터 지우기

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

조회 수: 1 (최근 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에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by