How to export data into text file with flexible formatSpec

2 views (last 30 days)
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.

Accepted Answer

Amy Haskins
Amy Haskins on 30 Dec 2015
'\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

More Answers (0)

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!