How fprintf cell array and martix?

12 ビュー (過去 30 日間)
Qingsheng Bai
Qingsheng Bai 2017 年 9 月 5 日
編集済み: per isakson 2017 年 9 月 6 日
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
  2 件のコメント
Qingsheng Bai
Qingsheng Bai 2017 年 9 月 5 日
Thanks! This helped me a lot.
per isakson
per isakson 2017 年 9 月 5 日
I added a speed test to my answer.

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by