2.2 Call of Tool Box Function
The TOOL BOX function is defined in a file that is the extension of the extension, such as regress.m is a toolbox function, used to calculate multi-linear regression, the function body is as follows:
Function [B, BINT, R, RINT, STATS] = Regress (Y, X, Alpha)
IF Nargin <2,
Error ('Regress Requires At Least TWO Input Arguments.');
end
if Nargin == 2,
Alpha = 0.05;
end
% Check That Matrix (x) And Left Hand Side (Y) Have Compatible Dimensions
[n, p] = size (x);
[N1, COLLHS] = Size (Y);
IF n ~ = n1,
Error ('The Number of Rows in y Must equal the number of rows in x.');
end
if collhs ~ = 1,
Error ('Y Must Be a Vector, Not A Matrix');
end
% Remove Missing Values, IF Any
Wasnan = (Isnan (Y) | An (Isnan (x), 2));
IF (ANY (WASNAN))
y (wasnan) = [];
X (Wasnan, :) = [];
N = Length (Y);
end
% Find The Least Squares Solution.
[Q, r] = qr (x, 0);
B = r / (q '* y);
% Find A Confidence Interval for Each Component of X
% Draper and Smith, Equation 2.6.15, Page 94
Ri = R / Eye (P);
XDIAG = SQRT (SUM ((RI. * ri) ', 1))';
Nu = N-P;% Residual Degrees of Freedom
YHAT = x * b;% Predicted Responses at Each Data Point.
R = Y-yHAT;% Residuals.
IF NU ~ = 0
RMSE = Norm (r) / SQRT (NU);% root mean square error.
Else
RMSE = INF;
end
S2 = RMSE ^ 2;% Estimator OF Error Variance.
TVAL = TINV ((1-alpha / 2), NU);
Bint = [B-TVAL * xDiag * RMSE, B TVAL * xDiag * rmse];
% Calculate R-Squared.
IF Nargout == 5,
RSS = NORM (YHAT-mean (y)) ^ 2;% regression sum of squares.
TSS = Norm (Y-Mean (Y)) ^ 2;% Total Sum of Squares.
R2 = RSS / TSS;% R-Square statistic.
IF (p> 1)
F = (RSS / (P-1)) / S2;% F statistic for regressionelse
F = nan;
end
Prob = 1 - FCDF (F, P-1, Nu);% Significance Probability for Regression
Stats = [R2 F Prob];
% All That Requires a constant. Do WE HAVE ONE?
IF (~ any (all (x == 1))))))
% Apparently NOT, But Look for an Implied Constant.
B0 = r / (q '* ones (n, 1));
IF (SUM (ABS (1-x * B0))> N * SQRT (EPS)))
Warning (Sprintf (['R-Square is not well defined unless x hans "...
'a column of ones./ntype "Help Regress" for' ...
'more information.']));
end
end
end
% Find The Standard Errors of the Residuals.
% Get The Diagonal Elements of The "HAT" Matrix.
% Calculate The Variance Estimate Obtained by Removing Each Case (I.E. Sigmai)
% see ChatterJee and Hadi P. 380 Equation 14.
T = x * ri;
Hatdiag = SUM ((t. * t) ', 1)';
OK = (1-HatDiag)> SQRT (EPS));
HATDIAG (~ OK) = 1;
IF NU <1,
Ser = rmse * one (length (y), 1);
Elseif Nu> 1
DENOM = (NU-1). * (1-HATDIAG);
Sigma = Zeros (Length (Denom), 1);
Sigmai (OK) = SQRT ((Nu * S2 / (Nu-1)) - (R (OK). ^ 2 ./ Denom (OK)));
Ser = SQRT (1-HATDIAG). * Sigmai;
SER (~ ok) = inf;
Elseif Nu == 1
Ser = SQRT (1-HATDIAG). * RMSE;
SER (~ ok) = inf;
end
% Create Confidence Interval for Residuals.
Z = [(R-TVAL * Ser) (R TVAL * Ser)] ';
RINT = Z ';
% Restore Nan So Inputs and Outputs Conform
IF (Nargout> 2 & ANY (WASNAN))
TMP = "SIZE (WASNAN);
TMP (:) = nan;
TMP (~ Wasnan) = R;
R = TMP;
end
IF (NARGOUT> 3 & ANY (WASNAN))
TMP = Ones (Length (Wasnan), 2);
TMP (:) = nan;
TMP (~ Wasnan, :) = RINT;
RINT = TMP;
end
Since this function is written by Matlab's proprietary language, it is not a C language, so we can't use it directly in our programs. However, it doesn't matter Matlab to provide us with powerful tool Mcc.exe, which can translate the function in the .m file into the C / C program we need, this function makes our development less. The method of use of MCC will be specifically described below.
1. Set a valid C compiler that uses the compiler LCC C Version 2.4 with the MATLAB.
Enable the MATLAB environment, enter in Command WINDOW
>> MBUILD -SETUP
Please choose your compiler for building Standalone Matlab Applications:
Would You Like Mbuild To Locate Installed Compilers [Y] / n? Y
SELECT A Compiler:
[1] LCC C Version 2.4 in D: / Matlab / Sys / LCC
[2] Microsoft Visual C / C Version 6.0 in C: / Program FILES / Microsoft Visual Studio
[0] none
Compiler: 1
Please Verify your Choices:
Compiler: LCC C 2.4
Location: D: / Matlab / Sys / LCC
Are Thase Correct? ([Y] / N): Y
The Default Options File:
"C: / Documents and Settings / Administrator / Application Data / MathWorks / Matlab / R12 / Compopts.bat"
Is Being Updated from d: /matlab/bin/win32/Mbuildopts/lcccompp.bat ...
Now we have set a C / C compiler in D: / MATLAB / SYS / LCC to the compiler we have to use.
2. You can now use the MCC to generate a C file. Here we use the regress.m as an example to generate the corresponding C language file. Enter in Command Window
>> MCC -M Regress
After the execution, you open the
Enter in Command Window
>> MCC -P Regress
After the execution is completed, the corresponding CPP file can be generated in the Work directory.
3. Create a new console program, the main program code is as follows:
#pragma HDRSTOP
#include
#include
#include
#include "libmatlb.h"
#include "libmmfile.h"
#include "regress.h"
#include "fcdf.h"
#include "tinv.h"
#include "chi2cdf.h"
#include "distchck.h"
#include "betainv.h"
#include "norminv.h"
#include "gamcdf.h"
#include "betacdf.h"
#include "betaPDF.H"
#pragma argsused
Static _mexinittermTableEntry Init_Term_Table [11]
= {{libmmfileinitialize, libmmfileterminate},
{INITIALIZEMODULE_REGRESS, TERMINATEMODULE_REGRESS},
{INITIALIZEMODULE_FCDF, TERMINATEMODULE_FCD},
{INITIALIZEMODULE_TINV, TERMINATEMODULE_TINV},
{INITIALIZEMODULE_CHI2CDF, TERMINATEMODULE_CHI2CDF},
{INITIALIZEMODULE_DISTCHCK, TERMINATEMODULE_DISTCHCK},
{INITIALIZEMODULE_BETAINV, TERMINATEMODULE_BETAINV},
{INITIALIZEMODULE_NORMINV, TERMINATEMODULE_NORMINV},
{INITIALIZEMODULE_GAMCDF, TERMINATEMODULE_GAMCDF},
{INITIALIZEMODULE_BETACDF, TERMINATEMODULE_BETACDF},
{INITIALIZEMODULE_BETAPDF, TERMINATEMODULE_BETAPDF}}
Static Double BUF1 [] = {1, 2, 3, 3, 2, 1, 3, 3, 4};
Static Double BUF2 [] = {3, 4, 4};
INT Main (int Argc, const char * * argv) {
MxArray * x = NULL;
MxArray * y = NULL;
MxArray * alpha = NULL;
MxArray * bint = null, * r = null, * RINT = NULL;
MxArray * status = null, * b = null;
/ * Enable Automated Memory Management * /
mlfenternewContext (0, 0);
/ * CREATE The Matrices and Assign Data to Them * /
MLFASSIGN (& x, Mlfdoublematrix) (3, 3, BUF1, NULL);
MLFASSIGN (& Y, MLFDOUBLEMATRIX (3, 1, BUF2, NULL);
Mlfassign (& Alpha, MLFSCALAR (1));
/ * Print The Matrices * /
MLFPrintMatrix (x);
MLFPrintmatrix (Y);
INT I;
For (i = 0; i { INIT_TERM_TABLE [I] .initialize (); } B = MLFREGRESS (& BINT, & R, & RINT, & Status, Y, X, Alpha); // b = mlfregress (NULL, NULL, NULL, NULL, MAT0, MAT1, Alpha); MLFPrintMatrix (b); MLFPrintMatrix (bint); MLFPrintMatrix (r); mlfprintmatrix (RINT); MLFPrintMatrix (status); / * Free the matices * / MXDESTROYARRAY (X); MXDESTROYARRAY (Y); For (i = 0; i { INIT_TERM_TABLE [I] .TERMINATE (); } / * Disable Automated Memory Management * / MLFRESTOREPREVIUSCONTEXT (0, 0); Return (exit_success); } 2.3 Another optional method for calling the Tool Box function 2.2 The method of calling the Toolbox function proposed is complicated because the MATLAT compiler will generate a large pile of C / C source code files and header files, which is more complicated to these source code, with the continuous development of the system. The maintenance of the source code generated by the programmer will become extremely difficult, and another way to choose from: compile the Toolbox function into a dynamic link library. For programmers, the reuse of the binary level is easier to maintain and use more easily than the reuse of the source code level. So how do you compile the Toolbox function into a dynamic link library? Fortunately, the MATLAT compiler can do this task for us! Let me tell it below. First set the MCC (see chapter 2.2 for the use of MCC). Then enter the following command: MCC -T -W LIB: TEST -TLINK: LIB Betaln Erf ERFCORE Realmax BetAn Erfcore Realmax BetAn ERFCORE Realmax Betacdf BetaPdf Erfc Gammaln Betacore Erfc Gammainc Gamcdf Distchck Betainv Norminv Betainc Chi2cdf Tinv Mean Fcdf Regress Executing this command will generate a declaration header file that exports functions in Test.dll, Test.Lib, and DLL. With these files, you can easily call the functions in the DLL. note 1 The main purpose of this command is to generate the REGRESS function, but since the calculation regress is required to be called to those subunies such as Betaln, Erf, ErfCore, so I will write such a big string, if only only execute MCC -T -W LIB: TEST -T LINK: LIB REGRESS The MATLAT compiler will give an error message. 2 Compiler Lib File is Coff Format, if you want BCB Meditation loading DLL , Then need Coff Format transition into omf format. Can be used Coff2omf.exe This tool, or sure Implib.exe Regeneration Lib file. The use of these two tools can refer to their help.