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

标签 matlab symbolic-math

定义符号向量

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

定义一个syms变量x

syms x

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

f(i) = x

给定任何k,那么我如何知道f(k)是否已分配?

最佳答案

简短回答

kf 条目的索引进行检查。然后

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

true (或 1 )如果 kf 条目已分配并 false (或 0 )否则。

长答案

来自documentation (添加黑体字)

A = sym('a',[m,n]) creates an m-by-n symbolic matrix filled with automatically generated elements. The generated elements do not appear in the MATLAB workspace.

例如,

>> 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

这确实表明 f1 , f2等不会出现在工作区中。但是,如果您随后分配

>> 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'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

因此,应用 ~isempty对此t产生true ( 1 ) 如果 kf 条目已分配并 false ( 0 ) 否则:

>> k = 2;
>> isAssigned = ~isempty(whos(char(f(k))))
isAssigned =
     0

>> k = 3;
>> isAssigned = ~isempty(whos(char(f(k))))
isAssigned =
     1

关于matlab - 我如何知道 syms 向量中的元素是否已分配 (MATLAB)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497737/

相关文章:

Matlab : how to know in which release a function was implemented?

string - 如何显示字符串中的每个单词?

python - SymPy:我可以安全地区分 atan2() 吗?

python - 矩阵和标量符号的混合

Matlab 将图形拟合为黑白图像

matlab - 在 MATLAB 中对矩阵进行排序时如何维护行?

latex - ``\nabla'' 符号错误地显示为黑色光盘

wolfram-mathematica - 从表达式中获取所有叶子

python - 使用 Python 和 Sympy 进行三角恒等式,tan(A/2) = (sin A )/(1 + cos A)

matlab - 使用 HMM Matlab 进行序列预测