How to export data into text file with flexible formatSpec
1 次查看(过去 30 天)
显示 更早的评论
Hi Matlabers.. Can you help me? I want to export cell data into a text file. But number of cells in every row is a variable. I've tried to use 'fprintf', but the thing is, if number of cells in every row is variable, of course value in formatSpec should be flexible, depends on variable too (cmiiw). Please look at this following pict..
this data..
I want to export into a text file till like this..
the text file have to suit with this specific details:
- every data in each cells separated using one space
- every cells in each row separated using tab-space
like I said, I've tried to use function 'fprintf', with details code..
fileID = fopen('result.txt','w');
formatSpec = '%d %d %d %d %d %d \n';
[nrows,ncols] = size(pop3);
for row = 1:nrows
for col = 1:ncols
fprintf(fileID,formatSpec,pop3{row,col});
end
end
and the result is..
I know (one of) my fault(s) is the formatSpec, but I have no idea what should I do to make the output text file meets to 2 specific details I explained before.
I need you guys to help me for any suggestion for this case.. Thankyou..
Dimas, Indonesia.
0 个评论
采纳的回答
Amy Haskins
2015-12-30
'\n' is new line. I think you want '\t' for tabs at the end of each cell and a new line at the end of the row. By adding an inner loop to go though each element in the cell, you can make the code even less sensitive to how many elements are in each cell.
fileID = fopen('result.txt','w');
[nrows,ncols] = size(pop3);
for row = 1:nrows
for col = 1:ncols
formatSpec = '%d '; % Puts a space between elements in the same cell
for idx = 1:numel(pop3{row,col})
fprintf(fileID,formatSpec,pop3{row,col}(idx));
end
fprintf(fileID,'\t'); % Add a tab at the end of each cell
end
fprintf(fileID,'\n'); % Add a new line at the end of a row
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!