Help improving speed of this code/loop
1 view (last 30 days)
I wrote the code below, which does exactly what I need. Basically, I have several (10.000+) 134x134 matrices (images). For each pixel of each matrix I first need to calculate the average and the standard deviation of the surrounding 8 pixels (removing the central pixel from the calculation). Then I create my Lower and Upper boundaries as the Mean-Std and Mean+Std, respectively. Then, if any, I remove the values of the 8 pixels falling outside these boundaries and I recompute the average. Finally, that average value is placed in a new matrix, at the same position of the central pixel.
Although the code does the job, it takes more than 20 seconds to go through the loop. I need to run it more than 10 thousand times, and it takes ages. Would you be able to suggest an alternative, improved code to make it faster? Perhaps removing the loop, or maybe exploiting some built-in or external function?
Thanks a lot for your help!
A=magic(134); % Assuming this is my 134x134 matrix
keep A background Mtx_Siz ymin ymax xmin xmax
Mathieu NOE on 19 Apr 2023
maybe this runs a bit faster ... my PC is not fast at all , and this loop needs less than 1 s to complete. I am not sure you can do all this in a non for loop code (there could be for loop inside functions anyway).
N = 134;
A=magic(N); % Assuming this is my 134x134 matrix
% some preparation work to ease the for loop job
[r,c] = ind2sub(size(A),1:Mtx_Siz); % create r,c indexes for all pixels
% remove first & last row and col indexes from the list
idr = (r>r(1) & r<r(end));
idc = (c>c(1) & c<c(end));
id = idr & idc;
r = r(id);
c = c(id);
ri = r(i)-1:r(i)+1;
ci = c(i)-1:c(i)+1;
B = B(:); % vector of lenght = 9 , central pixel is at 5th position
B(5) = ;% remove central pixel value