Borrar filtros
Borrar filtros

Create a table from a list of variables

15 visualizaciones (últimos 30 días)
Paolo Mazzoleni
Paolo Mazzoleni el 23 de Jun. de 2023
Comentada: Peter Perkins el 17 de Jul. de 2023
I'm loading a file that contains several Nx1 arrays of data, each one being a separate variable, plus various metadata
I want to assemble all the data into a table, how can I do that?
this is what I'm doing at the moment, it works, it's fast for what I'm doing, but I feel guilty because my grandma once told me never never to use eval
vars = whos;
vars = vars(strcmp({vars(:).class},'single'));
T = table;
for ii = 1:length(vars)
eval(['T.' vars(ii).name '=' vars(ii).name ';'])
end
  1 comentario
Peter Perkins
Peter Perkins el 17 de Jul. de 2023
Your grandma is smart. You can avoid eval on the LHS of that assignment
T.(vars(ii).name) = ...
but you do need an eval for the RHS.
If you knew the workspace var names, and they were always the same
t = table(myvar1,myvar2,...)
would capture the workspace names, but presumably you are not in that boat. So Rik's advice is good.

Iniciar sesión para comentar.

Respuesta aceptada

Rik
Rik el 23 de Jun. de 2023
If you are loading a file you should use this syntax:
S = load(filename);
That way, all variables in the mat file are stored as the fieldnames of S. This means it is always clear where variables came from. If you need the variable names for some reason, you can use the fieldnames function. struct2table may already do what you need.
  4 comentarios
Rik
Rik el 23 de Jun. de 2023
Just like you would otherwise: with dynicamic indexing.
example = struct(...
'a',rand(10,1),...
'b',single(rand(10,1)),...
'c','some description',...
'd',single(rand(10,1)));
f_names = fieldnames(example);
slim = example;
for n=1:numel(f_names)
if ~isa(slim.(f_names{n}),'single')
slim = rmfield(slim,f_names{n});
end
end
disp(slim)
b: [10×1 single] d: [10×1 single]
Paolo Mazzoleni
Paolo Mazzoleni el 23 de Jun. de 2023
it works, thanks

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by