text file dlmwrite fprintf save

1 次查看(过去 30 天)
Nicolas
Nicolas 2011-7-27
Hi,
It might be another question on this subject.. but i'm confused saving text files.
i have a basic code with data(2,49) to save in each loop the data minus one row
i=length(data)
for j=1:i
coord=[data(1:(i-j),1),data(1:(i-j),2)];
filename = [ 'coord' num2str(j-i) '.txt' ];
Then I'm stuck..
dlmwrite (filename, coord,'delimiter','\t','precision',7)
end
do not write in column, I understood that text files are row oriented, but i don't get the fprintf way..
if someone can explain me..

回答(2 个)

Walter Roberson
Walter Roberson 2011-7-27
You are not using fprintf() directly anywhere.
Anyhow, try
dlmwrite (filename, transpose(coord),'delimiter','\t','precision',7)
By the way: your coord matrix is not 2 x 49: it is 49 x 2.
Also, you can abbreviate your creation of coord:
coord = data(1:i-j,1:2);
  1 个评论
Nicolas
Nicolas 2011-7-27
thanks, I put fprintf() because I saw some answers written using it. Thanks for the abbreviation hint! but transpose don't work. When i open the text file the data are still on a row.

请先登录,再进行评论。


Oleg Komarov
Oleg Komarov 2011-7-27
The version with fprintf:
% Sample data
data = rand(49,2);
szData = size(data);
% Generate all filenames at once
filename = reshape(sprintf('coord-%02d.txt', szData(1)-1:-1:0),12,49).';
% Loop and use fprintf
for n = 1:szData(1)
coord = data(1:szData(1)-n,:);
fid = fopen(filename(n,:),'w');
fprintf(fid,'%.7f\t%.7f\r\n',coord.');
fid = fclose(fid);
end
  2 个评论
Nicolas
Nicolas 2011-7-27
??? Error using ==> reshape
To RESHAPE the number of elements must not change.
Error in ==> Generate_sequence at 6
filename = reshape(sprintf('Beb-coord-%02d.txt', szData(1)-1:-1:0),12,49).';
Oleg Komarov
Oleg Komarov 2011-7-27
You have to replace the 12 by the length of the name:
Beb-coord-48.txt, i.e. 16 chars.
filename = reshape(sprintf('Beb-coord-%02d.txt', szData(1)-1:-1:0),16,49).';

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by