casadi_to_mex.hpp
1 //
2 // MIT No Attribution
3 //
4 // Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl, KU Leuven.
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining a copy of this
7 // software and associated documentation files (the "Software"), to deal in the Software
8 // without restriction, including without limitation the rights to use, copy, modify,
9 // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so.
11 //
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13 // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
14 // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
15 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
16 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
17 // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 //
19 
20 // SYMBOL "to_mex"
21 template<typename T1>
22 mxArray* casadi_to_mex(const casadi_int* sp, const T1* x) {
23  casadi_int nrow, ncol, c, k;
24 #ifndef CASADI_MEX_NO_SPARSE
25  casadi_int nnz;
26 #endif
27  const casadi_int *colind, *row;
28  mxArray *p;
29  double *d;
30 #ifndef CASADI_MEX_NO_SPARSE
31  casadi_int i;
32  mwIndex *j;
33 #endif /* CASADI_MEX_NO_SPARSE */
34  nrow = *sp++;
35  ncol = *sp++;
36  colind = sp;
37  row = sp+ncol+1;
38 #ifndef CASADI_MEX_NO_SPARSE
39  nnz = sp[ncol];
40  if (nnz!=nrow*ncol) {
41  p = mxCreateSparse(nrow, ncol, nnz, mxREAL);
42  for (i=0, j=mxGetJc(p); i<=ncol; ++i) *j++ = *colind++;
43  for (i=0, j=mxGetIr(p); i<nnz; ++i) *j++ = *row++;
44  if (x) {
45  d = (double*)mxGetData(p);
46  for (i=0; i<nnz; ++i) *d++ = casadi_to_double(*x++);
47  }
48  return p;
49  }
50 #endif /* CASADI_MEX_NO_SPARSE */
51  p = mxCreateDoubleMatrix(nrow, ncol, mxREAL);
52  if (x) {
53  d = (double*)mxGetData(p);
54  for (c=0; c<ncol; ++c) {
55  for (k=colind[c]; k<colind[c+1]; ++k) {
56  d[row[k]+c*nrow] = casadi_to_double(*x++);
57  }
58  }
59  }
60  return p;
61 }