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

7 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 28 Oct 2013
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 Comments
Sandy
Sandy on 28 Oct 2013
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 on 28 Oct 2013
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);

Sign in to comment.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 28 Oct 2013
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)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!