Import name/value parameters from a text file to a struct (or cell array)

1 回表示 (過去 30 日間)
J G
J G 2020 年 6 月 15 日
コメント済み: J G 2020 年 6 月 15 日
Hi,
Matlab has all sorts of sophisticated functionality for importing datasets stored in text files, with plenty of options to control input behavior, variable names, replacement options, etc. etc.
What I am looking to do seems to need some of this functionality, but is fairly simple, and what I have found so far seems to be overkill, or doesn't work well. Can someone advise a better way?
Goal: Take a simple name/value list of parameters in a text file and write to a struct (preferred) or cell array, with datatypes appropriately converted and variable names stored as fields.
Example:
Input
myParamFile.txt:
dt .01
x0 0
y0 0
flag1 false
flag2 true
inputArray [1 0 0; 0 1 0; 0 0 1]
jobname 'myjob'
Output:
myStruct =
struct with fields:
dt: 0.0100
x0: 0
y0: 0
flag1: 0
flag2: 1
inputArray: [3×3 double]
jobname: 'myjob'
The point here is that whatever process/function that converts the input to the output will recognize the datatype and convert it appropriately, ideally creating struct fields based on the variable names in the textfile.
I could certainly build a custom parser to do this, but it seems that there is enough built-in Matlab functionality designed to work with text data I am curious if there is an existing and/or simpler way.
Thanks!

採用された回答

Stephen23
Stephen23 2020 年 6 月 15 日
編集済み: Stephen23 2020 年 6 月 15 日
As far as I am aware there isn't anything inbuilt. But you can do something like this:
>> str = fileread('myparamfile.txt');
>> tkn = regexp(str,'(\S+)\s+([^\r\n]*)','tokens');
>> tkn = vertcat(tkn{:}).';
>> [num,idx] = cellfun(@str2num,tkn(2,:),'uni',0);
>> idx = [idx{:}];
>> tkn(2,idx) = num(idx);
>> out = struct(tkn{:})
out =
dt: 0.01
x0: 0
y0: 0
flag1: 0
flag2: 1
inputArray: [3x3 double]
jobname: ''myjob''

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by