变量名与matlab中数组中的数据相同

时间:2015-08-06 20:45:08

标签: arrays matlab variables

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

'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,依此类推。

1 个答案:

答案 0 :(得分:0)

假设:

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中存储命名数据。对于许多目的而言,使用像这样的结构是相当不错的结构。