fprintf cell array with strings and numbers

2 次查看(过去 30 天)
I have a matrix "C" 902x14cell and I need to write it using fprintf. Before the matrix I have 10 lines of header that contain only strings.
%%do this 10 times for each line of header
[rows10{kk},cols10{kk}]=size(header_row10{kk});
for i=1:rows10{kk}
fprintf(B{kk},'%s,',header_row10{kk}{i,1:end-1});
fprintf(B{kk},'%s\n',header_row10{kk}{i,end});
end
%Begin writing data after 10 lines of header
[rowsC{kk},cols1{kk}]=size(C{kk});
for i=1:rowsC{kk}
fprintf(B{kk},'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',C{kk}{i,1:end});
fprintf(B{kk},'%f%f%f%f%f%f%f%f%f%f%f%f%f%f\r\n',transpose(C{kk}{i,end}));
end
but when I do this it just creates a csv file of 1 row with all the columns mashed together. The only reason I need to use fprintf is because the matrix has 13 columns of number and 1 column of strings and dlmread doesn't support cells. Is there a way to fprintf C without it losing the columns?

回答(1 个)

dpb
dpb 2017-2-3
...
fmt=[repmat('%f,',1,cols1{kk}-1) '%s\n']; % format presuming last is string
for i=1:rowsC{kk}
fprintf(B{kk},fmt,C{kk}{i,1:end-1},char(C{kk}(end)));
end
should do it altho a small sample of the actual data structure would be helpful.
  2 个评论
sal135
sal135 2017-2-7
The char column is the second column. So column 1 is made of doubles, column 2 is made of chars and columns 3-14 are made of doubles.
dpb
dpb 2017-2-7
So, just rearrange the format string and output to match the layout...again the actual storage would be useful to get the indexing expressions right; the arrangement of {} looks peculiar in your code that I just mimicked.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by