Calculating and Adding Percent Error to a Graph

37 ビュー (過去 30 日間)
Karen
Karen 2011 年 11 月 23 日
The Percent Error = 100*abs(exact solution-Approximate solution)/Exact Solution. I am writing a Euler method approximation and I need to know how best to present this. I keep getting the error message that "matrix dimensions must agree". Here is my code.
%Script that demonstrates Euler integration for a first order problem using
%MATLAB.
%The problem to be solved is:
%y'(t)+2*y(t)=2-exp(-4*t)
%This problem has a known exact solution
%y(t)=1+0.58*exp(-4*t)-0.5*exp(-2*t)
function ystar = Eulermethod20(n)
a=0;
b=5;
h=(b-a)/n;
t=0:h:5;%Initialize time variable
clear ystar;%wipe out old variable
ystar(1)=1.0;%Initial condition (same for approximation)
for i=1:length(t)-1, %Set up "for" loop
k1=2-exp(-4*t(i))-2*ystar(i); %Calculate the derivative
ystar(i+1)=ystar(i)+h*k1;%Estimate new value of y
end
%Exact solution
y=1+0.5*exp(-4*t)-0.5*exp(-2*t);
%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)');
percent_error= 100*(1)+(0.5*exp(-4*t)-(0.5*exp(-2*t))-(2-exp(-4*t(i)))-(2*ystar(i))/((1)+(0.5*exp(-4*t))-(0.5*exp(-2*t))));
legend('Percent Error')
The program runs, but the percent error doesn't calculate correctly. I need to calculate and show the error for this project and I was hoping someone can help. Thanks!
  2 件のコメント
Fangjun Jiang
Fangjun Jiang 2011 年 11 月 23 日
Apply {}Code format next time.
Karen
Karen 2011 年 11 月 23 日
I don't even know what {} code is. No formal matlab training.

サインインしてコメントする。

採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 11 月 23 日
Since you have the y and ystar, you can do
percent_error=100*abs(y-ystar)./y;
Notice "./" is the element-wise division.
  4 件のコメント
Fangjun Jiang
Fangjun Jiang 2011 年 11 月 23 日
y is a vector because t is a vector.
error() is a function but is for a completely different purpose. I don't understand your usage of Error(). Is Error() a user-defined function? If it is, you'd better use a different name even it is using capital "E".
You can just plot the error with your y and ystar.
plot(t,ystar,'b--',t,y,'r-',t,percent_error,'g');
Or put it in a separate figure because it is in a small scale.
figure;plot(t,percent_error);
Karen
Karen 2011 年 11 月 23 日
Thank you very much. I'll plot it on a different figure to be able to see it better.

サインインしてコメントする。

その他の回答 (1 件)

Naz
Naz 2011 年 11 月 23 日
You are missing the 'dot' in the following expression:
percent_error= 100*(1)+(0.5*exp(-4*t)-(0.5*exp(-2*t))-(2-exp(-4*t(i)))-(2*ystar(i))./((1)+(0.5*exp(-4*t))-(0.5*exp(-2*t))));
Now this should work
  1 件のコメント
Karen
Karen 2011 年 11 月 23 日
Thank you.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by