将txt文件加载到matlab结构中 [英] loading txt files into matlab structure
问题描述
我下面有一个txt文件,如下图所示:
I have a txt file below as shown in the attached figure:
a 0.15
ne 1e25
density 200
pulse_num 2
有n行,每行2个数据.第一个数据是包含字段名称的字符串,第二个数据包含值.这两个数据之间用空格隔开.如何将这个txt文件加载到matlab结构中?基本上我想要这样的东西:
Is has n rows, 2 data on each row. The first data is a sting that contains the field name, and the second data contains the value. The two data is separated by a space. How do I load this txt file into a matlab structure? Basically I want something like:
whatIwant = struct('a', 0.15, 'ne', 1e25, 'density', 200, 'pulse_num', 2)
我只知道如何将其加载到表中(使用readtable
),并且可以将表转换为单元格,然后转换为结构.问题是我不知道如何追加结构.我不想在代码中输入字段名称,因此,如果更改字段名称(或不知道字段名称),则最终结构将具有适当的字段名称.
I only know how to load it to a table (using readtable
), and I can convert the table to a cell, then to a structure. Problem is that I don't know how to append a structure. I don't want to input the field names in my code, so if I change the field names (or don't know the field names) the final structure will have the appropriate field names.
还是有其他简单的方法可以直接加载它?
Or are there other simple ways to load it directly?
推荐答案
这可以使用:
fid = fopen('info.txt'); %Opening the text file
C = textscan(fid, '%s%s'); %Reading data
fclose(fid); %Closing the text file
%Converting numeric data stored as strings in a cell to numeric data using cellfun
s=cell2struct(cellfun(@str2double,C{2},'un',0),C{1},1); %Converting into a structure array
阅读> fopen
, textscan
, fclose
, cellfun
和
Read the documentation of fopen
, textscan
, fclose
, cellfun
and cell2struct
for details.
这篇关于将txt文件加载到matlab结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!