필터 지우기
필터 지우기

for loop, write to text file, append, sprintf, fprintf

조회 수: 55 (최근 30일)
Jonas K
Jonas K 2017년 6월 23일
댓글: Jonas K 2017년 6월 23일
Hi, I want to make a for_loop that adds lines to a text file.
first loop: direction_lights_1 = [1 2 3] second loop: direction_lights_2 = [4 5 6] ... fifth loop: direction_lights_5 = [13 14 15]
My code so far looks like this:
fileID = fopen(sprintf('textfile.txt','w'); %here I create the text file
fprintf(fileID, '%f %f %f \n', direction_lights); %here I print the 3 numbers and then go to a new line
fclose(fileID);
Now I want the program to append lines to the existing text file. It should look somewhat like this:
for i=1:5 %obviously open the file again
fprintf(fileID, '%f %f %f \n', direction_lights_i.'a');
end
I can't figure out how to make it work. Hope it is clear what I'm trying to achieve. Thanks for your help! J
  댓글 수: 1
Jan
Jan 2017년 6월 23일
In fopen(sprintf('textfile.txt','w'): No "sprintf(" here.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 6월 23일
편집: Jan 2017년 6월 23일
fileID = fopen('textfile.txt', 'a');
for i=1:5
fprintf(fileID, '%f %f %f \n', direction_lights_i);
end
fclose(fileID);
The 'a' belongs to the fopen command, not to fprintf.
  댓글 수: 4
Jan
Jan 2017년 6월 23일
편집: Jan 2017년 6월 23일
:-) This is really funny! What a STRANGE output!!! :-)
But exactly as expected: These are the ASCII codes of the string 'direction_lights_1' - see:
double('direction_lights_1')
What is the prupose of
direction_lights_i = sprintf('direction_lights_%i',i);
? This creates a string, a CHAR vector. But it does not access the variable with the same name magically. Do not confuse the contents with the name of a variable. These are 2 different things.
What you want to use is the evil eval: This command evaluates the contents of a string as code. We discuss this nearly once a day here, because it is the evergreen of bad programming patterns. See e.g. this exhaustive overview: Answers: Don't eval!
Do not hide indices in the names of a variable, but use an index instead. There are some more problems in your code:
% Why? Do you have a good reason for a brutal clearing?
clc; close all; clear;
folder = cd; % Set it accordingly
name_object = 'test';
num_lights = '12'; % Now this is a string already
% Create an array, e.g. a cell array, instead of hiding
% an index in the names:
direction_lights{1} = [1 2 3];
direction_lights{2} = [4 5 6];
direction_lights{3} = [7 8 9];
filename = fullfile(folder, sprintf('lights_%s.txt', name_object));
fileID = fopen(filename, 'w');
% I've seen too many problems in this forum caused by
% unsuccessful opening of files without noticing this:
if fileID == -1, error('Cannot open file: %s', filename); end
% num_lights is a string already, then |str2double| is
% not useful as indirection:
fprintf(fileID, '%s\n', num_lights);
% No, leave the file open:
% fclose(fileID);
% But if the file was really closed before, open it
% *before* the loop as shown in my code example above:
fileID = fopen(sprintf('lights_%s.txt', name_object) , 'a');
for k = 1:3
fprintf(fileID, '%f %f %f\n', direction_lights{k});
end
fclose(fileID);
Opening and closing the file inside the loop is not an error, but a waste of time. There might be situations, where this is useful, but not in this example.
Prefer full file names containing a path. Note that a GUI or timer callback might change the current folder unexpectedly. Then files will appear in unexpected locations are might be lost. Avoid such sources of confusions - too many others suffered from such mistakes already.
Read the thread about eval carefully. This will ease your life.
Jonas K
Jonas K 2017년 6월 23일
thank you, this looks much nicer than my try!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by