How to add variable names for each column when using array2table

147 vues (au cours des 30 derniers jours)
Espen Mikkelsen
Espen Mikkelsen le 7 Avr 2018
Modifié(e) : Bill Tubbs le 16 Juin 2021
I have an array with 7 columns, and want to convert it to a table with certain variable names for each column. Thanks

Réponse acceptée

David Fletcher
David Fletcher le 8 Avr 2018
a=[1 2 3 4 5 6 7;1 2 3 4 5 6 7]
b=array2table(a,'VariableNames',{'col1','col2','col3','col4','col5','col6','col7'})

Plus de réponses (2)

Abdul Suleman
Abdul Suleman le 18 Déc 2019
Dear David,
My problem is sligthly different than the one to answered to. In my problem the number of columns is not fixed: may be e.g 3, 5 or 10. I wand to label those columns acccording to their number, which is not fixed. Suppose I have 5 columns in an particular dymanic context. Then I want to use a for statetement to create the labels 'col1', ..., 'col5' and use array2table for these five columns. Can you please help me in this issue?
Thank you for your time.
Best wishes,
Abdul

Bill Tubbs
Bill Tubbs le 16 Juin 2021
Modifié(e) : Bill Tubbs le 16 Juin 2021
I wrote a function to do it:
function T = array2table_with_name(X, label, sep)
% T = array2table_with_name(X, label) converts the
% matrix X to a table with custom column labels such
% as 'A1', 'A2', ... etc. if label is 'A' or 'A_1',
% 'A_2', ... etc. if sep (optional) is '_'.
if nargin == 2
sep = '';
end
assert(numel(size(X)) == 2)
n_cols = size(X, 2);
col_names = compose(strcat(label, sep, '%d'), 1:n_cols);
T = array2table(X, 'VariableNames', col_names);
end
The nice thing about this function is that you can label the columns when X is an expression.
Example:
>> array2table_with_name(X.^2, 'X_sq', '_')
ans =
2×3 table
X_sq_1 X_sq_2 X_sq_3
_______ ______ _________
0.67779 8.3869 3.1085
0.62707 3.0209 0.0029565

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by