CSWWrite

1 view (last 30 days)
Fredrik
Fredrik on 1 Dec 2011
Hi. I have my data in a Matrix called Data and my Time in a Cell array called Time, with "yyyy-mm-dd-hh-mm format". Now I want to write this as a csv-file, with the timestamp in the first column and then the data after that. Same number of rows in time and data..
I have tried to look into cellwrite and so but I dont really get it.. Can anyone help?
Fredrik

Accepted Answer

K E
K E on 23 Dec 2011
I would suggest using fprintf since you are mixing a string and a number in the CSV file.
%%Create example input data
Data = rand(10, 2) ;
% Cell array with time values
timeValue = datenum(2011, 12, 1:10) ; % Time in Matlab format
for iTime = 1:length(timeValue)
Time{iTime} = datestr(timeValue(iTime), 'yyyy-mm-dd-HH-MM') ;
end
%%Write CSV file
fid = fopen('c:\temp\test.csv', 'w') ;
for iLine = 1:size(Data, 1) % Loop through each time/value row
fprintf(fid, '%s1,', Time{iLine}) ; % Print the time string
fprintf(fid, '%12.3f, %12.3f\n', Data(iLine, 1:2)) ; % Print the data values
end
fclose(fid) ;

More Answers (1)

Walter Roberson
Walter Roberson on 23 Dec 2011
csvwrite() can only write numeric values. dlmwrite() can only write either numeric or character data on any one call (and character is not recommended.) xlswrite() can handle cell arrays, but only when you are using MS Windows and have Excel installed; this would normally be used for writing .xls or .xlsx files and I do not know if you could write csv files with it.
Using low level I/O such as K E shows is probably your only practical choice.

Community Treasure Hunt

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

Start Hunting!