首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >变量名与matlab中数组中的数据相同

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

Stack Overflow用户
提问于 2015-08-06 20:45:08
回答 1查看 77关注 0票数 0

我有一个单元格数组中的数据。我希望单元格数组中的每一行都分配一个变量名,与该行第一列中的变量名相同。我能把这个循环起来吗?

代码语言:javascript
复制
'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,等等。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-07 16:04:47

给予:

代码语言:javascript
复制
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'};

使用循环如下所示:

代码语言:javascript
复制
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中一个奇怪的语法特性,该特性用于引用名称存储在变量中的字段。下面的例子

代码语言:javascript
复制
%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,它如下所示:

代码语言:javascript
复制
>> 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'}

这是"Use a structure“选项,如下所述:stackoverflow.com.com/q/15438464/931379。在这个问题的最上面的答案中至少有四个很好的选项(加上对如何使用变量名称来完成此操作的描述)。

总之,在Matlab中有很多存储命名数据的方法。使用这样的结构,在很多方面都是相当不错的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31865479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档