1 //------------------------------------------------------------------------------
2 // GB_mex_cast: cast a MATLAB array using C-style casting rules
3 //------------------------------------------------------------------------------
4 
5 // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
6 // SPDX-License-Identifier: Apache-2.0
7 
8 //------------------------------------------------------------------------------
9 
10 // Usage: C = GB_mex_cast (X, type) casts the dense array X to given type using
11 // C-style typecasting rules instead of MATLAB's rules.
12 
13 #include "GB_mex.h"
14 
15 #define USAGE "C = GB_mex_cast (X, type, cover)"
16 
mexFunction(int nargout,mxArray * pargout[],int nargin,const mxArray * pargin[])17 void mexFunction
18 (
19     int nargout,
20     mxArray *pargout [ ],
21     int nargin,
22     const mxArray *pargin [ ]
23 )
24 {
25 
26     // do not get coverage counts unless the 3rd arg is present
27     bool do_cover = (nargin == 3) ;
28     bool malloc_debug = GB_mx_get_global (do_cover) ;
29 
30     // check inputs
31     if (nargout > 2 || nargin < 1 || nargin > 3)
32     {
33         mexErrMsgTxt ("Usage: " USAGE) ;
34     }
35 
36     if (mxIsSparse (pargin [0]))
37     {
38         mexErrMsgTxt ("X must be dense") ;
39     }
40 
41     // get X
42     GB_void *X ;
43     int64_t nrows, ncols ;
44     GrB_Type xtype ;
45     GB_mx_mxArray_to_array (pargin [0], &X, &nrows, &ncols, &xtype) ;
46     if (xtype == NULL)
47     {
48         mexErrMsgTxt ("X must be numeric") ;
49     }
50 
51     // get the type for C, default is same as X
52     GrB_Type ctype = GB_mx_string_to_Type (PARGIN (1), xtype) ;
53     if (ctype == NULL)
54     {
55         mexErrMsgTxt ("C must be numeric") ;
56     }
57 
58     // create C
59     pargout [0] = GB_mx_create_full (nrows, ncols, ctype) ;
60     if (ctype == Complex) ctype = GxB_FC64 ;
61     if (xtype == Complex) xtype = GxB_FC64 ;
62     GB_void *C = mxGetData (pargout [0]) ;
63 
64     // cast the data from X to C
65     GB_cast_array (C, ctype->code, X, xtype->code, NULL,
66         xtype->size, nrows*ncols, 1) ;
67 
68     GB_mx_put_global (do_cover) ;
69 }
70 
71