How to export a table including column names?

I have a matrix A that I want to convert into a table with variable names and export as csv.
This is my code:
MyTable = array2table(A);
MyTable.Properties.VariableNames(1:4) = {'Min','Max', 'Mean', 'St. Dev.'};
writetable(MyTable,'MyTable.csv', 'WriteVariableNames', true);
But I get the following error:
Error using writetable
Unsupported type 'double'. Use writematrix instead.
But when using 'writematrix' the column names aren't supported.
NB: one of the columns in A has NaN in some rows.
Update: the code above works fine; there was a mistake in the original code. SORRY!

 採用された回答

Jan
Jan 2022 年 3 月 20 日

0 投票

Maybe there is a typo in the original code? If I adjust the variable names, which must be legal Matlab symbols in my R2018b version, it is running:
A = rand(5, 4); % Some test data
MyTable = array2table(A);
MyTable.Properties.VariableNames(1:4) = {'Min','Max', 'Mean', 'StDev'};
writetable(MyTable,'MyTable.csv', 'WriteVariableNames', true);

1 件のコメント

Lu Da Silva
Lu Da Silva 2022 年 3 月 20 日
編集済み: Lu Da Silva 2022 年 3 月 20 日
You're right, there was a typo! My bad, so sorry! But thank you!

サインインしてコメントする。

その他の回答 (1 件)

Star Strider
Star Strider 2022 年 3 月 20 日

2 投票

It might be better to write it as a text file instead, since a .csv file may not be appropriate.
writetable(MyTable,'MyTable.txt', 'WriteVariableNames', true);

6 件のコメント

Lu Da Silva
Lu Da Silva 2022 年 3 月 20 日
Nope, doesn't do it. Do you think the fact that A contains NaNs in some rows could be the source of the error?
Stephen23
Stephen23 2022 年 3 月 20 日
It works for me, including NaNs:
T = array2table([1,2;NaN,3;NaN,4;5,6]);
T.Properties.VariableNames = {'X','Y'};
writetable(T,'test.txt')
type test.txt
X,Y 1,2 NaN,3 NaN,4 5,6
Lu Da Silva
Lu Da Silva 2022 年 3 月 20 日
You're right, this works fine. There was a mistake in the original code, my bad!
Star Strider
Star Strider 2022 年 3 月 20 日
@Stephen — Thank you!
Paul Safier
Paul Safier 2023 年 4 月 6 日
Thanks @Star Strider that solved my problem too!
Star Strider
Star Strider 2023 年 4 月 7 日
@Paul Safier — My pleasure!
A Vote would be appreciated!

サインインしてコメントする。

質問済み:

2022 年 3 月 20 日

コメント済み:

2023 年 4 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by