Clear Filters
Clear Filters

Access preallocated matrix on left hand side inside MEX

2 views (last 30 days)
I recently wondered whether there would be a way/mechanism to write immediately into the data array of a preallocated "left hand side" matrix from a MEX or not. Or even, detect, whether the LHS of a MEX call has already been allocated or not, and if so, reuse the memory without reallocating a new array. E.g.:
x = zeros(m,n)
for i = 1:m
tmp = unbelievableMexFunction(inputvariables, i); % with numel(tmp) approx. 3e6
x(i,:) = furtherProcessing(tmp);
end
Now, usually one would allocate a result matrix inside the MEX, but during the '='-instruction the Matlab mechanism will supposedly keep tmp in memory while the MEX code is executing and returning another matrix of same size (using twice as much memory at that moment) and requiring allocation of a big memory chunk at each iteration.
Or even, might it be feasible to immediately write data into a submatrix (although this would also require mechanisms to read out matrix dimensions of the entire lhs-matrix for correct pointer-arthmetic):
x = zeros(m,n)
for i = 1:m
x(i,:) = unbelievableMexFunction2(inputvariables, i); % with numel(x) approx. 3e6
end
Might one of both be feasible with doing a kind of fancy hack on subsref for matrices (or a dedicated matrix-wrapper-class).
I know that one could write to the data array of a rhs-matrix, but that's no answer on my question, just as any suggestions to "address my problem differetly"... there is no particular problem, I just want to know whether it would be feasible or not! ;)
Thanks for your suggestions.

Accepted Answer

Jan
Jan on 4 Aug 2011
It is not feasible.
Look at the MEX interface: You do not get any pointers to the LHS variables. In opposite: the MEX has to create them. Therefore the MEX cannot obtain any information about the LHS in any way.
And this is a remarkable and hard drawback.
  2 Comments
Pierre
Pierre on 4 Aug 2011
>> And this is a remarkable and hard drawback.
I wouldn't call it THAT hard drawback, though nice to have... on the other hand, I have to admit that one might create pitfalls for "mex-beginners" by enabling the user to mess on LHS variables.

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 4 Aug 2011
To do what you are asking to do, you would pass in x as an input argument and then modify it in place (i.e., it would be one of the prhs). This can have unintentional side effects, however, if x is shared with another variable. In your particular example it would be OK because you know it is not shared, but if one were to do a statement such as y = x before doing the mex call and then if x were modified in place, y would also get unintentionally modified as well.

Community Treasure Hunt

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

Start Hunting!