I want to define n symbolic variables in Matlab. For example, if the user enters n=3
then compiler defines x1
, x2
, x3
as symbolic variables (the range of n
is unlimited). How can I do this by for
loop?
Asked
Active
Viewed 2,715 times
0

horchler
- 18,384
- 4
- 37
- 73

user2987710
- 11
- 1
- 4
3 Answers
1
I suppose the same advice holds for symbolic variables as for regular variables:
If you can prevent it, don't create numbered variables. Use a vector instead.
I cannot try it myself, but I believe doc syms
will lead you to this:
A = sym('A',dim) %creates a vector or a matrix of symbolic variables.

Dennis Jaheruddin
- 21,208
- 8
- 66
- 122
0
No need to use a loop.
N = input('How many variables? ');
strArray = [ repmat('x',N,1) dec2base(1:N,10) repmat(' ',N,1)]; % create strings
strArray = strvcat(regexprep(mat2cell(strArray, ...
ones(1,size(strArray,1)), size(strArray,2)),'x0+','x')).'; % remove heading 0's
str = ['syms ' strArray(:).']; % string to be avaluated
eval(str)
For example, inputing "11", the string
syms x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
is built and evaluated, which creates the 11 symbolic variables,

Luis Mendo
- 110,752
- 13
- 76
- 147
0
Creating a vector as @DennisJaheruddin shows is really the standard way, but if you really need separate variables:
for i = 1:10
x = sprintf('x%d',i);
assignin('caller',x,sym(x));
end
Or this will do it in one line:
arrayfun(@(n)assignin('caller',sprintf('x%d',n),sym(sprintf('x%d',n))),1:10)

horchler
- 18,384
- 4
- 37
- 73