1

Consider the following matlab program:

function results = prog()
    opts.x = 1;
    if ~isfield(opts, 'y'); opts.y = 1; end
    'asdf'
return

I am able to run this program successfully in matlab however when I try to use coder to convert it to C I get the following error:

This structure does not have a field 'y'; new fields cannot be added when structure has been read or used.

I would like to know if there is a way to convert to C using coder (or possible some other tool) that does not use a stricter compiler as seems to be the case with coder as I am using it. I am using matlab version R2019B.

Please note that this is just one of many examples of how coder is using a stricter compiler than normal matlab. I have a fairly large program that I would like to convert to C and I don't want to have to go through each error (there are over 100).

2
  • 1
    There is no alternative which could translate above code. Structs with optional components are something you can't really translate to C. Commented Nov 10, 2019 at 8:13
  • 2
    The other alternative is the MATLAB Compiler, which doesn’t translate to C but allows you to run your code without having MATLAB. Commented Nov 10, 2019 at 14:56

1 Answer 1

2

Like Daniel mentioned, optional fields of structs don't exist in C, which is why MATLAB Coder errors on that code.

To make this code work with MATLAB Coder, opts could always have property y, but make it variable-sized and initialized to empty:

function results = prog()
    opts.x = 1;
    opts.y = [];
    coder.varsize('opts.y');
    if isempty(opts.y); opts.y = 1; end
    'asdf'
end

Or you could create another options variable optsWithY that will have field y, even if opts doesn't:

function results = prog()
    opts.x = 1;
    optsWithY = opts;
    if ~isfield(opts, 'y'); optsWithY.y = 1; end
    'asdf'
end

This could even be moved into a helper function and assigned back to opts:

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

The difference between this and the original code is partial assignment opts.y = ... vs complete assignment opts = ....

Or like Cris mentioned, MATLAB Compiler will be a lot closer to MATLAB (though you won't get C code)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.