Filter löschen
Filter löschen

Create a table from a list of variables

15 Ansichten (letzte 30 Tage)
Paolo Mazzoleni
Paolo Mazzoleni am 23 Jun. 2023
Kommentiert: Peter Perkins am 17 Jul. 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 Kommentar
Peter Perkins
Peter Perkins am 17 Jul. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 23 Jun. 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 Kommentare
Rik
Rik am 23 Jun. 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 am 23 Jun. 2023
it works, thanks

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by