Error operands of = have illegal types `pointer to double' and `double' in mex

4 views (last 30 days)
I'm a bit of a beginner to C and I've tried my hand at learning how to use mex in Matlab. However, I've been hitting this error fairly often and I can't seem to be able to solve it. These are the relevant lines of code:
#include <matrix.h>
#include <mex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//declare variables
mxArray *sin_o_out_m, *cos_o_out_m;
mwSize *dims;
double Ac = 1, i, Time_Spacing = 0.000002032;
double Fc = 3500; //input
double* sin_o, *cos_o; //output
double rad;
dims = (mwSize *) mxMalloc (2 * sizeof (mwSize));
dims[0] = 30;
sin_o_out_m = plhs[0] = mxCreateCellArray(1,dims);
cos_o_out_m = plhs[1] = mxCreateCellArray(1,dims);
sin_o = mxGetPr(sin_o_out_m);
cos_o = mxGetPr(cos_o_out_m);
rad = 2*PI*Fc*i*Time_Spacing;
for(i=0;i<=30;i++)
{
sin_o[i]=-Ac*sin(rad);
cos_o[i]=Ac*cos(rad);
}
I'm pretty sure the problem is with the pointers, but anything I try to do doesn't seem to work. The version is Matlab 7.10.9 (R2010a). Thanks in advance for your help.

Answers (1)

James Tursa
James Tursa on 8 Apr 2015
Edited: James Tursa on 8 Apr 2015
You have created plhs[0] and plhs[1] as cell arrays, meaning that their data areas contain (mxArray *) types, not (double) types. So these lines makes no sense:
sin_o = mxGetPr(sin_o_out_m);
cos_o = mxGetPr(cos_o_out_m);
The data area of sin_o_out_m and cos_o_out_m are (mxArray *), but you use a function, mxGetPr, that treats these data areas as having (double) data in them. They don't. So you put double data in those spots when MATLAB is expecting pointers to mxArray variables. And downstream when it tries to access those memory areas as mxArray variables (and there are only doubles at those spots instead) MATLAB crashes.
You need to create these output arrays as double, not cell. E.g.,
sin_o_out_m = plhs[0] = mxCreateDoubleMatrix(30, 1, mxREAL);
cos_o_out_m = plhs[1] = mxCreateDoubleMatrix(30, 1, mxREAL);
Also, you should check to see if nlhs >= 2 before you assign anything to plhs[1]. Otherwise, if the user calls you function with only one output your function will crash MATLAB.
  2 Comments
Micael
Micael on 9 Apr 2015
Thank you, but now I find the following error: "Error operands of + have illegal types `pointer to double' and `double'".
James Tursa
James Tursa on 9 Apr 2015
Edited: James Tursa on 9 Apr 2015
Please post your current code. Do so by editing your original Question. Put the text "EDIT Apr-9-2015" at the end of your Question (do not delete anything), and then add your current code after that.

Sign in to comment.

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!