How to create structs with text data

17 views (last 30 days)
fernando aguirre
fernando aguirre on 7 Jul 2022
Commented: Rik on 8 Jul 2022
I am struggling to find a way to separate the cells I created from the data I read in into an ordered structured based on the parent string
i.e. want data = {"couple1:" , " child1:" , " grandchild1: 3",....}
into couple1.child1.grandchild1 = 3
I thought of using isspace to determine if the cell has spaces or not and sum from there to check the previous cell, but it sounds memory expensive if my text files is much bigger.
Thanks!
fid = open('exampledata.txt')
Error using open
Failed to open MATLAB Editor.
tline = fgetl(fid);
data = cell(0,1);
while ischar(tline)
data{end+1,1} = tline;
tline = fgetl(fid);
end
fclose(fid);
  1 Comment
Rik
Rik on 7 Jul 2022
Why do you want that structure? It seems very difficult to work with the data once it is inside that data structure.

Sign in to comment.

Answers (1)

Mathieu NOE
Mathieu NOE on 8 Jul 2022
hello
check my demo code below :
clc
clearvars
mylines = readlines('exampledata.txt'); %
[m,n] = size(mylines);
% grouping all variables under an overarching struct
S = struct() ;
for ck = 1 : m
tmp = char(mylines(ck));
% empty default numeric values
lev1_num = [];
lev2_num = [];
lev3_num = [];
if length(tmp)>0
nb_of_leading_spaces = max(find(isspace(tmp(1:min(length(tmp),9))))); % assuming here no more than 9 leading spaces are used (adjust)
%% level 1 (couple)
if isempty(nb_of_leading_spaces) % check no space characters in the 3 first positions
ind = strfind(tmp,':');
lev1 = tmp(1:ind-1)
S.(lev1) = lev1_num;
end
%% level 2 (child)
if nb_of_leading_spaces == 3 % check no space characters in the 3 first positions
ind = strfind(tmp,':');
lev2 = tmp(1:ind-1);
lev2 = strtrim(lev2); % remove leading spaces
% check if data after ':' is numeric
lev2_num = tmp(ind+1:end);
if ~isempty(lev2_num)
lev2_num = str2num(lev2_num)
end
S.(lev1).(lev2) = lev2_num;
end
%% level 3 (grandchild)
if nb_of_leading_spaces == 6 % check no space characters in the 3 first positions
ind = strfind(tmp,':');
lev3 = tmp(1:ind-1)
lev3 = strtrim(lev3); % remove leading spaces
% check if data after ':' is numeric
lev3_num = tmp(ind+1:end);
if ~isempty(lev3_num)
lev3_num = str2num(lev3_num)
end
S.(lev1).(lev2).(lev3) = lev3_num;
end
end
end
  1 Comment
Rik
Rik on 8 Jul 2022
You can probably make the depth dynamic by using the setfield function.

Sign in to comment.

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!