How can i read different data types (strings numbers vectors) from one .txt-File?

5 views (last 30 days)
At the moment i am using a .txt - File for my data input. (Only numbers with 3 columns)
In this .txt-file I want also store all the relevant formating data for my diagram. -> see attachment file. So i can use this parameters in my matlab code. How can i read them?
This was my old matlab code just with my Data Input:
Input_Matrix = textread('InputXX.txt')
x = Input_Matrix(:,1)
y = Input_Matrix(:,2)
z = Input_Matrix(:,3)
Thank you guys. Sincelery Philipp

Sign in to comment.

Accepted Answer

Guillaume on 8 Nov 2016
As per my comment you could use an xml file and xmlread or a json file and jsondecode (the latter being a lot less verbose) but it means a substantial change of syntax for your input file.
It's not that complicated to write a parser for your current format. This would work (although lacking a lot of syntax validation):
diagramoptions = [];
diagramlimits = [];
inputdata = [];
wholecontent = fileread('InputXX.txt');
sections = regexp(wholecontent, '\**([^*]*)\**([^*]*)', 'tokens');
for section = sections
case 'Diagram Options'
keyvalues = regexp(section{1}{2}, '([^\n\r=]*)=([^\n\r=]*)', 'tokens');
diagramoptions = cell2table(vertcat(keyvalues{:}), 'VariableNames', {'Key', 'Value'});
case 'Diagram Limits'
header = strsplit(regexp(section{1}{2}, '[^\n\r]*', 'match', 'once'));
content = textscan(section{1}{2}, repmat('%f', 1, numel(header)), 'HeaderLines', 2);
diagramlimits = table(content{:}, 'VariableNames', header);
case 'Input Data'
inputdata = cell2mat(textscan(section{1}{2}, '%f%f%f', 'HeaderLines', 1));
warning('Unknown section: %s', section{1}{1});
%see the outputs
openvar diagramoptions
openvar diagramlimits
openvar inputdata
Guillaume on 16 Nov 2016
The simplest way would be to append to diagramoptions, diagramlimits, inputdata every time you encounter a new one. It's easily done by replacing the assignment with
diagramoptions{end+1} = cell2table(... %same for the other two
You can then index each section using cell array indexing:
openvar diagramoptions{1}

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!