Clear Filters
Clear Filters

Create a table from a list of variables

15 views (last 30 days)
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 Comment
Peter Perkins
Peter Perkins on 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.

Sign in to comment.

Accepted Answer

Rik
Rik on 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 Comments
Rik
Rik on 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]

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!