Using coder.extrinsics conditionally

164 views Asked by At

This question refers to Matlab coder extrinsic functionality. Some functions like fprintf are extrinsic in older Matlab version, and are not extrinsic in the newer ones. Is there a way to support several Matlab versions, if coder.extrinsics is allowed only at the top level, and it's not possible to put it under if statement?

2

There are 2 answers

0
Navan On

You cannot conditionally make some functions extrinsic directly. One way would be to use two different functions like fprintf_old and fprintf_new. fprintf_old would have coder.extrinsic declaration and then calls fprintf. fprintf_new can call fprintf without extrinsic declaration. Now you can pick between the two calls by checking for your version with a condition that is constant during compilation. For example,

if coder.const(isOlderVersion())
  fprintf_old();
else
  fprintf_new();
end
0
Ryan Livingston On

In code generation, feval constructs an extrinsic call to the function named in the first argument. Since you can embed calls to feval inside of control flow, it can be used to selectively call a function extrinsically and keep the code in a single source file:

if isOlderVersion()
  % Call fprintf extrinsically
  feval('fprintf');
else
  fprintf();
end