# reduce for loops number

1 view (last 30 days)
ludovica de gregorio on 17 Jun 2015
Commented: Ingrid on 18 Jun 2015
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
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

Ingrid on 17 Jun 2015
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.
Ingrid on 18 Jun 2015
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