How to create structs with text data
19 次查看(过去 30 天)
显示 更早的评论
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 个评论
Rik
2022-7-7
Why do you want that structure? It seems very difficult to work with the data once it is inside that data structure.
回答(1 个)
Mathieu NOE
2022-7-8
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 个评论
Rik
2024-10-21
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?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!