Reading file with variable name

15 Ansichten (letzte 30 Tage)
PIYUSH MOHANTY
PIYUSH MOHANTY am 2 Apr. 2019
Kommentiert: Stephen23 am 2 Apr. 2019
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 Kommentare
Adam
Adam am 2 Apr. 2019
If the variable contains your filename then just use it without "
What happened when you did that instead?
Stephen23
Stephen23 am 2 Apr. 2019
There are basically two ways to process a sequence of files, and the MATLAB documentation gives examples for both of them:

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

the cyclist
the cyclist am 2 Apr. 2019
Bearbeitet: the cyclist am 2 Apr. 2019
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 Kommentar
PIYUSH MOHANTY
PIYUSH MOHANTY am 2 Apr. 2019
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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by