如何知道syms向量中的元素是否已分配(MATLAB)?

时间:2015-07-19 03:31:30

标签: matlab symbolic-math

定义syms矢量

f = sym('f', [1 100]);

定义syms变量x

syms x

可以访问和分配向量f中的元素,例如,

f(i) = x

鉴于k,我怎么知道是否分配了f(k)

1 个答案:

答案 0 :(得分:3)

简短回答

k成为要检查的f条目的索引。然后

isAssigned = ~isempty(whos(char(f(k))));

true(或1k条目f已分配且false(或0)否则。

答案很长

来自documentation(加粗体字)

  

A = sym('a',[m,n])创建一个m - by - n符号矩阵,其中包含自动生成的元素。 生成的元素不会出现在MATLAB工作区

例如,

>> clear all
>> f = sym('f', [1 10])
>> f =
[ f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]
>> whos
  Name      Size            Bytes  Class    Attributes

  f         1x10              112  sym

确实表明f1f2等不会出现在工作区中。但是,如果您再分配

>> syms x;
>> f(3) = x
f =
[ f1, f2, x, f4, f5, f6, f7, f8, f9, f10]

变量x当然会出现在工作区中:

>> whos
  Name      Size            Bytes  Class    Attributes

  f         1x10              112  sym                
  x         1x1               112  sym   

因此,检查是否已分配f的特定条目的方法是使用whos的函数形式检查其在工作区中的存在。比较

>> whos('f2') %// produces no output because no variable f2 exists in the workspace

>> whos('x') %// produces output because variable x exists in the workspace
  Name      Size            Bytes  Class    Attributes

  x         1x1               112  sym                

给定要检查的k条目的索引f,您可以使用{自动生成上例中的相应字符串('f2''x') {1}}:

char(f(k))

仅将>> k = 2; >> char(f(k)) ans = f2 >> k = 3; >> char(f(k)) ans = x 的输出分配给变量,如果尚未分配whos(char(f(k))),则该变量为空;如果已分配,则为非空:

f(k)

因此,如果已分配>> k = 2; >> t = whos(char(f(k))) t = 0x1 struct array with fields: name size bytes class global sparse complex nesting persistent >> k = 3; >> t = whos(char(f(k))) t = name: 'x' size: [1 1] bytes: 112 class: 'sym' global: 0 sparse: 0 complex: 0 nesting: [1x1 struct] persistent: 0 的{​​{1}}条目,则将~isempty应用于此t会产生true1)和kf)否则:

false