필터 지우기
필터 지우기

Is there a version switch for codegen?

조회 수: 1 (최근 30일)
Patrick Vogt
Patrick Vogt 2019년 10월 30일
댓글: Patrick Vogt 2019년 11월 3일
Is it possible to branch which part of the code is generated to C based on the current Matlab version, that is generating code at compile time?
For example I have a function which uses runtime recursion (which is only possible after R2016B) and an alternative without runtime recursion and I want to somehow switch between the factorial and the recursive line in the below simplified example based on the Matlab version generaing code from this function in order to make it backwards compatible with Matlab before R2016B.
function [x] = codertest(a)
if verLessThan('matlab', '9.1')% starting with R2016B runtime recursion is allowed in code generation
% some pragma like %#codegen or a function like coder.target is needed here to switch at compile time
x = factorial(a);
else
x = recursive(a);
end
end
function [rec] = recursive(x)
if x == 1
rec = x;
else
rec = x*recursive(x - 1);
end
end
The file can be compiled with:
>> Tx = coder.typeof(1, [1, 1], [false, false]);
>> codegen('codertest.m', '-args', '{Tx}');
When I run these lines, Matlab before R2016B should therefore generate code using the "factorial" lines and Matlab after R2016B should use the "recursive" lines.
Simply using
coder.extrinsic('verLessThan');
does not solve the problem because this switches at runtime and then code generation will fail e.g. in R2015B with
??? Recursive calls are not allowed. Function 'recursive' participated in a recursive call.
which is exactly what I try to prevent.

채택된 답변

Ryan Livingston
Ryan Livingston 2019년 11월 2일
편집: Ryan Livingston 2019년 11월 2일
Use coder.const to forcibly constant fold the extrinsic call to verLessThan
if coder.const(verLessThan('matlab', '9.1'))
% Older style code
else
% Newer style code
end
The doc on this has more examples on constant folded extrinsic functions:
  댓글 수: 2
Walter Roberson
Walter Roberson 2019년 11월 3일
Ah, I had not encountered that before!
Patrick Vogt
Patrick Vogt 2019년 11월 3일
Works perfectly, thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by