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 CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by