How to create structs with text data

조회 수: 19 (최근 30일)
fernando aguirre
fernando aguirre 2022년 7월 7일
댓글: Rik 2024년 10월 21일
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
Rik
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
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
Rik 2022년 7월 8일
You can probably make the depth dynamic by using the setfield function.
Rik
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by