reduce for loops number

1 次查看(过去 30 天)
ludovica de gregorio
评论: Ingrid 2015-6-18
I have a code with 3 for loops. I have 365 tiff images, each of which is a matrix 2028x2880 (the pixel value could be 0,1,2,3). For each pixel I have to check all images and find where it assumes the first 1-value. My code (for only 4x4 pixels) is:
f=dir('D:\SCD_02_03\*.tif');
vec=zeros(length(f),1);
for i=1:4 % for loop for checking the firsts 4 rows
for j=1:4 % for loop for checking the firsts 4 column
for idx=1:length(f) % for loop for checking all images
[A,R]=geotiffread(f(idx).name);
vec(idx)=A(i,j,1);
ind=find (vec==1,1);
if ind~=0;
matrix(i,j)=ind; % the result that I want is a matrix 2028x2880 where, for each pixel, I have the index corresponding to the number of the image that satisfies my condition (first 1-value)
else matrix (i,j)=0;
save matrix.mat matrix
end
end
end
end
This code takes about 20 minutes (for only 4x4 pixels), so it's impossible to run it for 2028x2880 pixels!
How could I reduce the number of for loops (for example by eliminating "for i..." and "for j..." loops?)
Thank you

回答(1 个)

Ingrid
Ingrid 2015-6-17
the problem with this code that it needs to read in the whole image each loop, so for each pixel and since it is a large image this takes a while
my first thought was to just read all the images once and store it in one matrix but this was a bad idea since the resulting matrix is 17Gb... however, since you indicate that the values can only be 0,1,2,3 than you might do with uint8 instead of double precision which reduces the required size to 2Gb which is feasible I think. So I would advice to first use a loop to read in all the images and store in one matrix (so be careful to cast to uint8 because otherwise you will get a computer crash as I unfortunately experienced the hard way)
than you do not need a double loop but just a logical indexing to first set all the pixels that are not 1 to zero and than a diff function to see where the change from zero to 1 occurs first.
  4 个评论
Walter Roberson
Walter Roberson 2015-6-18
2028x2880x365 of uint8 is not even 2 GB. if you do not have 2 GB available then you should be switching to 64 bit MATLAB. RAM is not expensive these days.
Ingrid
Ingrid 2015-6-18
indeed that is what I meant, otherwise you will not be able to achieve a speed-up because you are reading 2028x2880x365 data in now for each pixels so of course this will be slow and time consuming

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by