From: Bas on
Hi group,

long time matlab user but beginner with C and mexfiles here. I have
some algorithm written in matlab, which I want to compile and
encapsulate in a loop in a C program. One of the outputs of the
function is a state to be passed to the next iteration. The matlab
function will look something like


function [next_state, outputs] = my_fun(current_state, inputs)
outputs = some_computation(inputs);
if some_condition(inputs)
next_state = current_state;
else
next_state = current_state;
nest_state.foo = next_state.foo + 1;
end


which I want to call from C as (untested pseudocode):


mxArray* mInputs
mxArray* mOutputs
mxArray* mState
mxArray* mState_new

/* initial state */
mState = mxCreateDoubleMatrix(0, 0, mxREAL); #start with empty state


while(not_finished()) {
/* get input data */
mInputs = mxCreate...
...

/* call matlab function */
my_compiled_fun(2, &mState_new, &mOutputs, mState, mInputs);

/* do something with output data */
pData = mxGetPr(mOutputs);
...

/* destroy old state and update current state*/
mxDestroyArray(mState);
mState = mState_new;

mxDestroyArray(mOutputs);
mxDestroyArray(mInputs);

}
mxDestroyArray(mState);


Depending on the matlab algorithm, I might pass an unmodified state or
a modified state. If I understand it correctly, when Matlab makes a
copy of a variable, it simply makes a pointer to a the old data, and
only allocates new memory when the data is modified ('copy on write').
My worry is that in case I do not modify the state, matlab simply
passes a pointer to the old state, so mxDestroing the old state will
also destroy the new state. Is this assumption correct or is all that
transparent for the user? And is the way I create, destroy and pass
the mxArrays around correct? This program is supposed to run in real
time for very long periods, so I do care about memory leaks and all
that.

Thanks,
Bas
 | 
Pages: 1
Prev: evaluetion of segmentation
Next: Removing columns