필터 지우기
필터 지우기

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