Setting a class object property of type string class in a Coder project

22 ビュー (過去 30 日間)
AJ
AJ 2023 年 10 月 20 日
コメント済み: AJ 2023 年 11 月 26 日
I'm generally please with MATLAB's support for classes in Coder. But I am running into an issue I don't know how to solve.
The target function being compiled has an argument that is a class object. That class object has a property of string class:
tag(1,1) string
That property is being modified in the target function:
myObj.tag = "xyzzy";
The error I get is:
??? Size mismatch (size [1 x 0] ~= size [1 x :?]) in field 'Value'.
Mismatched varying and fixed sizes indicate a probable run-time error. If this diagnostic is incorrect, use indexing to explicitly make the varying size fixed.
I believe this stems from the fact that the tag property is not of type coder.StringType (and thus is "fixed-length") and I can't specify the VariableStringLength and StringLength properties.
The Coder error report isn't much help here -- The tooltip for relevant variables, unfortunately, does not show all the metadata associated with a variable (but I wish it would).
I figured I'd post here before I contact tech support.

採用された回答

Yash Sharma
Yash Sharma 2023 年 11 月 23 日
I understand that you have a property of string type and wants to change the length of the property using object of the class. When you define a property as a string, MATLAB Coder treats it as a fixed-size string, which means it expects the string to always have the same length. When you try to assign a new value to the string property that has a different length than the original, MATLAB Coder throws an error because it cannot handle the change in size at runtime.
To work around this limitation, you can use “coder.varsize” to specify that the string property can vary in size.
Here's an example of how to define a class that uses “coder.varsize” to allow for a variable-size string property:
classdef MyClass
properties
% Pre-initialize the string with a fixed maximum length
tag;
end
methods
function obj = MyClass()
% Enable variable-sizing for the 'tag' property
coder.varsize('obj.tag', [1, 50]);
end
end
end
Now you can modify the tag variable as follows
obj = MyClass;
obj.tag = xyzzy
Please look at the below documentation that can be helpful for your implementation:
Hope this helps!
  1 件のコメント
AJ
AJ 2023 年 11 月 26 日
Thank you for the response.
I notice that the tag property is being declared without a size or data type. If I do this, it works. Else I get:
Code generation does not support string arrays. Use a cell array of character vectors.
This seems like a very awkword implementation, and I hope Mathworks implements a better approach. But I accept the solution as workable. Thank you.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB Coder についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by