Reading file with variable name

조회 수: 17 (최근 30일)
PIYUSH MOHANTY
PIYUSH MOHANTY 2019년 4월 2일
댓글: Stephen23 2019년 4월 2일
In the folder I have TEXT files named as PPT1.TXT, PPT2.TXT,PPT3.TXT...., PPT16.TXT. I want to read these files and do some operations like, adding one more column and then save to a new location with same name as PPT1.TXT, PPT2.TXT.... I wish to use a variable for naming these files and do the operation on them as I can just change the name of the variable at one place in the code and the code should should be able to read the correct desired file(PPT1.TXT) and write to the file with the desired name(PPT1.TXT).
But if I put the variable name inside '' (apostropes) in textscan and fprintf commands, it throws error.
Can you please help me with this?
  댓글 수: 2
Adam
Adam 2019년 4월 2일
If the variable contains your filename then just use it without "
What happened when you did that instead?
Stephen23
Stephen23 2019년 4월 2일
There are basically two ways to process a sequence of files, and the MATLAB documentation gives examples for both of them:

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

채택된 답변

the cyclist
the cyclist 2019년 4월 2일
편집: the cyclist 2019년 4월 2일
for n = 1:16
filename = sprintf('PPT%d.TXT',n)
end
That loop creates the filenames you need, with the '%d' in the sprintf command taking the values of n from the loop.
When you use the filename, don't enclose it in quotes. It is already a character array.
  댓글 수: 1
PIYUSH MOHANTY
PIYUSH MOHANTY 2019년 4월 2일
Hi The Cyclist,
Thanks for your answer,
My code looks something like this:
rootdir= 'D:\IEM\TEST1-IEM\Analysis of results';
relativefolder='0.08g';
fid = fopen(fullfile(rootdir,relativefolder,'Time.txt'));
Ttext=textscan(fid,'%s',1);
T = textscan(fid,'%f');
Time=T{1,1};
subfolder='PPT';
ppt=PPT1;
fileid = fopen(fullfile(rootdir,relativefolder,subfolder,'ppt.txt'));
A1text=textscan(fileid,'%s',1);
A1=textscan(fileid,'%f');
Pp=A1{1,1};
figure()
plot(Time,Pp);
xlabel('Time');
ylabel('Pore Pressure');
legend('0.08g-ppt','location','northwest');
fileid1 = fopen('D:\IEM\TEST1-IEM\Analysis of results\0.08g\PPT\Time Vs Pore Pressure\ppt.txt','w');
fprintf(fileid1,'%6s %12s \r\n','Time',' Pore pressure');
fprintf(fileid1,'%f %f\r\n', [transpose(Time);transpose(Pp)]);
fclose('all');
clear
If you see in this code, I read the content from one PPT1.TXT file and want to write to file PPT1.TXT at another location with appending one column.
It throws error as this may not eb the right way of using the variable for file name.
Can you please help?

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

추가 답변 (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