Matlab: Mex-File - Matrix Multiplication

9 views (last 30 days)
alty
alty on 26 May 2016
Commented: Steven Lord on 26 May 2016
Hello everyone,
I am looking for a way to implement a matrix multiplication (2 square matrices) using the mex-function.
This is my code so far:
#include <mex.h>
/* core */
double MM(double A, double B, double C, double ii, double jj, double kk, double n, double A[10][10], double B[10][10], double C[10][10])
// double n;
// double A[10][10];
// double B[10][10];
// double C[10][10];
{
for (ii = 1; ii = n; ii ++){
for (jj = 1; jj = n; jj ++){
for (kk = 1; kk = n; kk ++){
C( ii , jj ) = C( ii , jj ) + A( ii , kk ) * B( kk , jj ) ;
}
}
}
return C;
}
/* mex-function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double A, B, C, ii, jj, kk, n ;
double *result;
/* error-message */
if (nrhs < 2) mexErrMsgTxt("Error: missing input arguments!");
/* warning-message */
else if (nrhs > 2) mexWarnMsgTxt("too many input arguments!");
/* type check */
if ((!mxIsCell(prhs[0])) || (!mxIsCell(prhs[1]))) {
mexErrMsgTxt("Both inputs have to be type cell!");
}
if (sizeof(prhs[0])!= sizeof(prhs[1])) {
mexErrMsgTxt("not the same input size!");
}
A = *mxGetPr(prhs[0]);
B = *mxGetPr(prhs[1]);
n = sizeof(prhs[0]);
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
result = mxGetPr(plhs[0]);
result [0]= MM(A,B);
}
Since I am new to using c in matlab, any help would be deeply appreciated! I always get error messages but I just can not figure out where its going wrong.
Thank you so much!
  2 Comments
James Tursa
James Tursa on 26 May 2016
Edited: James Tursa on 26 May 2016
This code has a lot of errors in it. It kinda looks like you took some code that was written to multiply two scalars and return a scalar result, and then naively tried to expand it to do matrix multiplication. Is that what happened here? To fix this, you need to switch all of that scalar stuff to pointers, and then calculate the indexing into the matrices manually. I can do that, but maybe as a first step you should get that scalar multiply version working first since it will be much simpler. And then only consider doing a matrix multiply version of this once you are very comfortable working with pointers in C. Let me know.
Steven Lord
Steven Lord on 26 May 2016
Why are you trying to implement matrix multiplication in a MEX-file yourself? Is there a reason you can't or don't want to:
  1. Use the * operator in MATLAB
  2. Call mexCallMATLAB from your MEX-file to have MATLAB call "mtimes"

Sign in to comment.

Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!