I'd like to create a loop that each time adds a new line to a .txt file.

8 次查看(过去 30 天)
I have a loop that generates a vector each time it loops through .
my_vector = [ 4, 5, 6,7];
I'd like to create a loop that each time adds the new vector to a .txt file.

采纳的回答

Walter Roberson
Walter Roberson 2013-10-28
fid = fopen('Output.txt', 'wt');
for K = 1 : 10000
my_vector = randi(10,1,4); %generate vector
fprintf(fid, '%d %d %d %d\n', my_vector); adds new vector to text file
end
fclose(fid);
  2 个评论
Sandy
Sandy 2013-10-28
I guess the issue now is that my vector is actually just a string line and it doesn't seem to be working.
str = horzcat(date,' ',name,' ',lat,' ',long,' ', height)
fName = 'test.txt'; % A file name
fid = fopen(fName,'w'); % Open the file
fprintf(fid,'%d %d %d %d\n',str); % Print the string
fclose(fid); % Close the file
Walter Roberson
Walter Roberson 2013-10-28
Replace the fprintf() with
fprintf(fid, '%s\n', str );
But to check to be sure: are "date" and "lat" and "long" and "height" already strings, or are they numeric? If they are numeric then that is the wrong approach, and instead you should use this (presuming here that date and name are string already):
fprintf(fid, '%s %s %f %f %f\n', date, name, lat, long, height);

请先登录,再进行评论。

更多回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-10-28
Look at this example
fid=fopen('file.txt','w')
for k=1:10
my_vector=randi(4,1,4)
fprintf(fid,'%f %f %f %f \r\n',my_vector)
end
fclose(fid)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by