


PURPOSE: calculate r square using data y and estimates yhat
-------------------------------------------------------------------
USAGE: R2 = rsquare(y,yhat)
where:
y are the original values as vector or 2D matrix and
yhat are the estimates calculated from y using a regression, given in
the same form (vector or raster) as y
-------------------------------------------------------------------------
OUTPUTS:
R2 is the r square value calculated using 1-SS_E/SS_T
-------------------------------------------------------------------
Note: NaNs in either y or yhat are deleted from both sets.
Felix Hebeler, Geography Dept., University Zurich, Feb 2007

0001 function R2 = rsquare(y,yhat) 0002 % PURPOSE: calculate r square using data y and estimates yhat 0003 % ------------------------------------------------------------------- 0004 % USAGE: R2 = rsquare(y,yhat) 0005 % where: 0006 % y are the original values as vector or 2D matrix and 0007 % yhat are the estimates calculated from y using a regression, given in 0008 % the same form (vector or raster) as y 0009 % ------------------------------------------------------------------------- 0010 % OUTPUTS: 0011 % R2 is the r square value calculated using 1-SS_E/SS_T 0012 % ------------------------------------------------------------------- 0013 % Note: NaNs in either y or yhat are deleted from both sets. 0014 % 0015 % Felix Hebeler, Geography Dept., University Zurich, Feb 2007 0016 0017 if nargin ~= 2 0018 error('This function needs some exactly 2 input arguments!'); 0019 end 0020 0021 % reshape if 2d matrix 0022 yhat=reshape(yhat,1,size(yhat,1)*size(yhat,2)); 0023 y=reshape(y,1,size(y,1)*size(y,2)); 0024 0025 % delete NaNs 0026 while sum(isnan(y))~=0 || sum(isnan(yhat))~=0 0027 if sum(isnan(y)) >= sum(isnan(yhat)) 0028 yhat(isnan(y))=[]; 0029 y(isnan(y))=[]; 0030 else 0031 y(isnan(yhat))=[]; 0032 yhat(isnan(yhat))=[]; 0033 end 0034 end 0035 0036 % 1 - SSe/SSt 0037 R2 = 1 - ( sum( (y-yhat).^2 ) / sum( (y-mean(y)).^2 ) ); 0038 0039 % SSr/SSt 0040 % R2 = sum((yhat-mean(y)).^2) / sum( (y-mean(y)).^2 ) ; 0041 0042 if R2<0 || R2>1 0043 error(['R^2 of ',num2str(R2),' : yhat does not appear to be a valid estimate of y from a regression.']) 0044 end