Resolve Error: coder.varsize Not Supported for Strings - MATLAB & Simulink (original) (raw)
Main Content
Issue
Code generation does not support defining string variables as variable-size by using the coder.varsize directive. If you callcoder.varize
on a string variable, this error occurs during code generation:
coder.varsize() is not supported for variables of string type.
Possible Solutions
Consider this MATLABĀ® function, which returns a string. Code generation fails for this function because the code generator defines s
as a fixed-size string with length 0
and cannot increase the size of the string inside thefor
-loop. You cannot use coder.varsize
to define s
as variable size because s
is a string.
function out = varSizeStringError(n) s = ""; for i = 1:n s = s + ":) "; end out = s; end
Avoid Using Strings
If your application does not require strings, you can use a variable-size character row vector instead of a string. For example:
function out = varSizeStringExample1(n) s = ''; coder.varsize('s'); for i = 1:n s = append(s,':) '); end out = s; end
Convert Variable-Size Character Vectors to Strings
Because code generation supports defining variable-size character arrays using thecoder.varsize
directive, you can define a variable-length character row vector and then convert that vector to a string. For example:
function out = varSizeStringExample2(n) chars = ''; coder.varsize("chars"); s = convertCharsToStrings(chars); for i = 1:n s = s + ":) "; end out = s; end
Use string(blanks(coder.ignoreConst(0)))
to Construct an Empty Variable-Length String
You can use string(blanks(coder.ignoreConst(0)))
to instruct the code generator to create an empty, variable-length string in the generated code. You can then change the length of this string without explicitly defining the string as variable size. For example:
function out = varSizeStringExample3(n) s = string(blanks(coder.ignoreConst(0))); for i = 1:n s = s + ":) "; end out = s; end