How fprintf cell array and martix?

12 次查看(过去 30 天)
I want to fprintf a cell array and a matrix to a txt file. I used the following code, but got the wrong result.
xx={'2017032312_8953';'2017032312_8978'};
yy=[10;11];
fprintf('%s %e \n ',xx{:}, yy)
The results is:
2017032312_8953 5.000000e+01
017032312_8978 1.000000e+01
I want the result like this:
2017032312_8953 1.0E+01
2017032312_8978 1.1e+01
How can this problem be solved? Many thanks!

采纳的回答

per isakson
per isakson 2017-9-5
编辑:per isakson 2017-9-6
xx={'2017032312_8953';'2017032312_8978'};
yy=[10;11];
for jj = 1 : length( xx )
fprintf( '%s %3.1E \n', xx{jj}, yy(jj) )
end
outputs
2017032312_8953 1.0E+01
2017032312_8978 1.1E+01
Comparison of elapse times of loop codes and the vectorized code by Stephen Cobeldick
"It is better, since my data is huge." "Huge" implies that you want to write to a text file.
Here is a test on R2016a 64bit, Win7 and an old vanilla desktop.
>> et = cssm(1e4)
et =
8.4265 0.6577 0.1814
The difference between the first and the second elapse time value illustrates the influence of automatic flushing on speed. (Both are based on for-loops.) See Improving fwrite performance at Undocumented Matlab by Yair Altman. The third value is the elapse time of the vectorized code by Stephen Cobeldick.
The test is done with this function
function et = cssm(N)
xx = repmat( {'2017032312_8953';'2017032312_8978'}, N,1 );
yy = repmat( [10;11], N, 1 );
tic
fid = fopen( 'test1.txt', 'w' );
for jj = 1 : length( xx )
fprintf( fid, '%s %3.1E \n', xx{jj}, yy(jj) );
end
fclose( fid );
et = toc;
tic
fid = fopen( 'test2.txt', 'W' );
for jj = 1 : length( xx )
fprintf( fid, '%s %3.1E \n', xx{jj}, yy(jj) );
end
fclose( fid );
et(end+1) = toc;
tic
C = xx.';
C(2,:) = num2cell(yy);
fid = fopen( 'test3.txt', 'W' );
fprintf( fid, '%s %3.1E \n', C{:});
fclose( fid );
et(end+1) = toc;
end

更多回答(1 个)

Stephen23
Stephen23 2017-9-5
编辑:Stephen23 2017-9-5
Avoiding the for loop is quite easy too:
C = xx.';
C(2,:) = num2cell(yy);
fprintf('%s %3.1E \n', C{:})
which prints:
2017032312_8953 1.0E+01
2017032312_8978 1.1E+01
  2 个评论
Qingsheng Bai
Qingsheng Bai 2017-9-5
Thank you. It is better, since my data is huge.
Stephen23
Stephen23 2017-9-5
@Qingsheng Bai: I hope that it helps. You can also vote for my answer if it was useful for you.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by