alternatives to putting multiple placeholders
1 次查看(过去 30 天)
显示 更早的评论
I have an 1000000*8 matrix which I am trying to output to a text file.
fprintf(fid, '\n%12d %12d %12d %12d %12d %12d %12d %12d', P(:,1:8)')
If the matrix had more columns I would be writing the same placeholder (%12d) many more times. Is there a more efficient way to copy a large matrix to a text file preserving the rows and columns, possibly by writing the necessary placeholder just once.
0 个评论
回答(2 个)
Walter Roberson
2012-3-13
No there is not.
You can, however, pre-calculate the format as a string and pass the string in to the call.
numcols = 8;
fmt = [ '\n', repmat('%12d ', 1, numcols) ];
fprintf(fid, fmt, P(:,1:8).');
0 个评论
Jacob Halbrooks
2012-3-13
Since all of your data has the same format, you can let FPRINTF repeat the format specifier over all of your data. Here is an example of doing that:
data = rand(5,10);
for rInd = 1:size(data,1)
fprintf('\n');
fprintf('%12d ',data(rInd,:));
end
If your data is not regular enough for this, another approach would be to use REPMAT to dynamically create the format specifier for your data. I wrote an example of that here.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!