Can you explain this Embedded MATLAB Function erro

2020-04-16 08:21发布

问题:

I'm having a problem sending a value from a GUI to an Embedded MATLAB Function (EMF) in a Simulink model. I get this value from a slider in my GUI and send it to an EMF block in my model. I can confirm that the value is being transferred correctly from my GUI to my Simulink block, since I can display the value with a display block in my model and see the value change when I change the slider position in my GUI. However I keep getting this error when I run my model:

Could not determine the size of this expression.

Function 'Kastl' (#18.282.283), line 14, column 1:
"f"

This is part of my EMF block code:

function y = input_par(u,fstart)
  ...
  f_end = 1000;
  f = fstart:f_end; 
  ...

回答1:

I believe MikeT is correct: you can't redefine the size of a variable in an embedded function. If you look at this Embedded MATLAB Function documentation page under the subsection Defining Local Variables, it says:

Once you define a variable, you cannot redefine it to any other type or size in the function body.

You will have to rework your embedded function such that the variables you declare are not changing size. Since I don't know what you are subsequently doing with the variable f, there's not much more specific help I can give you.

In general, if you absolutely need to use data that changes size, one solution is to pad the data with "garbage" values in order to maintain a constant size. For example:

MAX_ELEMS = 1000;  % Define the maximum number of elements in the vector
f = [fstart:MAX_ELEMS nan(1,fstart-1)];  % Create vector and pad with NaNs

In the above example, the variable f will always have 1000 elements (assuming the value of fstart is an integer value less than or equal to 1000). The value NaN is used to pad the vector to the appropriate constant size. Any subsequent code would have to be able to recognize that a value of NaN should be ignored. Depending on what calculations are subsequently done in the embedded function, different pad values might be needed in place of NaN (such as 0, negative values, etc.).



回答2:

I believe the issue you are running into is that you can't change a parameter during simulation that will cause the dimension of a signal to change. In your example, the code,

f = fstart:f_end;

changes size whenever fstart changes. I think this is what EMF block is complaining about. I don't have any easy workaround for this particular issue, but maybe there's an equivalent way of doing what you want that avoids this issue.