Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...