Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

loading txt files into matlab structure

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?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...