Problem adding headers to a matrix and saving it in txt file

Hello everyone,
I have a matrix called data (2618x17) I would like to add headers to each column and save it in a TXT file. I did the following code but it doesn't work. Can someone help me fix this problem? Thanks!
headers={'Timestamp','PosX','PosZ','PosY','RotX','RotY','RotZ','RPosX','RPosZ','RPosY','RRotX','RRotY','RRotZ','velocity','acceleration','curvature','target_reached'};
newdata=[headers; num2cell(data)]; dlmwrite('file_treated.txt',newdata);

 Respuesta aceptada

Stephen23
Stephen23 el 12 de Abr. de 2018
Editada: Stephen23 el 12 de Abr. de 2018
dlmwrite only writes numeric data: its help states that it "writes numeric data in array M...". You do not have a numeric array, you have a mixed cell array.
If you want to write mixed char/numeric (e.g numeric data with a header) then you could use xlswrite, writetable, or do-it-yourself with fprintf.

3 comentarios

Alex castilla
Alex castilla el 12 de Abr. de 2018
Editada: Alex castilla el 12 de Abr. de 2018
I tried to use xlswrite and the output was : The input cell array cannot be converted to a matrix.
newdata=[header; data];
xlswrite('Alexandra_SNV31_treated.xlsx',newdata);
Stephen23
Stephen23 el 12 de Abr. de 2018
Editada: Stephen23 el 12 de Abr. de 2018
You could use fprintf:
headers={'Timestamp','PosX','PosZ','PosY','RotX','RotY','RotZ','RPosX','RPosZ','RPosY','RRotX','RRotY','RRotZ','velocity','acceleration','curvature','target_reached'};
data = rand(4,17); % four rows of fake data.
fmt = repmat(',%.12g',1,size(data,2)); % pick numeric format to suit!
fmt = [fmt(2:end),'\n'];
[fid,msg] = fopen('temp4.csv','wt');
assert(fid>=3,msg)
fprintf(fid,'%s',headers{1})
fprintf(fid,',%s',headers{2:end})
fprintf(fid,'\n')
fprintf(fid,fmt,data.')
fclose(fid);
The file that this created is attached to this comment.
Thanks so much. It works perfectly.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 12 de Abr. de 2018

Comentada:

el 13 de Abr. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by