Reputation: 817
Suppose I have the following MATLAB
code:
clear; clc
Items = {'counter','item1', 'item2', 'item3', 'item4'};
a = rand(8,4);
j = (1:8)';
t = table(j,a(:,1), a(:,2), a(:,3), a(:,4),'VariableNames',Items)
I would like to know if there is a sophisticated way to extend this list if i have e.g. 20 items. Following this code, I should include inside table
every single a(:,i), i = 1,...,20
, plus I would have to do the same for the Items
list. I guess there is a more convenient way than this.
Upvotes: 1
Views: 660
Reputation: 12214
See array2table
:
a = rand(8,4);
[l, w] = size(a);
j = 1:l;
Items = cell(1, w + 1);
Items{1} = 'counter';
for ii = 2:length(Items)
Items{ii} = sprintf('item%u', ii - 1);
end
t = array2table([j', a], 'VariableNames', Items);
Edit: It seems like there's a lot of overhead associated with array2table
. It's essentially a wrapper for mat2cell
so there might be a speed benefit to just using that on its own and skipping all the error checking. Haven't tested it out though.
Upvotes: 1
Reputation: 211
You can make a cell with all columns in a.
for i=1:size(a,2)
acell{end+1}=a(:,i);
end
and then call
table(j,acell{:},'VariableNames',Items)
Here is an example:
Items = {'counter'};
a = rand(8,6);
j = (1:8)'
acell = [];
for i=1:size(a,2)
acell{end+1}=a(:,i);
Items{end+1}=['item',num2str(i)];
end
t = table(j,acell{:},'VariableNames',Items);
Upvotes: 1