Scalar variable as output of Matlab function in Simulink
18 ビュー (過去 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;
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1297755/image.png)
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!