How fprintf cell array and martix?

12 vues (au cours des 30 derniers jours)
Qingsheng Bai
Qingsheng Bai le 5 Sep 2017
Modifié(e) : per isakson le 6 Sep 2017
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!

Réponse acceptée

per isakson
per isakson le 5 Sep 2017
Modifié(e) : per isakson le 6 Sep 2017
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 commentaires
Qingsheng Bai
Qingsheng Bai le 5 Sep 2017
Thanks! This helped me a lot.
per isakson
per isakson le 5 Sep 2017
I added a speed test to my answer.

Connectez-vous pour commenter.

Plus de réponses (1)

Stephen23
Stephen23 le 5 Sep 2017
Modifié(e) : Stephen23 le 5 Sep 2017
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 commentaires
Qingsheng Bai
Qingsheng Bai le 5 Sep 2017
Thank you. It is better, since my data is huge.
Stephen23
Stephen23 le 5 Sep 2017
@Qingsheng Bai: I hope that it helps. You can also vote for my answer if it was useful for you.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by