How can I write to a txt file dynamically?

2 Ansichten (letzte 30 Tage)
Ahmed Elkady
Ahmed Elkady am 1 Aug. 2012
I want to save this form to a text file:
Col1 Col2 Col3 ..... ColN % Text File Heading
4 45 345 ..... 34
34 88 455 ..... 73
Note: The number of columns "N" is variable.
I need an expression that is a function in "N" inside a loop (1:N)
  2 Kommentare
nanren888
nanren888 am 1 Aug. 2012
Can you ask the question again in different words?
Ahmed Elkady
Ahmed Elkady am 1 Aug. 2012
To make it more easier. I need an expression where I specify a value "N" and then it automatically writes Col1 Col2 Col3 up to ColN in the text file as shown earlier.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

venkat vasu
venkat vasu am 1 Aug. 2012
Bearbeitet: Walter Roberson am 1 Aug. 2012
A = round(rand(6,7)*9); % Write this to file.
fid = fopen('Mymatrix.csv','wt');
c='col';
for i = 1:size(A,2)
fprintf(fid,'%s=%d\t',c,i);
end
fprintf(fid,'\n');
for ii = 1:size(A,1)
fprintf(fid,'%g\t',A(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
this may help you...

Weitere Antworten (1)

Oleg Komarov
Oleg Komarov am 1 Aug. 2012
Bearbeitet: Walter Roberson am 1 Aug. 2012
A = [ 4 45 345 34
34 88 455 73];
% Number of columns
N = 2;
% Create/open file discarding content
fid = fopen('test.txt','w');
% Write header
fmt = sprintf('Col%d\t',1:N);
fprintf(fid,[fmt(1:end-1) '\r\n']);
% Write data
fmt = repmat('%.f\t',1,N);
fprintf(fid, [fmt(1:end-2) '\r\n'],A');
fclose(fid);

Kategorien

Mehr zu Data Import and Export finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by