MATLAB Answers


Reading file with variable name

Asked by PIYUSH MOHANTY on 2 Apr 2019
Latest activity Commented on by Stephen Cobeldick on 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?


If the variable contains your filename then just use it without "
What happened when you did that instead?
There are basically two ways to process a sequence of files, and the MATLAB documentation gives examples for both of them:

Sign in to comment.

1 Answer

Answer by the cyclist
on 2 Apr 2019
Edited by the cyclist
on 2 Apr 2019

for n = 1:16
filename = sprintf('PPT%d.TXT',n)
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 Comment

Hi The Cyclist,
Thanks for your answer,
My code looks something like this:
rootdir= 'D:\IEM\TEST1-IEM\Analysis of results';
fid = fopen(fullfile(rootdir,relativefolder,'Time.txt'));
T = textscan(fid,'%f');
fileid = fopen(fullfile(rootdir,relativefolder,subfolder,'ppt.txt'));
ylabel('Pore Pressure');
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)]);
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?

Sign in to comment.