matlabfunctionsimulink

handing string to MATLAB function in Simulink


In my Simulink Model I have a MATLAB function, this_function, which uses as one parameter the name of the Simulink Model, modelname. The name is defined in an extra parameter file with all other parameters needed. Loading the parameter file loads modelname into the workspace. The problem is now, that this_function can't access modelname in the workspace and therefore the model doesn't run.

I tried to use modelname as a constant input source for this_function, which I used as a work-around previously, but Simulink doesn't accept chars/strings as signals. Furthermore does setting modelname to global not work as well.

Is there a way to keep modelname in the parameter file instead of writing it directly into this_function?


Solution

  • Simulink does not support strings. Like, anywhere. It really sucks and I don't know why this limitation exists - it seems like a pretty horrible design choice to me.

    I've found the following workarounds for this limitation:

    Dirty Casting

    Let

    function yourFun(num_param1, num_param2, ..., str_param);
    

    be your MATLAB function inside the Simulink block, with str_param the parameter you want to be a string, and num_param[X] any other parameters. Then pass the string signal to the function like so:

    yourFun(3, [4 5], ..., 'the_string'+0);
    

    Note that '+0' at the end; that is shorthand for casting a string to an array of integers, corresponding to the ASCII codes of each character in the string. Then, inside the function, you could get the string back by doing the inverse:

    model = char(str_param);
    

    but usually that results in problems later on (strcmp not supported, upper/lower not supported, etc.). So, you could do string comparisons (and similar operations) in a similar fashion:

    isequal(str_param, 'comparison'+0);
    

    This has all the benefits of strings, without actually using strings.

    Of course, the '+0' trick can be used inside constant blocks as well, model callbacks to convert workspace variables on preLoad, etc.

    Note that support for variable size arrays must be enabled in the MATLAB function.

    Fixed Option Set

    Instead of passing in a string, you can pass a numeric scalar, which corresponds to a selection in a list of fixed, hardcoded options:

    function yourFun(..., option)
    
        ...
    
        switch (option)
            case 1 
                model = 'model_idealised';
            case 2
                model = 'model_with_drag';
            case 3
                model = 'model_fullscale';
            otherwise
                error('Invalid option.');
        end
    
        ...
    
    end
    

    Both alternatives are not ideal, both are contrived, and both are prone to error and/or have reusability and scalability problems. It's pretty hopeless.

    Simulink should start supporting strings natively, I mean, come on.