Search code examples
matlabnewlinefopenfgets

discard newline character


Here is the code that I am using;

files2 = dir('X_*.txt');

for kty=1:p

fidF = fopen(['X(A)_' num2str(kty) '.txt'], 'w');

for i = 1:length(files2)

fid = fopen(files2(i).name);

while(~feof(fid))

  string = fgetl(fid) 

 fprintf(fidF, '%s', string)


end

    fclose(fidF);
end

end

P equal to 90, because there have 90 different X text file which include different angles.The new X(A) text files should be 90 different files.

The code is used for getting rid of this second line and it's working.

The thing I want to ask is that when I use this code it creates X(A) text files (90 files) but all include X_1 files angle variable but it should be;

X_1    >   X(A)_1        (each variable should transfer to new file.)
                                                 (X_65  > X(A)_65)
X_2    >   X(A)_2         
...
...

How can I fix the code?

  files2 = dir('angle_*.txt');

for i = 1:length(files2)
   fidF = fopen(['angle(A)_' num2str(i) '.txt'], 'w');
   fid = fopen(files2(i).name);
   while(~feof(fid))
      string = fgetl(fid) 
      fprintf(fidF, '%s', string)
   end
   fclose(fidF);
   fclose(fid);
end

result are

angle_1=272       angle(A)_1=272
angle_2=276       angle(A)_2=308
angle_3=280       angle(A)_3=312
angle_4=284       angle(A)_4=316
angle_5=288       angle(A)_5=320
angle_6=292       angle(A)_6=324
angle_7=296       angle(A)_7=328
angle_8=300       angle(A)_8=332
angle_9=304       angle(A)_9=336
angle_10=308      angle(A)_10=340
angle_11=312      angle(A)_11=344
angle_12=316      angle(A)_12=348

angle_10 variable goes to angle(A)_2 variable and its copy in this order.

Solution

  • In order to have your input and output files match, you need to remove one of the for loops and have X(A)_#.txt match files2(#).name:

    files2 = dir('X_*.txt');
    
    for i = 1:length(files2)
       fid = fopen(files2(i).name);
       fNum = regexp(files2(i).name, '([0-9]*)', 'match');
       fidF = fopen(['X(A)_' fNum{1} '.txt'], 'w');
       while(~feof(fid))
          string = fgetl(fid) 
          fprintf(fidF, '%s', string)
       end
       fclose(fidF);
       fclose(fid);
    end
    

    I've removed the loop from 1:p and used the loop over the number of input files with i as the loop variable. i is used for both the output file name and the index to the input file list.