【问题标题】:Variable name the same as data in array in matlab变量名与matlab中数组中的数据相同
【发布时间】:2015-08-06 20:45:08
【问题描述】:

我有一个单元格数组中的数据。我希望为元胞数组中的每一行分配一个变量名称,该名称与该行第一列中的变量名称相同。我可以循环使用它吗?

'P' 'El'    'Ge'    'R' 'M'  'RANGE'
'A' 'El'    'Ge'    'T' 'M'  'RANGE' 
'B' 'El'    'Ge'    'K' 'M'  'RANGE' 
'D' 'El'    'Ge'    'M' 'NM' 'RANGE'

例如,我希望这个数组的第一行有一个变量名 P,第二行一个变量名 A,第三行一个变量名 B,依此类推。

【问题讨论】:

  • 这需要大量的assignin(甚至更糟eval)。推荐Generate Field Names from Variables,或者使用元胞数组,但已经有了。
  • 每次有人使用eval,上帝就是在杀死一只小猫。不开玩笑,@Hoki 完全正确
  • 有没有其他方法可以做到这一点。我在第一列中有任何内容作为我的 GUI 下拉菜单的一部分。所以我想知道我是否可以有同名的变量。
  • 有人可以向我解释一下为什么这样做会是一件好事吗?
  • 相关:stackoverflow.com/q/15438464/931379。我认为这里更普遍的问题是“我应该如何在 Matlab 中存储命名数据”。

标签: arrays matlab variables


【解决方案1】:

给定:

dataCell = {...
    'P' 'El'    'Ge'    'R' 'M'  'RANGE'; ...
    'A' 'El'    'Ge'    'T' 'M'  'RANGE'; ... 
    'B' 'El'    'Ge'    'K' 'M'  'RANGE'; ...
    'D' 'El'    'Ge'    'M' 'NM' 'RANGE'};

使用循环看起来像这样:

for ix = 1:size(dataCell ,1)
    curFieldName = dataCell{ix, 1};
    curData = dataCell(ix, 2:end);  %You can put other data here
    data.(curFieldName) = curData;  %Note the ".()' notation
end

这利用了 Matlab 中一个奇怪的语法特性,该特性用于引用名称存储在变量中的字段。下面的例子

%If you know the name of a field when you are writing the code, 
%use this syntax
someStructure.field1 = 1;

%If you want the name of the filed to be generated dynamically, when 
%the code is executed, use this syntax (note parenthesis). 
theFieldNameInAVariable = 'field1';
someStructure.(theFieldNameInAVariable ) = 1

这导致结构 data,如下所示:

>> data
data = 
    P: {'El'  'Ge'  'R'  'M'  'RANGE'}
    A: {'El'  'Ge'  'T'  'M'  'RANGE'}
    B: {'El'  'Ge'  'K'  'M'  'RANGE'}
    D: {'El'  'Ge'  'M'  'NM'  'RANGE'}

这是“使用结构”选项,如下所述:stackoverflow.com/q/15438464/931379。该问题的最佳答案中至少有四个不错的选择(以及如何使用变量名执行此操作的说明。)

底线,有很多方法可以在 Matlab 中存储命名数据。使用这样的结构对于许多目的来说都是相当不错的。

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多