how to read in variable from workspace in s-function written in C without simulink crashing
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
When I add the following code to my mdlOutputs function, the mex compiler does not give any errors, but when I run my simulink model it crashes... any idea what I am doing wrong? I am trying to read in the variable temperature from my base workspace and then accessing the third element (in reality I would like to have the element that I am accessing dynamically changing but I will worry about this problem later when the static code finally works)
The variable temperature is a 730x2 matrix, when I try to define temperature[1] [2] as I would expected I needed since there are two dimension, the compiler does not work so I think there is a problem with indexing. The help of the mxGetPr does not really help me: "Call mxGetPr to access the real data in the mxArray that pm points to. Once you have the starting address, you can access any other element in the mxArray." The latter might be obvious to others, but I do not see how I can do this so any example code is highly appreciated...
real_T *temperature, *currentTemperature;
char array_name1[20] = "temperature";
const mxArray *array_ptr1;
array_ptr1 = mexGetVariablePtr("base", array_name1);
if (array_ptr1 == NULL){
mexErrMsgIdAndTxt( "MATLAB:mxislogical:getVariableFailed",
"Could not get the variable named temperature.\n");}
temperature = mxGetPr(array_ptr1);
*currentTemperature = temperature[3];
mxFree(array_name1)
y[0] = *currentTemperature;
0 comentarios
Respuesta aceptada
Kaustubha Govind
el 26 de Nov. de 2012
Your use of the MEX API looks fine to me, but I think you're making some syntactic mistakes:
*currentTemperature = temperature[3];
This line is trying to dereference the pointer currentTemperature, which does not point to any legitimate memory location at this point. If you simply want to get the value of temperature[3], you don't need to use a pointer. Just use:
real_T currentTemperature;
...
currentTemperature = temperature[3];
or, if you want to stick with a pointer:
real_T *currentTemperature;
...
currentTemperature = &(temperature[3]);
Also, you don't need:
mxFree(array_name1);
Since 'array_name1' is a stack variable, and not dynamically allocated using mxMalloc or mxCalloc.
About your question regarding the statement "Once you have the starting address, you can access any other element in the mxArray." - it basically means that mxGetPr returns a C-style builtin pointer to the array, so you can index the array just like you would in C with linear indexing.
Also, it looks like your ultimate goal should be to use tunable parameters with your S-function.
Más respuestas (0)
Ver también
Categorías
Más información sobre Simulink Coder en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!