Scalar variable as output of Matlab function in Simulink
20 次查看(过去 30 天)
显示 更早的评论
I careted a Simulink model in MATLAB 2017 for debug. The model includes only a MATLAB function. It is shown in the image below;
The code in the MATLAB function looks like below:
function y = fcn(time,stateVariables)
ii = find(stateVariables(:,1)<=time,1,'last');
if isempty(ii)
ii = 1;
end
y = ii
end
The stateVariables was loaded in the base workspace, as a parameter of the function. The first column is the time.
stateVarables = [0 10;
1 20;
2 40;
3 50;];
When run the Simulink model, it showed the following error: " Data 'y' is inferred as a variable size matrix, while its properties in the Model Explorer specify its size as inherited or fixed. Please check the 'Variable Size' check box and specify the upper bounds in the size field."
Then I checked "Variable Size" box and put 1 in "Size" textbox. I got another error: "Size computation for 'y' (#831) failed. MATLAB Function Block and Stateflow do not support Variable Sizes for scalar signals."
Then I unchecked "Variable Size" box, and reset -1 in "Size textbox". Then I changed the code as following:
function y = fcn(time,stateVariables)
ii = find(stateVariables(:,1)<=time,1,'last');
if isempty(ii)
ii = 1;
end
y = reshape([ii 0],[2,1]);
end
And it works. But this is not what I want. In this case, I have to add additional column to the output.
My question is: how to get a scalar variable as output of the MATLAB function?
0 个评论
采纳的回答
Fangjun Jiang
2023-2-16
编辑:Fangjun Jiang
2023-2-16
In your code, you use the find() function. It could return zero, one or more results. That is why the inital error message says "Data 'y' is inferred as a variable size matrix". The error that followed is caused by the "not-so-good-workaround" solution.
Even though you had the find(...,1,'last') option and further if-statement to guarantee the output y is a scalar, I guess MATLAB is not "smart" enough to recognize this. You could contact Mathworks tech support to see what they say about this.
A good workaround I have proved to work is this. Set everything back to the orignal default, add a line "ii=ii(1);" before the "y=ii;" line. It runs without any error.
2 个评论
Fangjun Jiang
2023-2-16
Yes. It seems that way. The algorithm to "infer" the variable size is not smart enough.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!