Matlab Tips: 结构体递归式打印--Dump matlab struct content recursively
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
相关文章
- matlab 点云沿坐标轴进行等距切片
- 基于MATLAB的车牌识别系统设计(Matlab代码实现)
- 高压直流输电(HVDC)的最优潮流(OPF)(Matlab代码实现)
- 【无人机】采用NOMA的节能多无人机多接入边缘计算(Matlab代码实现)
- 模拟不同MIMO-OFDM方案的MATLAB代码(Matlab代码实现)
- 基于MATLAB中雷达和视觉合成数据的目标级传感器融合(Matlab代码实现)
- 【信号处理】基于优化算法的 SAR 信号处理(Matlab代码实现)
- 【MATLAB】图像基本运算(点运算、算术运算、缩放、旋转)
- 【MATLAB】求Taylor展开式
- 【MATLAB】matlab 文档使用 ( 文档查询 | 文档层次 | 自带搜索工具 | 帮助命令 | 学习导引 )
- 三车道交通流元胞自动机研究(matlab代码实现)
- Matlab使用笔记(三):matlab设置代码自动补全功能
- Matlab使用笔记(九):matlab实现交通流仿真/车感知/城市交通交叉路口
- Matlab使用笔记(七):将PreScan连接MATLAB实现仿真 (附录:自动无人驾驶仿真软件PreScan的应用介绍)