How can I calculate the sum of the absolute error?

14 views (last 30 days)
Hello,
I am trying to do some exercises in Matlab, and i have trouble with calculating the absolute error and state it with 2 decimal places. You can see the exercise (the last one) in the image below.
I am done with sub task 1 and 2, where i got:
A_system_matrix = [1 -2 3; 1 -1 0; 1 0 -1; 1 1 0; 1 2 3] % System matrix A
y_vector = [0; 15; 25; 50; 110]
rref([A'*A,A'*y_vector]) % Using rowreducing
(A'*A)^(-1)*A'*y_vector % Using the equation stated in the text above
Can someone help me with using Matlab to calculate the sum of the absolute error stated in the exercise and then state it with 2 decimal places?
Thanks a lot!

Accepted Answer

Fabio Freschi
Fabio Freschi on 23 Sep 2021
Edited: Fabio Freschi on 23 Sep 2021
Please check the code below.
clear all, close all
% model
F = @(c,x)c(1)+c(2)*x+c(3)*(x.^2-1);
% data
xk = [-2 -1 0 1 2].';
yk = [0 15 25 50 110].';
% build matrix A
A = [F([1 0 0],xk) F([0 1 0],xk) F([0 0 1],xk)];
% least-square fit
c = (A.'*A)\(A.'*yk);
% error
err = sum(abs(yk-F(c,xk)));
fprintf('error = %.2f\n',err);
error = 24.00
% plot
x = (-2:.1:2).';
figure, hold on
plot(xk,yk,'o')
plot(x,F(c,x))
Three remarks
  • never ever use ^(-1) or inv to solve a linear system. Backslash operator is faster and more accurate.
  • the transpose operator is .' for the transpose. A simple ' is the complex conjugate transpose. In your case this is not affecting the result, but it is a good practice to keep the two operations separated.
  • Note that you can solve the least-square problem without explicitly write the normal equations using the backslash operator on your overdetermined system
c = A\yk;
  3 Comments
Fabio Freschi
Fabio Freschi on 23 Sep 2021
Edited: Fabio Freschi on 23 Sep 2021
Decimal places means digits after the decimal point.
The error formula in your OP is a scalar, so you should produce only one number
If my answer solves your problem, please accept it
Mads Yar
Mads Yar on 23 Sep 2021
Fair enough. Thank you very much for the detailed answer! Can i ask you about other exercises also? Else you can take a look at my other questions? It would be such a big help!

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB 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!