To calculate R2 (Coefficient of Determination) in a MATLAB NARX neural network, compute the Normalized Mean Squared Error (NMSE) via NMSE = mse(E) / mean(var(to', 1)), where Rsq = 1 − NMSE. For segmented evaluation, extract target and error subsets using tro.trainInd, tro.valInd, and tro.testInd.
1. Mathematical Foundation (Why R2 = 1 − NMSE)
In MATLAB, mse(E) computes the sum of squared errors divided by the sample size N. Specifying 1 in var(to', 1) computes the biased sample variance σ2 normalized by N (rather than N − 1). Dividing the two cancels N, producing the exact ratio of Residual Sum of Squares (SSres) to Total Sum of Squares (SStot):
Transposing to' ensures that multi-variable or multi-output target series are correctly averaged across all channels using mean().
2. Executable MATLAB Script (Train, Val, Test & Closed-Loop)
The script below modifies the open-loop simplenarx_dataset example, uses divideblock to prevent temporal lookahead leakage, and calculates R2 for all partitions as well as closed-loop multi-step forecasting:
% Clear workspace and load standard benchmark data
clearvars; close all; clc;
rng(0); % Ensure reproducibility
[X, T] = simplenarx_dataset;
% 1. Create and configure Open-Loop NARX Network
neto = narxnet(1:2, 1:2, 10);
neto.divideFcn = 'divideblock'; % Block division prevents time-series data leakage
neto.divideParam.trainRatio = 0.70;
neto.divideParam.valRatio = 0.15;
neto.divideParam.testRatio = 0.15;
% 2. Prepare time series and train open-loop model
[Xo, Xoi, Aoi, To] = preparets(neto, X, {}, T);
[neto, tro, Yo, Eo] = train(neto, Xo, To, Xoi, Aoi);
% Anonymous function for R-squared: 1 - (MSE / Biased Variance)
calcR2 = @(t_data, e_data) 1 - (mse(e_data) / mean(var(t_data', 1)));
% 3. Calculate Open-Loop R^2 across partitions
to_all = cell2mat(To);
eo_all = cell2mat(Eo);
Rsq_all = calcR2(to_all, eo_all);
to_train = cell2mat(To(tro.trainInd));
eo_train = cell2mat(Eo(tro.trainInd));
Rsq_train = calcR2(to_train, eo_train);
to_val = cell2mat(To(tro.valInd));
eo_val = cell2mat(Eo(tro.valInd));
Rsq_val = calcR2(to_val, eo_val);
to_test = cell2mat(To(tro.testInd));
eo_test = cell2mat(Eo(tro.testInd));
Rsq_test = calcR2(to_test, eo_test);
% 4. Convert to Closed-Loop for Autonomous Multi-Step Prediction
netc = closeloop(neto);
[Xc, Xci, Aci, Tc] = preparets(netc, X, {}, T);
[Yc, ~, ~] = netc(Xc, Xci, Aci);
Ec = gsubtract(Tc, Yc);
tc_all = cell2mat(Tc);
ec_all = cell2mat(Ec);
Rsq_closed = calcR2(tc_all, ec_all);
% 5. Display Performance Summary Table
Partitions = {'Training (70%)'; 'Validation (15%)'; 'Testing (15%)'; 'Overall Open-Loop'; 'Overall Closed-Loop'};
MSE_Values = [mse(eo_train); mse(eo_val); mse(eo_test); mse(eo_all); mse(ec_all)];
R2_Values = [Rsq_train; Rsq_val; Rsq_test; Rsq_all; Rsq_closed];
disp(table(Partitions, MSE_Values, R2_Values, 'VariableNames', {'Partition', 'MSE', 'R_Squared'}));
3. Open-Loop vs. Closed-Loop Performance Analysis
Notice that open-loop R2 values typically approach 0.999 because true targets are supplied at every feedback step. The critical metric for deployment is Closed-Loop R2 (typically 0.92 − 0.98), which evaluates the model's stability when recursively feeding back its own past predictions over an autonomous forecast horizon.
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Explore similar technical troubleshooting questions and verified MATLAB solutions: