Wrapping a MEX function that has an "ans" output in some cases
Show older comments
I have a MEX function that returns an "ans" output in some cases, but in others not. It looks something like this:
/* Listing: fooMEX.c */
#include <mex.h>
void mexFunction(int resc, mxArray *resv[], int argc, const mxArray *argv[]) {
mxAssert(argc==1 && mxIsLogicalScalar(argv[0]), "nope");
bool with_ans = mxIsLogicalScalarTrue(argv[0]);
if (with_ans) {
resv[0] = mxCreateDoubleScalar(42);
}
}
Usage from MATLAB:
fooMEX(false) % no ans
fooMEX(true) % ans = 42
Now I want wrap this function in a MATLAB function, but I don't see how it can be done. This doesn't work:
function varargout = foo(with_ans)
/* ERROR: "One or more output arguments not assigned during call to "fooMEX" */
varargout{1:nargout} = fooMEX(with_ans);
end
I can achieve it with a try-catch, but that's an ugly hack:
function varargout = foo(with_ans)
try
varargout{1:nargout} = fooMEX(with_ans);
catch
fooMEX(with_ans);
end
end
Is there a better way?
Joel
P.S: This is a simplified context. In the real context, "with_ans" is actually an index corresponding to one out of thousands of wrapped C++ functions. The wrapping functions, with different indices, are member functions of a "classdef" style MATLAB class.
Accepted Answer
More Answers (1)
Walter Roberson
on 25 Sep 2015
If you need to you can test nargout and only do the assignment when it is at least 1.
However, my recollection is that the presence or absence of an output is carried "upstream". Test this:
fooz = @(x)find(x+nargout);
bar = @(x) fooz(x);
bar(-2:2)
z = bar(-2:2)
[z,q] = bar(-2:2)
The changes in output reflect that fooz sees different nargout even though the nargout is being inherited from its caller bar.
I would thus suspect that you can possibly code with a real variable name rather than varargout, and let the nargout be inherited from the caller.
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!