首页 > 解决方案 > 使用字符串数组的值来命名变量(Matlab)

问题描述

我正在尝试将多个文件的结果组合到一个结构中。

所述结构应命名为以下名称:

result.[FileName1].Result1ofFile1
result.[FileName1].Result2ofFile1
result.[FileName2].Result1ofFile2
...
result.[FileNameX].ResultYofFileX

我将文件名保存在字符串数组中。因此

FileName(1) = "abc1"
FileName(2) = "abc2"
and so on

不幸的是,我不知道如何使它工作。

最后它应该是这样的,不需要自己输入 abc-Names:

result.abc1.Result1ofFile1
result.abc2.Result1ofFile2

如何使用存储在数组中的字符串作为变量名?

标签: arraysmatlabstructnaming

解决方案


您可以使用动态结构字段名称

>> result = struct;
>> FileName = 'test';
>> result.(FileName) = rand(10);
result = 
  struct with fields:

    test: [10×10 double]

或者当使用字符串数组时:

result = struct; 
for k = 1:numel(FileName)
    result.(FileName(k)) = rand(10);
end

推荐阅读