How to create structs with text data
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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')
tline = fgetl(fid);
data = cell(0,1);
while ischar(tline)
data{end+1,1} = tline;
tline = fgetl(fid);
end
fclose(fid);
1 comentario
Rik
el 7 de Jul. de 2022
Why do you want that structure? It seems very difficult to work with the data once it is inside that data structure.
Respuestas (1)
Mathieu NOE
el 8 de Jul. de 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
2 comentarios
Rik
el 21 de Oct. de 2024
Deleting your answer and reposting as comment is not what I meant. Go to https://www.mathworks.com/matlabcentral/discussions and see which category fits best.
Although, to be honest, I don't understand why you don't put this in a Word document on your own computer. What is the actual benefit to others of this wall of text?
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!