How can we write data into csv file with column labels included ?
조회 수: 191 (최근 30일)
이전 댓글 표시
I want to write the data into csv file with column labels. I have illustrated the code below.
chead = {'a','b','c','d','e','f','g','h','i','k','l'};
data1 = ones(1001,4);
data2 = ones(125,7);
data = {data1,data2};
R = [chead;data];
writecell(R,'file.csv');
But this doesn't work the way i expected. This was writing the data like:
a b c .......
1 1 1 1 .... 1 1 1 1 .... 1 1 1 1....
instead of
a b c .......
1 1 1
1 1 1
1 1 1
1 1 1
. . .
. . .
If anyone knows please tell the answer.
댓글 수: 2
답변 (2개)
dpb
2020년 8월 22일
편집: dpb
2020년 8월 22일
...
data1 = ones(1001,4);
data2 = ones(125,7);
data = {data1,data2};
...
You have created a disparate-sized array of 125 rows of seven variables and the remainder with only four -- this can't be put into a rectangular array to write a regular .csv file. writecell did what you asked it to do, output the content of the cell array you built; you just didn't build a representation of what you (apparently) intended.
What do you intend the content of the file to be for the shorter records -- missing values or shorter records?
I've not tested if writecell will build a file -- well, let's just see:
>> writecell(cell(2,4))
>> type cell.txt
,,,
,,,
>>
Ah! Indeed it will, if you convert your numeric array by num2cell to a cell array of one element to cell, and add the empty cells where needed, joy wil ensue.
ADDENDUM:
While it's relatively trivial to write using fprintf, you can try something like
names={'a','b','c'}; % build a set of variable names
writecell(names) % write to names.txt (pick your name as desired)
c= [ones(2,3) zeros(2,4)]; % longer rows
save names.txt c -ascii -append % add to existing file
c= ones(2,3); % short rows
save names.txt c -ascii -append % ditto
results in
>> type names.txt
a,b,c
1.0000000e+00 1.0000000e+00 1.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00
1.0000000e+00 1.0000000e+00 1.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00
1.0000000e+00 1.0000000e+00 1.0000000e+00
1.0000000e+00 1.0000000e+00 1.0000000e+00
>>
댓글 수: 2
dpb
2020년 8월 22일
You'll have to write the file specifically with low-level calls, then. There is no prepared function to write an irregular file of that format.
You'll run into trouble trying to read the file back again, anyway, unless an application is aware of this issue going in.
giancarlo maldonado cardenas
2022년 6월 6일
you can do it with this
A=[4 5 6;7 8 9]
T = array2table(A)
T.Properties.VariableNames(1:3) = {'x_axis','y_axis','z_axis'}
writetable(T,'file1.csv')
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Analysis에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!