How to read several text files in a loop

조회 수: 15 (최근 30일)
Homayoon
Homayoon 2015년 8월 27일
댓글: shah nawaz 2020년 6월 12일
Hello Guys, I have a problem that I cannot understand how fopen, fid and other similar syntax are working. But I know I have to seek for the answer to my question around them :-)
Well, here is my question. Assume I have 10 text files with filenames of 1.txt , 2.txt, 3.txt and etc. I have a code which perfectly works for each single filename. However, I need to run the code 10 times seperately to do my desired calculations for these 10 files. Is there any way to run the code for once and it starts loading each file working through it and then goes to the next file?
For the time being, I wrote my code in this order which is of course so annoying:
filename = '1.txt';
A = load (filename);
% doing some calculations
print the output for 1.txt
clear
clc
filename = '2.txt';
A = load (filename);
% doing some calculations
print the output for 2.txt
clear
clc
filename = '3.txt';
A = load (filename);
% doing some calculations
print the output for 3.txt
Thank you in advanced.

채택된 답변

Stephen23
Stephen23 2015년 8월 27일
편집: Stephen23 2015년 8월 27일
Processing a sequence of file is comprehensively explained in the wiki, together with example code: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
Basically you need to do something like this (pseudocode):
for k = 1:10
filename = sprintf('%d.txt',k);
A = load(filename);
% doing some calculations
print the output for k.txt
end
  댓글 수: 3
belkhir settou
belkhir settou 2019년 2월 2일
did you find the solution please send it to me
i have the same problem :'(
shah nawaz
shah nawaz 2020년 6월 12일
use the import tool. it will help you create function file and then you can call the function whenever u want

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by