Importing and Organizing Text File Data

3 views (last 30 days)
Hello,
I have a text file from an experiment, and I would like to be able to import the numerical data as well as the strings for every listed variable (Start Date, End Date, A, B, etc...). Some of the data are strings, some are a single numerical values, and some are large matrices. I have tried uiimport and importdata, but due to the format of the text file it does not import as sperate string and data arrays. Instead, it is usually a large char array if I can even import anything at all. Any assistance on code that could import and organize my text file for me to be able to do analysis would be apprecaited. I have attatched an exmaple of the text files I am dealing with. Thanks.

Accepted Answer

Stephen23
Stephen23 on 20 Oct 2020
Edited: Stephen23 on 20 Oct 2020
This efficiently reads all of the file data into one structure.
[fid,msg] = fopen('Example_File.txt','rt');
assert(fid>=3,msg)
out = struct();
while ~feof(fid)
pos = ftell(fid);
str = fgetl(fid);
str = strtrim(str);
if numel(str) % ignore blank lines
spl = regexp(str,':','once','split');
spl = strtrim(spl);
if isnan(str2double(spl{1}))
fnm = strrep(spl{1},' ','');
val = str2double(spl{2});
if isnan(val) % string
out.(fnm) = spl{2};
else % numeric scalar
out.(fnm) = val;
end
else % numeric matrix (converted to vector)
fseek(fid,pos,'bof');
vec = fscanf(fid,'%*d:%f%f%f%f%f',[1,Inf]);
out.(fnm) = vec;
end
end
end
fclose(fid);
Giving:
>> out
out =
StartDate: '08/26/20'
EndDate: '08/26/20'
Subject: 1
Experiment: 'RIRR ETOH'
Group: ''
Box: 1
StartTime: '11:01:16'
EndTime: '12:39:44'
MSN: 'KGB_JB_PR4_RightLev'
A: 408
C: 0
D: 0
F: 409
G: 0
H: 57
J: 30
K: 0
L: 0
M: 0
N: 0
O: 0
P: 0
Q: 0
R: 14
S: 300
U: 0
V: 0
W: 0
X: 4
Y: 0
Z: 0
B: [1x1001 double]
E: [1x2001 double]
I: [1x101 double]
T: [0 5493.1 0 0 0]
>>

More Answers (0)

Community Treasure Hunt

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

Start Hunting!