how to read string data from excel and write it to a text file delimited

1 view (last 30 days)
hi all
i have a column of data that i imported using xlsread from excel but i cant write it into a text file because dlmwrite only accepts numerical data and its putting a comma on every character. i also cant use fprintf because it doesnt accept "cell arrays". at the same time i want the data to be delimited by a tab or comma or anything so that i can link the text file to access and make a proper table.
  1 Comment
Stephen23
Stephen23 on 3 Dec 2015
Edited: Stephen23 on 3 Dec 2015
Why not just use Excel for this? Copy the data to a new sheet and save it as a CSV file. The control Panel has options for the string delimiter and column separator.

Sign in to comment.

Answers (1)

Kirby Fears
Kirby Fears on 3 Dec 2015
So you have a cell array in Matlab that you want to print to csv format...
If your cell array contains only numeric data, dlmwrite() would work fine. Just convert your cell array to a double array with cell2mat() before using dlmwrite().
If your cell array contains numeric data as well as character arrays, first convert all contents to character arrays like so:
c = {'abc','d','efgh'; 12, 34, 56; 78, 9, 10}; % sample data
c = cellfun(@(cElt) num2str(cElt),c,'UniformOutput',false);
Now assuming you have a cell array where each cell contains a character array, you can print them in comma-separated format in a csv file as follows:
fid = fopen('test.csv','w'); % open a new csv file
for row = 1:size(c,1),
if numel(c(row,:))>1,
fprintf(fid,'%s,',c{row,1:end-1});
end
fprintf(fid,'%s\n',c{row,end});
end
fclose(fid);

Community Treasure Hunt

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

Start Hunting!