Create a table from a list of variables

10 次查看(过去 30 天)
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 个评论
Peter Perkins
Peter Perkins 2023-7-17
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.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2023-6-23
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 个评论
Rik
Rik 2023-6-23
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]

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by