Matlab 如何直接从table.Properties.VariableNames获取逗号分隔的列表?
例如:Matlab 如何直接从table.Properties.VariableNames获取逗号分隔的列表?,matlab,Matlab,例如: >> A = table({}, {}, {}, {}, {}, ... 'VariableNames', {'Foo', 'Bar', 'Baz', 'Frobozz', 'Quux'}); >> vn = A.Properties.VariableNames; >> isequal(vn, A.Properties.VariableNames) ans = 1 到目前为止还不错,但即使vn和A.Properties.
>> A = table({}, {}, {}, {}, {}, ...
'VariableNames', {'Foo', 'Bar', 'Baz', 'Frobozz', 'Quux'});
>> vn = A.Properties.VariableNames;
>> isequal(vn, A.Properties.VariableNames)
ans =
1
到目前为止还不错,但即使vn
和A.Properties.VariableNames
看起来是一样的,但当人们试图从它们那里获取“逗号分隔列表”(使用{:}
)时,它们的行为非常不同:
有没有办法直接从a.Properties.VariableNames获取“逗号分隔列表”(也就是说,不必创建像vn
这样的中间变量)
(还有,是否有比isequal
更可靠的函数来测试单元阵列的相等性?在上面的示例中vn
和a.Properties.VariableNames
显然不够相等!)
对于那些没有支持(相当新的)
表
对象的MATLAB版本的人来说,如果使用数据集
对象(来自统计工具箱),情况也是一样的。然后,上述示例将转换为:
clear('A', 'vn');
A = dataset({}, {}, {}, {}, {}, ...
'VarNames', {'Foo', 'Bar', 'Baz', 'Frobozz', 'Quux'});
vn = A.Properties.VarNames;
isequal(vn, A.Properties.VarNames)
{'Frobnitz', vn{:}}
{'Frobnitz', A.Properties.VarNames{:}}
(注意从
VariableNames
到VarNames
的更改;省略输出:它与上面显示的输出相同):isequal没有问题vn
和A.Properties.VariableNames
实际上是相等的。问题是别的
如果您键入帮助数据集.subsref
,您将得到一个关于为什么会发生这种情况的解释,该解释应与表
类的解释相同:
限制:
Subscripting expressions such as A.CellVar{1:2}, A.StructVar(1:2).field,
or A.Properties.ObsNames{1:2} are valid, but result in subsref
returning multiple outputs in the form of a comma-separated list. If
you explicitly assign to output arguments on the LHS of an assignment,
for example, [cellval1,cellval2] = A.CellVar{1:2}, those variables will
receive the corresponding values. However, if there are no output
arguments, only the first output in the comma-separated list is
returned.
简言之,当您调用行A.Properties.VarNames{:}
时,您正在调用dataset.subsref
方法,并且花括号下标{:}
正与其他下标一起传递给它,而不是在调用dataset.subsref
方法后单独应用
因此,看起来不可能不使用中间变量就直接从a
获取逗号分隔的列表。但是,如果您的目标(如示例中所示)是将字符串与另一个字符串连接到一个新的单元格数组中,则可以执行以下操作:
>> [{'Frobnitz'} A.Properties.VarNames]
ans =
'Frobnitz' 'Foo' 'Bar' 'Baz' 'Frobozz' 'Quux'
不,我认为除了创建临时变量vn之外,您什么都做不了。长期以来,用户定义类的一个令人不安的缺点是它们不能进行逗号分隔的列表扩展。不过,我确实觉得奇怪,TMW选择在用户定义的类框架中实现表类
至于isequal
,没有问题。您看到的行为与vn和A.Properties.VariableNames不相等无关
>> [{'Frobnitz'} A.Properties.VarNames]
ans =
'Frobnitz' 'Foo' 'Bar' 'Baz' 'Frobozz' 'Quux'