【发布时间】:2021-03-17 15:46:02
【问题描述】:
我有 MATLAB 代码,我想调用 GNU 科学库 (GSL) C 库来计算矩阵的 singular value decomposition。基本上,我需要实现gateway MEX function。我知道如何设置输入变量,但是如何设置输出变量?
到目前为止,这是我的代码:
build.m
mex -v -L/home/miran045/reine097/c-libs/lib/ -R2017b project_m.c -lgsl -lgslcblas -lm
call_c_from_matlab.m
A_data = [1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0];
[U, S, V] = project_m(4, 5, A_data);
project_m_from_c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include "mex.h"
void run_svd(const size_t M, const size_t N, double A_data[], gsl_matrix * B, gsl_matrix * V, gsl_vector * S, gsl_vector * work)
{
gsl_linalg_SV_decomp(B, V, S, work);
}
static double
get_double(const mxArray *array_ptr)
{
double *pr;
pr = mxGetPr(array_ptr);
double result = (double) *pr;
return result;
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
int i, j;
/* You should put code here to check nrhs, nlhs, prhs[0], prhs[1], prhs[2] */
int m = (int) get_double(prhs[0]);
int n = (int) get_double(prhs[1]);
double *mexArray = mxGetPr(prhs[2]);
int Bm, Bn; /* added */
gsl_matrix * B;
gsl_matrix * V;
gsl_vector * S;
gsl_vector * work;
gsl_matrix_view A = gsl_matrix_view_array(mexArray, m, n);
if (n > m) {
Bm = n; Bn = m; /* added */
work = gsl_vector_alloc(m);
gsl_matrix_transpose_memcpy(B, &A.matrix);
} else {
Bm = m; Bn = n; /* added */
work = gsl_vector_alloc(n);
gsl_matrix_memcpy(B, &A.matrix);
}
plhs[0] = mxCreateDoubleMatrix( Bm, Bn, mxREAL );
plhs[1] = mxCreateDoubleMatrix( Bn, 1, mxREAL );
plhs[2] = mxCreateDoubleMatrix( Bn, Bn, mxREAL );
run_svd(m, n, mexArray, plhs[0], plhs[2], plhs[1], work);
gsl_vector_free(work);
}
但是我收到以下错误:
gsl: ../gsl/gsl_matrix_double.h:278: ERROR: first index out of range
Default GSL error handler invoked.
matlab&
[2] 130182
[1] Killed matlab
reine097@native [/panfs/roc/groups/4/miran045/reine097] % MATLAB is selecting SOFTWARE OPENGL rendering.
MATLAB: smart_ptr.cpp:82: matrix::unique_mxarray_ptr matrix::from_matlab(mxArray* const&): Assertion `Input to from_matlab must have temporary or local scope' failed.
matlab&
[3] 115869
[2] Segmentation fault (core dumped) matlab
reine097@native [/panfs/roc/groups/4/miran045/reine097] % MATLAB is selecting SOFTWARE OPENGL rendering.
reine097@native [/panfs/roc/groups/4/miran045/reine097] % gsl: svd.c:79: ERROR: length of workspace must match second dimension of matrix A
Default GSL error handler invoked.
matlab&
[4] 89615
[3] Killed matlab
【问题讨论】: