How can I vectorize these while and nested for loops in MATLAB?

I am trying to vectorize the following code. My program takes quite a while to complete the result. For this reason, I want to vectorize my while loop. Can you vectorize it or do you have another idea of ​​what I should do?

Here I take the average of the neighboring pixels and repeat the loop until an approximate result is obtained:

n = 500;
Mat_new = rand(n); 
error = 1;
while error > 0.000001
    Mat_Old = Mat_new;
    for i = 2:n-1
        for j = 2:n-1
            Mat_new(i,j) =abs((2+((Mat_Old(i+1,j)+Mat_Old(i-1,j)+Mat_Old(i,j+1)+Mat_Old(i,j-1))))/(4));
        end
    end
    error =max(max(abs(Mat_Old-Mat_new)));
end
+4
source share
1 answer

, , 2D-. , . : , , , , . , 3 x 3, , imfilter conv2, . , , 1 , , conv2. (yuck), ( ), , , 2, , 4.

, :

n = 500;
Mat_new = rand(n); 
error = 1;
h = [0 1 0; 1 0 1; 0 1 0]; % // Define filter here
while error > 0.000001
    Mat_Old = Mat_new;

    Mat_new = conv2(Mat_Old, h, 'valid');
    Mat_new = abs(Mat_new + 2) / 4; %//Take the output, add 2, absolute then divide by 4
    %// Pad border with zeroes
    Mat_new = padarray(Mat_new, [1 1]);

    error = max(abs(Mat_Old(:) - Mat_new(:))); %// Calculate maximum error
end

, , for. , conv2. Mat_new , , for. , abs 2 , 4. , padarray. , error, max. , .

, while ( ...) . . - .... while. , for , .

, , , !

+1

All Articles