zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Matlab Tips: 结构体递归式打印--Dump matlab struct content recursively

MATLAB递归 -- 结构 打印 content dump Tips
2023-09-14 09:15:00 时间

    Matlab有一个内置命令disp可以在命令行窗口显示结构体(struct)内容,但是有两个缺点:(1)不能递归地展示,即对于多层嵌套结构体,只能显示第一层的内容,不能显示内层结构体的内容;(2)不能打印到文件中去。这个不能满足有些特定场合的需要,所以自己写了一个函数用于以递归的方式打印结构体内容的函数。

    

function printStruct(st, fid, indent)
%printStruct Print the content of input struct recursively
%Input:
%  st:     input struct
%  fid:    1 means print to console window
%  indent: indentation control   

if nargin == 1
    fid = 1; indent = 0;
elseif nargin == 2
    indent = 0;
end

% % For debug -- Begin
% st = struct;
% st('para1') = 1;
% st('para2') = 2;
% st('para3') = 'Hello world!';
% fid = 1;
% % For debug -- End

if ~isequal(class(st),'struct')
    fprintf(1,'Usage : printStruct(st, fid, indent), st must be a struct!');
    return;
end

allFields = fields(st);

indentStr = '';
for k = 1:indent
%if indent == 1
    tmpStr = sprintf('%20s','+');
    indentStr = strcat(indentStr,tmpStr);
end

for k = 1:1:length(allFields)        
    curField = char(allFields(k));
%     disp(curField)
%     disp(st(curField))
    
    if isa(getfield(st,curField),'struct')
        fprintf(fid, '%s%20s = [struct: ] \n',indentStr,curField);
        printStruct(getfield(st,curField),fid, indent+1);
    else
        if isnumeric(getfield(st,curField))
            a = getfield(st,curField);
            fprintf(fid, '%s%20s = ',indentStr,curField);
            for k = 1:min(numel(a),16)
                fprintf(fid, '%g ',a(k));
            end            
            if numel(a) > 16
                fprintf(fid, '...... ');
            end
            fprintf(fid, '\n');
        elseif ischar(getfield(st,curField))
            fprintf(fid, '%s%20s = %s\n',indentStr,curField,getfield(st,curField));
        else
        end
    end
end

以下给出两个调用例。

% Usage Example 1: Print to console window
t.a = 1;
t.b.b1 = 2;
t.b.b2 = 'abcde';
printStruct(t,1);

第2个参数设置为,表示打印到命令行窗口,执行后可以得到如下结果(作为对比,也给出了调用disp的结果):

                   a = 1 
                   b = [struct: ] 
                   +                  b1 = 2 
                   +                  b2 = abcde
>> disp(t)
    a: 1
    b: [1×1 struct]

% Usage Example 2: Print to a file. File must be open/close outside the
% function
myinfo.name = 'sillykidult';
myinfo.age  = 48;
myinfo.myson.name = 'fatcowboy';
myinfo.myson.age  = 12;
fid = fopen('myinfo.log','w');
printStruct(myinfo,fid);
fclose(fid);

执行后会生成一个叫myinfo.log的文件,其中内容如下所示:

                name = sillykidult
                 age = 48 
               myson = [struct: ] 
                   +                name = fatcowboy
                   +                 age = 12