libsvmwrite.c
Go to the documentation of this file.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "mex.h"
5 
6 #ifdef MX_API_VER
7 #if MX_API_VER < 0x07030000
8 typedef int mwIndex;
9 #endif
10 #endif
11 
13 {
14  mexPrintf(
15  "Usage: libsvmwrite('filename', label_vector, instance_matrix);\n"
16  );
17 }
18 
19 void libsvmwrite(const char *filename, const mxArray *label_vec, const mxArray *instance_mat)
20 {
21  FILE *fp = fopen(filename, "w");
22  int i, k, low, high, l;
23  mwIndex *ir, *jc;
24  int label_vector_row_num;
25  double *samples, *labels;
26  mxArray *instance_mat_col; // instance sparse matrix in column format
27 
28  if (fp == NULL)
29  {
30  mexPrintf("can't open output file %s\n", filename);
31  return;
32  }
33 
34  // transpose instance matrix
35  {
36  mxArray *prhs[1], *plhs[1];
37  prhs[0] = mxDuplicateArray(instance_mat);
38  if (mexCallMATLAB(1, plhs, 1, prhs, "transpose"))
39  {
40  mexPrintf("Error: cannot transpose instance matrix\n");
41  return;
42  }
43  instance_mat_col = plhs[0];
44  mxDestroyArray(prhs[0]);
45  }
46 
47  // the number of instance
48  l = (int) mxGetN(instance_mat_col);
49  label_vector_row_num = (int) mxGetM(label_vec);
50 
51  if (label_vector_row_num != l)
52  {
53  mexPrintf("Length of label vector does not match # of instances.\n");
54  return;
55  }
56 
57  // each column is one instance
58  labels = mxGetPr(label_vec);
59  samples = mxGetPr(instance_mat_col);
60  ir = mxGetIr(instance_mat_col);
61  jc = mxGetJc(instance_mat_col);
62 
63  for (i = 0; i < l; i++)
64  {
65  fprintf(fp, "%g", labels[i]);
66 
67  low = (int) jc[i], high = (int) jc[i + 1];
68  for (k = low; k < high; k++)
69  fprintf(fp, " %ld:%g", ir[k] + 1, samples[k]);
70 
71  fprintf(fp, "\n");
72  }
73 
74  fclose(fp);
75  return;
76 }
77 
78 void mexFunction(int nlhs, mxArray *plhs[],
79  int nrhs, const mxArray *prhs[])
80 {
81  // Transform the input Matrix to libsvm format
82  if (nrhs == 3)
83  {
84  char filename[256];
85  if (!mxIsDouble(prhs[1]) || !mxIsDouble(prhs[2]))
86  {
87  mexPrintf("Error: label vector and instance matrix must be double\n");
88  return;
89  }
90 
91  mxGetString(prhs[0], filename, mxGetN(prhs[0]) + 1);
92 
93  if (mxIsSparse(prhs[2]))
94  libsvmwrite(filename, prhs[1], prhs[2]);
95  else
96  {
97  mexPrintf("Instance_matrix must be sparse\n");
98  return;
99  }
100  }
101  else
102  {
103  exit_with_help();
104  return;
105  }
106 }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Definition: libsvmwrite.c:78
void exit_with_help()
Definition: libsvmwrite.c:12
void libsvmwrite(const char *filename, const mxArray *label_vec, const mxArray *instance_mat)
Definition: libsvmwrite.c:19


ml_classifiers
Author(s): Scott Niekum , Joshua Whitley
autogenerated on Sun Dec 15 2019 03:53:50