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?
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!