我有一个单元格数组中的数据。我希望单元格数组中的每一行都分配一个变量名,与该行第一列中的变量名相同。我能把这个循环起来吗?
'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,等等。
发布于 2015-08-07 16:04:47
给予:
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'}这是"Use a structure“选项,如下所述:stackoverflow.com.com/q/15438464/931379。在这个问题的最上面的答案中至少有四个很好的选项(加上对如何使用变量名称来完成此操作的描述)。
总之,在Matlab中有很多存储命名数据的方法。使用这样的结构,在很多方面都是相当不错的。
https://stackoverflow.com/questions/31865479
复制相似问题