如何在mex文件中创建单个浮点稀疏矩阵

时间:2013-12-12 19:26:54

标签: matlab sparse-matrix mex

Creating sparse matrix in MEXmxCreateSparse上有一个很好的例子。但是这个函数返回double稀疏矩阵而不是single。如果我想返回一个稀疏矩阵,我该怎么办?谢谢!

1 个答案:

答案 0 :(得分:3)

建议@horchler,您可以使用未记录的函数mxCreateSparseNumericMatrix。例如:

singlesparse.c

#include "mex.h"
#include <string.h>    /* memcpy */

/* undocumented function prototype */
EXTERN_C mxArray *mxCreateSparseNumericMatrix(mwSize m, mwSize n, 
    mwSize nzmax, mxClassID classid, mxComplexity ComplexFlag);

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    const float pr[] = {1.0, 7.0, 5.0, 3.0, 4.0, 2.0, 6.0};
    const mwIndex ir[] = {0, 2, 4, 2, 3, 0, 4};
    const mwIndex jc[] = {0, 3, 5, 5, 7};
    const mwSize nzmax = 10;
    const mwSize m = 5;
    const mwSize n = 4;

    plhs[0] = mxCreateSparseNumericMatrix(m, n, nzmax, mxSINGLE_CLASS, mxREAL);
    memcpy((void*)mxGetPr(plhs[0]), (const void*)pr, sizeof(pr));
    memcpy((void*)mxGetIr(plhs[0]), (const void*)ir, sizeof(ir));
    memcpy((void*)mxGetJc(plhs[0]), (const void*)jc, sizeof(jc));
}

用法:

>> mex -largeArrayDims singlesparse.c

>> s = singlesparse()
s =
   (1,1)        1
   (3,1)        7
   (5,1)        5
   (3,2)        3
   (4,2)        4
   (1,4)        2
   (5,4)        6
>> ss = double(s);
>> whos s ss
  Name      Size            Bytes  Class     Attributes

  s         5x4               160  single    sparse    
  ss        5x4               152  double    sparse    

>> f = full(s)
One or more output arguments not assigned during call to "full". 
>> f = full(ss)
f =
     1     0     0     2
     0     0     0     0
     7     3     0     0
     0     4     0     0
     5     0     0     6

>> s + s;
Undefined function 'plus' for input arguments of type 'single' and attributes 'sparse 2d real'. 
>> ss + ss;
>> 2 * s;
Error using  * 
Undefined function 'times' for input arguments of type 'single' and attributes 'sparse 2d real'. 
>> 2 * ss;
>> s * s';
Error using  * 
MTIMES is not supported for one sparse input and one single input. 
>> ss * ss';

>> nnz(s)
ans =
     7
>> nzmax(s)
ans =
    10

>> dmperm(s)
Undefined function 'dmperm' for input arguments of type 'single'. 
>> dmperm(ss)
ans =
     1     3     0     5

>> svds(s)
Error using horzcat
The following error occurred converting from double to single:
Error using single
Attempt to convert to unimplemented sparse type
Error in svds (line 64)
B = [sparse(m,m) A; A' sparse(n,n)]; 
>> svds(ss)
ans =
    9.9249
    5.5807
    3.2176
    0.0000

>> % abs(s), cos(s), sin(s), s.^2, s.*s, etc.. all give errors

正如您所看到的,稀疏单个数组已成功创建,但是许多函数希望该数组的类型为double,因此有很多缺少的功能......

另一个限制是你不能在MATLAB中创建多维稀疏数组,它们必须是二维矩阵..

底线是:在MATLAB中坚持使用双稀疏2D矩阵