Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Calculating and Adding Percent Error to a Graph

Asked by Karen on 23 Nov 2011

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
%The problem to be solved is:
%This problem has a known exact solution
function ystar = Eulermethod20(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
  %Exact solution
%Plot approximate and exact solutions
title('Euler Approximation');
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!


Fangjun Jiang on 23 Nov 2011

Apply {}Code format next time.

Karen on 23 Nov 2011

I don't even know what {} code is. No formal matlab training.



No products are associated with this question.

2 Answers

Answer by Fangjun Jiang on 23 Nov 2011
Accepted answer

Since you have the y and ystar, you can do


Notice "./" is the element-wise division.


Karen on 23 Nov 2011

It was great not getting an error message from MATLAB when I ran the code! Thanks, and then how can this error calculation get displayed on the graph?
Here is the code that I'm failing at:

Error(percent_error); %Is something wrong at this line?
%Plot approximate and exact solutions
title('Euler Approximation');
ylabel('y*(t), y(t)');

Fangjun Jiang on 23 Nov 2011

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.
Or put it in a separate figure because it is in a small scale.

Karen on 23 Nov 2011

Thank you very much. I'll plot it on a different figure to be able to see it better.

Fangjun Jiang
Answer by Naz on 23 Nov 2011

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 Comment

Karen on 23 Nov 2011

Thank you.


Contact us