Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Matlab中定义n个符号变量?_Matlab_Symbolic Math - Fatal编程技术网

如何在Matlab中定义n个符号变量?

如何在Matlab中定义n个符号变量?,matlab,symbolic-math,Matlab,Symbolic Math,我想在Matlab中定义n个符号变量。例如,如果用户输入n=3,则编译器将x1、x2、x3定义为符号变量(n的范围是无限的)。如何通过for循环来实现这一点?无需使用循环 N = input('How many variables? '); strArray = [ repmat('x',N,1) dec2base(1:N,10) repmat(' ',N,1)]; % create strings strArray = strvcat(regexprep(mat2cell(strArray,

我想在Matlab中定义n个符号变量。例如,如果用户输入
n=3
,则编译器将
x1
x2
x3
定义为符号变量(
n
的范围是无限的)。如何通过
for
循环来实现这一点?

无需使用循环

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)
例如,输入字符串“11”

syms x1  x2  x3  x4  x5  x6  x7  x8  x9  x10 x11 

它创建了11个符号变量,

我认为符号变量的建议与常规变量的建议相同:

for i = 1:10
    x = sprintf('x%d',i);
    assignin('caller',x,sym(x));
end
如果你能阻止它,不要创建编号的变量。使用向量代替

我自己无法尝试,但我相信
doc syms
将引导您实现以下目标:

A = sym('A',dim) %creates a vector or a matrix of symbolic variables.

如@DennisJaheruddin所示,创建一个向量确实是标准方法,但如果您确实需要单独的变量:

for i = 1:10
    x = sprintf('x%d',i);
    assignin('caller',x,sym(x));
end
或者这将在一行中完成:

arrayfun(@(n)assignin('caller',sprintf('x%d',n),sym(sprintf('x%d',n))),1:10)