How to load data from csv-files with "dot"-structured variable names and convert to struct/table?

2 visualizaciones (últimos 30 días)
Importing data is not the biggest problem, however autogenterate variable names from the headers from the csv-file has been a nightmare.
For example, in a csv-file i can have the table like this(note i can't change the structure of the data sorce)
in.sensors.temp.x in.sensors.temp.y
2 3
1 4
Now what i want to do, is to load in the data and create a struct with the same structure as readings header and assign the data to it.
% what i have done so far:
I import the data by using the functionen "importdata". I have tried csvread, xlsread and readtable , but they have either not worked or created corupt data.
After that I get a struct containg data and datatext. The data text is type char characters.
How do I take create a struct by reading a cell containing charcaraters with dots?
I have tried something like this:
in = createStruct(var_name(5), data(:,5))
function temp = createStruct(fullString, data)
fullString = cell2mat(fullString);
dotFind = strfind(fullString,'.');
temp = data;
while ~isempty(dotFind)
%temp = temp.(convertCharsToStrings(fullString(1:dotFind(1)-1)));
struct(fullString(1:dotFind(1)-1),0);
%fullString = fullString(dotFind(1)+1:end);
%dotFind = strfind(fullString,'.');
end
end
but did not perform very well
  1 comentario
Stephen23
Stephen23 el 11 de Dic. de 2020
Editada: Stephen23 el 11 de Dic. de 2020
Rather than that complex and fiddly loop, to split the string at the dots just use SPLIT or REGEXP.
Rather than using awful EVAL (bad advice), the best way to create the structure field is with SETFIELD.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 11 de Dic. de 2020
Editada: Stephen23 el 11 de Dic. de 2020
Better than evil EVAL is to use more robust SETFIELD and a comma-separated list:
str = 'in.sensors.temp.x';
val = pi;
tmp = regexp(str,'\.','split'); % or SPLIT
S = struct();
S = setfield(S,tmp{:},val)
S = struct with fields:
in: [1×1 struct]
Checking:
S.in.sensors.temp.x
ans = 3.1416
Loop as required. Read more:
  3 comentarios
Sean de Wolski
Sean de Wolski el 11 de Dic. de 2020
Awesome! I did not know about setfield. I looked at the see also for rmfield and searched addfield and did not come across setfield... :(

Iniciar sesión para comentar.

Más respuestas (1)

Niclas Klarström
Niclas Klarström el 11 de Dic. de 2020
Okey, here is an example of simplifyed log file. Just to not leak any sensible info.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by