How to write script for multiple files

1 次查看(过去 30 天)
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?

采纳的回答

Walter Roberson
Walter Roberson 2016-7-1
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 个评论
Hosup Song
Hosup Song 2016-7-1
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 2016-7-1
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();

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by