How to create structs with text data
19 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Rik
il 7 Lug 2022
Why do you want that structure? It seems very difficult to work with the data once it is inside that data structure.
Risposte (1)
Mathieu NOE
il 8 Lug 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 Commenti
Rik
il 21 Ott 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?
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!