Accessing a cell array of cell arrays in a C++ mex file

2 visualizzazioni (ultimi 30 giorni)
I'm writing a large code that requires me to use a cell array of cell arrays of single precision real matrices. This may seem odd, but there are good reasons centred on efficient storage, that I won't go into here. The simplest code that illustrates the problem that I have is:
#include "mex.h"
float fn(mxArray *strat)
{
float *indstrat, x;
indstrat = (float *)mxGetCell(mxGetCell(strat,0),0);
x = *(indstrat+1);
return x;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
(void) nlhs; (void) plhs;
fn(prhs[0]);
}
There's one input, a cell array of cell arrays of the form, for example, strat{i}{j}(k). In this fragment, I've used mxGetCell twice to extract the pointer to the {1}{1} vector, and then extracted the second value from that using '*(indstrat+1)'. However, debugging this in Visual Studio shows that the values aren't being extracted properly. I must be doing something wrong with the pointer to the array of pointers implicit in a cell array like this, but I can't see what. Should there be a '**' somewhere for a pointer to a pointer?
Can anyone tell me what I'm doing wrong?

Risposta accettata

Geoff Hayes
Geoff Hayes il 6 Ott 2014
John - check the function signature for mxgetcell - it returns a pointer to an mxArray object. So you would have to do something like the following
float fn(const mxArray *strat)
{
mxArray *tempMxArray = 0;
float *indstrat, x;
tempMxArray = mxGetCell(mxGetCell(strat,0),0);
indstrat = (float *)mxGetPr(tempMxArray);
x = *(indstrat+1);
return x;
}
It is very similar to what you had, we just assign the result of the double mxGetCell call to the tempMxArray pointer, and then use mxGetPr to get a pointer to the first element in your single data type matrix.
I tried the above with the following example where the mexFunction is defined as
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
float x;
x=fn(prhs[0]);
mexPrintf("%f\n", x);
}
And in MATLAB, the following is executed from the Command Line
cellArray = {};
cellArray{1} = {single(1:4)};
cellTest(cellArray); % where cellTest is the name of the c-file with above code
2.000000 % 2 is the output of the mex function
Given that the input matrix is [1 2 3 4], the output of 2 makes sense. (I needed to add the const qualifier on the fourth input to the mexFunction.)
  1 Commento
John Billingham
John Billingham il 7 Ott 2014
Thanks very much. It works fine now. In fact you don't actually need the temporary array.
indstrat = (float *)mxGetPr(mxGetCell(mxGetCell(strat,0),0));
works too.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Write C Functions Callable from MATLAB (MEX Files) in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by