loading txt files into matlab structure

2019-09-07 23:22发布

问题:

I have a txt file below as shown in the attached figure:

a 0.15
ne 1e25
density 200
pulse_num 2

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)

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?

回答1:

This can be done using:

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

Read the documentation of fopen, textscan, fclose, cellfun and cell2struct for details.