How fprintf cell array and martix?
11 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Qingsheng Bai
il 5 Set 2017
Modificato: per isakson
il 6 Set 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!
0 Commenti
Risposta accettata
per isakson
il 5 Set 2017
Modificato: per isakson
il 6 Set 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 Commenti
Più risposte (1)
Stephen23
il 5 Set 2017
Modificato: Stephen23
il 5 Set 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 Commenti
Stephen23
il 5 Set 2017
@Qingsheng Bai: I hope that it helps. You can also vote for my answer if it was useful for you.
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!