Is it possible to use zero padding in the variable names when creating a symbolic array of automatically generated elements.

4 次查看(过去 30 天)
I am currently trying to implement an algorithm that generates and solves a set of polynomial equations. I generally need to create R symbolic variables for the polynomials .I wanted to use the sym('a',n) functionality for this. For example:
x_var_list = sym('x%d',[1 R])
Since R can sometimes be 10 or higher, I wanted to introduce zero padding, such that the variables will usually be displayed in sorted order, when printing.
n_digits_R = num2str(ceil(log10(abs(R))))
x_var_list = sym(strcat('x%0',n_digits_R,'d'),[1 R])
This code snippet, however, yields the following error message:
Error using sym>createCharMatrix (line 1561)
If the second argument specifies the dimensions of the generated symbolic vector or matrix, then the first argument must be a character vector specifying the base name for vector or matrix elements. It must be a valid variable name.
Is padding generally incompatible with the sym function?
  2 个评论
Vinai Datta Thatiparthi
Hey Armin,
Is there any specific reason why you use "%0"?
Instead,
sym(strcat('x0',n_digits_R,'d'),[1 R])
% Does this fetch the expected results?
Also, could you mention what are the expected output variable names?
Armin Römer
Armin Römer 2020-9-17
Hello Vinai Datta,
it still throws the same error as posted in the original question. I am using % according to the documentation:
It says there:
Format the names of elements of a by using a format character vector as the first argument. sym replaces %d in the format character vector with the index of the element to generate the element names.
a = sym('x_%d',[1 4])
The output then is
a =
[x_1, x_2, x_3, x_4]
I would like to be able to use zero padding in the variable names. For example. Say that I need to create 10 variables. Then I would like to create the 10 symbolic variables in the following way:
x_01, x_02, x_03, x_04, x_05, x_06, x_07, x_08, x_09, x_10,
Currently I have to use explicit loops and use the eval function. It would just be nice to get the same result in one line of code.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2020-9-17
编辑:Walter Roberson 2020-9-17
No, the code checks that what you pass in is a variable name itself, and if not then it deletes all '%d' and tries again to see if the result is a variable name. There is no possibility in the code for anything other than '%d'
To get around this problem,
syms(compose("x_%02d", 1:R))
or similar variations like
a = sym(compose("x_%02d", 1:R))

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Formula Manipulation and Simplification 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by