adding a save command to libSVM MATLAB Interface

Although libSVM can be easily manipulated under MATLAB with MATLAB Interface, users are required to write some codes to save their trained models in libSVM model format instead of MATLAB structs.

There is a function to save models in svm.cpp which is included in the libsvm-mat package, and the following code will give you a way to save models in libSVM format. It is also needed to add lines into the Makefile to compile the code.

The command can be invoked under MATLAB as [code]>> svm_save(model, 'filename');[/code] where svm_save is the name of this command, and model and filename represent the model to be saved, and the filename in which the model should be written respectively.

Plz, use this code at your own risk.

[code] #include #include #include #include "svm.h" #include "mex.h" #include "svm_model_matlab.h" #define CMD_LEN 2048 void exit_with_help(){ } static void fake_answer(mxArray *plhs[]) { plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL); } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { struct svm_model *model; if(nrhs > 3 || nrhs < 1) { exit_with_help(); fake_answer(plhs); return; } if(mxIsStruct(prhs[0])){ const char *error_msg; model = (struct svm_model *) malloc(sizeof(struct svm_model)); error_msg = matlab_matrix_to_model(model, prhs[0]); if(error_msg) { mexPrintf("Error: can't read model: %s¥n", error_msg); svm_destroy_model(model); fake_answer(plhs); return; } if(mxIsChar(prhs[1])){ int buflen,status; char * filename; buflen = (mxGetM(prhs[1]) * mxGetN(prhs[1])) + 1; filename = mxCalloc(buflen, sizeof(char)); status = mxGetString(prhs[1], filename, buflen); if (status != 0) mexWarnMsgTxt("Not enough space. String is truncated."); svm_save_model(filename,model); }else{ mexPrintf("filename should be given as char(s)¥n"); } svm_destroy_model(model); }else{ mexPrintf("model file should be a struct array¥n"); fake_answer(plhs); } return; } [/code]