Borrar filtros
Borrar filtros

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

8 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Walter Roberson
Walter Roberson el 28 de Oct. de 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 comentarios
Sandy
Sandy el 28 de Oct. de 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 el 28 de Oct. de 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);

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 28 de Oct. de 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)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by