如何将Matlab Mat文件中的变量保存到Mat文件中的各个结构中

时间:2014-02-25 20:57:16

标签: arrays matlab data-structures

我有一个包含来自不同测试用例的多个数据变量的matfile,例如matfile就是:

zzz.mat

其中的数据列为:

C1_jjj
C1_lll
C1_ggg

C2_jjj
C2_lll
C2_ggg

jjjlllggg代表变量名称,C1C2是不同的案例编号。

我想重写并保存matfile,以便将每个测试Case变量(C1和C2)分解为matfile中的自己的结构。因此matfile,zzz.mat现在会读取:

C1(structure)
C2(structure)

其中C1和C2包含每个测试的每个变量(jjj,lll,ggg)。

关于如何重组这个的任何想法?

1 个答案:

答案 0 :(得分:0)

你应该更进一步,使用一组结构。您的matfile将包含一个变量,C(1).jjj是一个引用变量的示例。
基本思想是将matfile作为结构加载(以获得简单的变量列表),然后使用动态字段引用将结构的形式转换为更易读的内容。

C = struct;

% Load MATFILE into a single structure containing all the variables.
S = load('zzz.mat');

% Loop over fields of S, which is the same as
%    variable names in the MATFILE
fn = fieldnames(S);
for ii = 1:length(fn)
    f = fn{ii};  % original variable name, C1_jjj for exammple

    % Extract case number and variable name from the string.
    % Edit this if your variable names are different from
    % the examples given
    tokens = regexp(f, 'C(\d+)_(\w+)', 'tokens');
    case_number = str2num(tokens{1}{1});
    var_name = tokens{1}{2};

    % Insert the value of the field into the new structure
    %   using dynamic fieldnames
    C(case_number).(var_name) = S.(f);
end
相关问题