matlab编码器的要求比普通的matlab更严格

matlab编码器的要求比普通的matlab更严格,matlab,matlab-coder,Matlab,Matlab Coder,考虑以下matlab程序: function results = prog() opts.x = 1; if ~isfield(opts, 'y'); opts.y = 1; end 'asdf' return 我能够在matlab中成功运行该程序,但是当我尝试使用编码器将其转换为C时,我得到以下错误: This structure does not have a field 'y'; new fields cannot be added when structure

考虑以下matlab程序:

function results = prog()
    opts.x = 1;
    if ~isfield(opts, 'y'); opts.y = 1; end
    'asdf'
return
我能够在matlab中成功运行该程序,但是当我尝试使用编码器将其转换为C时,我得到以下错误:

This structure does not have a field 'y'; new fields cannot be added when structure has been read or used.
我想知道是否有一种方法可以使用coder(或者其他工具)转换成C,而不使用更严格的编译器,就像我使用coder时所使用的那样。我使用的是matlab版本R2019B


请注意,这只是编码器如何使用比普通matlab更严格的编译器的众多示例之一。我有一个相当大的程序,我想转换成C,我不想经历每一个错误(超过100个)。

就像Daniel提到的,C中不存在结构的可选字段,这就是为什么MATLAB编码器会在代码中出错

要使此代码与MATLAB编码器一起工作,
opts
可以始终具有属性
y
,但要使其大小可变并初始化为空:

或者,您可以创建另一个选项变量
optsWithY
,该变量将包含字段
y
,即使
opts
没有:

甚至可以将其移动到帮助器函数中,并重新分配给
opts

此代码与原始代码之间的区别是部分赋值
opts.y=…
与完全赋值
opts=…


或者像Cris提到的那样,MATLAB编译器将更接近MATLAB(尽管您不会得到C代码)

没有其他方法可以翻译上述代码。带有可选组件的结构不能真正转换为C。另一种选择是MATLAB编译器,它不转换为C,但允许您在没有MATLAB的情况下运行代码。
function results = prog()
    opts.x = 1;
    opts.y = [];
    coder.varsize('opts.y');
    if isempty(opts.y); opts.y = 1; end
    'asdf'
end
function results = prog()
    opts.x = 1;
    optsWithY = opts;
    if ~isfield(opts, 'y'); optsWithY.y = 1; end
    'asdf'
end
function results = prog()
    opts.x = 1;
    opts = addOpt(opts, 'y', 1);
    'asdf'
end

function newOpts = addOpt(opts, field, defaultValue)
    newOpts = opts;
    if ~isfield(opts, field)
        newOpts.(field) = defaultValue;
    end
end