How to use function table (or timetable) inside a loop to generate a final table that contains a large number of variables (columns) with names
Show older comments
Wondering if anyone could suggest how to use the function table (or timetable) inside a loop to generate a final table that contains a large number of variables (columns) with names?
%This is my wrong attempt...
T = array2table(DATA);
%DATA is an array with 1st column (sorted dates), following 300 columns (data, double), and over 100.000 rows.
for kk=1:size(DATA,2)
name={num2str(file_name_list{kk})}; % Generate individual names to add to next step
T =[T; array2table(DATA,'VariableNames', {name})]; % Trying to add new names to columns...
end
%... to get something like
Time VarName1 VarName2 ... VarName300
'20-Sep-2001 00:00:00' 10 2.5 ... NaN
'20-Sep-2001 01:00:00' NaN 0.34 ... 12
'20-Sep-2001 02:00:00' 0.1 NaN ... 0.4
... ... ... ... ...
Thanks!
Accepted Answer
More Answers (1)
Walter Roberson
on 7 Mar 2017
Almost!
T =[T, array2table(DATA,'VariableNames', {name})]; % Trying to add new names to columns...
This changes the ";" to ","
For example,
T = array2table(randi(6,5,2))
T = [T,array2table(randi(10,5,7), 'VariableNames', {'A1','A2','A3','A4','A5','A6','A7'})]
5 Comments
Robert
on 7 Mar 2017
Walter Roberson
on 7 Mar 2017
Edited: Walter Roberson
on 7 Mar 2017
name = arrayfun(@(N) sprintf('Var%d',N), file_list{1,kk}, 'Uniform', 0);
This asumes that file_list{1,kk} contains a vector of numbers and that you want the variables named 'Var' followed by the corresponding number. Note that numbers cannot be used as variable names in themselves: each name must be a valid MATLAB identifier.
Robert
on 8 Mar 2017
Walter Roberson
on 8 Mar 2017
My guess:
T = array2table(DATA(:,1));
%This now create a Table with one column, which has the dates
for kk = 2 : size(DATA,2)
name_cell = file_list(kk);
% Generate individual names to add to next step
T = [T, array2table(DATA(:,kk),'VariableNames', name_cell)];
end
However, if you were going to do that, then just
T = array2table(DATA, 'VariableNames', file_list);
with no loop.
Robert
on 8 Mar 2017
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!