定义syms矢量
f = sym('f', [1 100]);
定义syms变量x
syms x
可以访问和分配向量f
中的元素,例如,
f(i) = x
鉴于k
,我怎么知道是否分配了f(k)
?
答案 0 :(得分:3)
让k
成为要检查的f
条目的索引。然后
isAssigned = ~isempty(whos(char(f(k))));
true
(或1
)k
条目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
确实表明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'
) {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
会产生true
(1
)和k
(f
)否则:
false