Search code examples
matlabparameterssimulinks-function

Passing a structure of parameters to a Level 1 m-code S-function in Simulink


I am trying to pass a structure of parameters to an S-function in MATLAB. I have a bunch of parameters and I would like to avoid passing them like this:

% The general form of an MATLAB S-function syntax is: % [SYS,X0,STR,TS,SIMSTATECOMPLIANCE] = SFUNC(T,X,U,FLAG,P1,...,Pn)

I would prefer passing a single structure that includes all of my parameters. I loaded the data into the Model Workspace as: enter image description here

First I tried ( in response to Phil):

function [sys,x0,str,ts,simStateCompliance]=system1(t,x,u,flag,DATA_HMMWV)

sizes.NumInputs = 2;

also,

with the Simulink looking like:

But I get this error:

enter image description here

Phil, this is why I tried to add another input port to the S-Function, I thought that it had to go in there.

I also tried: sizes.NumInputs = 1;

and I get this error: enter image description here

Also, are you sure that the DATA_HMMWV is a parameter? It looks slightly different than a Param in this window: enter image description here

NEW:::: 1/25/2016

Phil, the issue is not with my derivative function, the issue is that I am still not passing the structure into the function. Here is a picture. Notice the data is in the Model Workspace and I passed it (DATA_HMMWV) to the function, but when I stop the simulation at line 13 (debugging mode), DATA_HMMWV is not in the function workspace.

enter image description here

If the code continues ( to flag = 1) we get: enter image description here

If the code continues to run, it crashes with this error: enter image description here

So, there were not enough input arguments passed to the function. Also, the function is very simple:

% function sys = mdlDerivatives(t,x,u,DATA_HMMWV)

sys = DATA_HMMWV.g;

% end mdlDerivatives

It just tries to grab a parameter from the structure.


Solution

  • Setup 1: Load the data as a structure into the base workspace and run the simulink model

    clear;
    clc;
    close all
    PlantName = 'untitled';
    open(PlantName)
    TFinal          = 10;
    load DATA_HMMWV.mat
    sim(PlantName, TFinal)
    

    Setup 2: level 1 S-function that is being called in simulink

    Setup 3: When you double click on this model, specify the structure that you would like to pass to the S-function as: enter image description here

    Setup 4: your functions should also have the structure in it:

    function [sys,x0,str,ts,simStateCompliance]=system1(t,x,u,flag,DATA_HMMWV)
    

    and any other functions that you need the structure in, for example:

      case 1
    sys = mdlDerivatives(t,x,u,DATA_HMMWV);
    

    then,

    function sys = mdlDerivatives(t,x,u,DATA_HMMWV)
    

    Now, you have passed a strucure to level-1 S-function!