Azzera filtri
Azzera filtri

Using MEX file to edit MATLAB data struct

5 visualizzazioni (ultimi 30 giorni)
Bernie il 25 Mar 2014
Commentato: James Tursa il 17 Giu 2014
I have a function that takes a MATLAB data structure as an argument, uses the fields in that data structure to perform calculations, and returns that data structure with additional fields containing the results. I would like to convert that function to a Fortran MEX-file to speed up computation time (it contains some nested loops and lengthy calculations), but I am unsure how to deal with the data structure input/output. The MWE code is as follows:
% Some calculations performed up here...
a = 7;
b = 14;
c = 10;
% Package data into structure for ease of use
d.a = a;
d.b = b;
d.c = c;
% Call computational function
d = myfunction(d);
function [d] = myfunction(d)
% Perform some calculations using d
x = d.a^2;
y = d.b + 12;
z = d.c * 7;
% Package results into d
d.x = x;
d.y = y;
d.z = z;
In the actual code there are many more variables, so we use the struct to avoid having over 50 arguments to pass into and out of the function. Is there a way to implement this function in a Fortran MEX-file? (I would also accept a C/C++ MEX-file answer, as I'm sure there are more people out there using C than Fortran these days).
I've found documentation (the explore.c example) explaining struct input and struct output separately, but not much on how to modify the same struct and re-output it into MATLAB.
Thanks, Bernie
  3 Commenti
David Marx
David Marx il 17 Giu 2014
Sorry, but what do you mean by "deep data copy"?
I have a similar problem where I want to send data in a C struct to Matlab via a mex call. As far as I can tell, the only way is to create the mx struct with mxCreateStructArray(), and then copy field by field from the C struct to the mx struct. Is there a better way?
Thanks, David
James Tursa
James Tursa il 17 Giu 2014
@David: What you are proposing is the ONLY way. Since you cannot mix native C/C++ memory (e.g., stuff allocated with malloc or new etc.) into an mxArray, your only recourse is to create the return mxArray variable via mxCreateStructArray and then manually, field by field, create the field elements and copy the C/C++ native memory over into the data area of the field elements. Let me know if you need an example.

Accedi per commentare.

Risposte (0)


Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by