Mean absolute error tutorial MATLAB

Here’s how to calculate the mean-absolute-error by hand in MATLAB

Basic idea: You have a set of numbers,

Actual = [1 2 3 4];

Then you have some method that tries to predict these numbers and returns some predicted values,

Predicted = [1 3 1 4];

You might now ask, “How do I evaluate how close the Predicted values are to the Actual values?”

Well one way is to take the mean absolute error (MAE) and report that.

[ A side note, you could also take the root-mean-square-error (RMSE) too.]

Here’s a quick tutorial on how to take the MAE of two sets of numbers:

% MAE tutorial.
% The actual values.
Actual = [1 2 3 4];
% The values we predicted.
Predicted = [1 3 1 4]; 
% You can just use the built in Mean Absolute Error function and pass in
% the "error" part.
builtInMAE = mae(Actual-Predicted)
% That's really all there is to it. But if you want to really understand
% it, here's how to calculate it by hand.
% Just follow the name, MEAN-ABSOLUTE-ERROR
% First calculate the "error" part.
err = Actual - Predicted;
% Then take the "absolute" value of the "error".
absoluteErr = abs(err);
% Finally take the "mean" of the "absoluteErr".
meanAbsoluteErr = mean(absoluteErr)
% That's it! You have now calculated the mean-absolute-error by hand.
% Thus, the MAE we calculated by hand has the same 
% value in the built in function, making this true 
builtInMAE == meanAbsoluteErr

3 thoughts on “Mean absolute error tutorial MATLAB”

Questions/comments? If you just want to say thanks, consider sharing this article or following me on Twitter!