필터 지우기
필터 지우기

Create a table from a list of variables

조회 수: 15 (최근 30일)
Paolo Mazzoleni
Paolo Mazzoleni 2023년 6월 23일
댓글: Peter Perkins 2023년 7월 17일
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]
Paolo Mazzoleni
Paolo Mazzoleni 2023년 6월 23일
it works, thanks

댓글을 달려면 로그인하십시오.

추가 답변 (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