Clear Filters
Clear Filters

How to write script for multiple files

1 view (last 30 days)
so I have my files named 'abcd001' ~ 'abcd999' I'm trying to write a script using for loop to perform some function on these files. How do I write the code so that it will automatically read each file? I thought about doing something like
for i = 1:999
TIFFdata=Tiff('abcd'num2str(i)'.tif','r');
firstlevelTIFF'i'=TIFFdata.read();TIFFdata.nextDirectory();
secondlevelTIFF'i'=TIFFdata.read();TIFFdata.nextDirectory();
thirdlevelTIFF'i'=TIFFdata.read();
end
but that wouldn't work because it would become 'abcd1' instead of the needed 'abcd001'.
How do I maintain the three digit form for this code?

Accepted Answer

Walter Roberson
Walter Roberson on 1 Jul 2016
thisfile = sprintf('abcd%03d.tif', i);
TiffDta = Tiff(thisfile, 'r');
firstlevelTIFF{i} = TIFFData.read(); TIFFdata.nextDirectory();
secondlevelTIFF{i} = TIFFData.read(); TIFFdata.nextDirectory();
thirdlevelTIFF{i} = TIFFData.read();
  2 Comments
Hosup Song
Hosup Song on 1 Jul 2016
why do i need the thisfile part? is there a way to incorporate the %03d into the first line of the code?
Walter Roberson
Walter Roberson on 1 Jul 2016
Using a variable makes it easier to read, and also makes it easier to issue error messages because in your real code you would have put in a try/catch in case opening the file failed. But it is not strictly necessary.
TiffDta = Tiff(sprintf('abcd%03d.tif', i), 'r');
firstlevelTIFF{i} = TIFFData.read(); TIFFdata.nextDirectory();
secondlevelTIFF{i} = TIFFData.read(); TIFFdata.nextDirectory();
thirdlevelTIFF{i} = TIFFData.read();

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!