如何保存一个结构数组到一个文本文件 [英] How to save a structure array to a text file

查看:189
本文介绍了如何保存一个结构数组到一个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MATLAB我怎么一个结构数组保存到一个文本文件中,以便它显示的一切结构数组显示在命令窗口?

In MATLAB how do I save a structure array to a text file so that it displays everything the structure array shows in the command window?

推荐答案

您必须首先定义为您的文件的格式。

You have to define a format for your file first.

如果你不关心格式,只是希望能够在以后的时间来加载数据,使用的 保存 ,例如:

If you don't care about the format, and simply want to be able to load the data at a later time, use save, for example:

save 'myfile.mat' structarr

存储阵列结构 structarr 二进制文件MAT名为file.mat。要阅读它放回你的工作空间,您可以使用 负荷

That stores struct array structarr in a binary MAT file named "file.mat". To read it back into your workspace you can use load:

load 'myfile.mat'

另存为逗号分隔值(.csv)

如果你想保存你的结构数组中的一个文本文件作为逗号分隔值对,其中每对包含字段名称和它的价值,你可以沿着这些路线的内容:

Saving as comma-separated values (.CSV)

If you want to save your struct array in a text file as comma-separated value pairs, where each pair contains the field name and its value, you can something along these lines:

%// Extract field data
fields = repmat(fieldnames(structarr), numel(structarr), 1);
values = struct2cell(structarr);

%// Convert all numerical values to strings
idx = cellfun(@isnumeric, values); 
values(idx) = cellfun(@num2str, values(idx), 'UniformOutput', 0);

%// Combine field names and values in the same array
C = {fields{:}; values{:}};

%// Write fields to CSV file
fid = fopen('myfile.csv', 'wt');
fmt_str = repmat('%s,', 1, size(C, 2));
fprintf(fid, [fmt_str(1:end - 1), '\n'], C{:});
fclose(fid);

该解决方案假定每个字段包含一个标值或字符串,但您认为合适的,当然你也可以扩展它。

This solution assumes that each field contains a scalar value or a string, but you can extend it as you see fit, of course.

这篇关于如何保存一个结构数组到一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆