lowering computaional cost in finding the location of minimum distance

54 Views Asked by At

I am using MATLAB for the calibration model of the monitor... I need to find the values as follow

for a1 = 1:s1
for j = 1:s2
    c=0;
for i = 1:257;
    if ((XYZ1(a1,j,1)-r1(1,i))<0.5)
        rgb(a1,j,1) = a(i);
        c=c+1;
        break;
    end
end

if ((c ==0)|(rgb>255))
    rgb(j,1)=255;
end
c=0;
for i = 1:257;
    if ((XYZ1(a1,j,2)-r1(2,i))<0.5)
        rgb(a1,j,2) = a(i);
        c=c+1;
        break;
    end
end


if ((c ==0)|(rgb>255))
    rgb(a1,j,2)=255;
end
c=0;

for i = 1:257;
    if ((XYZ1(a1,j,3)-r1(3,i))<0.5)
        rgb(a1,j,3) = a(i);
        c=c+1;
        break;
    end
end
if ((c ==0)|(rgb>255))
    rgb(a1,j,3)=255;
    c=c+1;
end

end
a1
end

My code is working very fine and results are v good... But the only issue is computational cost since size of XYZ1 is 2448x2048x3 so these three loops with if conditions are taking lot of time. I need help to reduce the computational cost. Basically these three loops are causing the delay

for i = 1:257;
    if ((XYZ1(a1,j,1)-r1(1,i))<0.5)
        rgb(a1,j,1) = a(i);
        c=c+1;
        break;
    end
end

if ((c ==0)|(rgb>255))
    rgb(j,1)=255;
end
c=0;
for i = 1:257;
    if ((XYZ1(a1,j,2)-r1(2,i))<0.5)
        rgb(a1,j,2) = a(i);
        c=c+1;
        break;
    end
end


if ((c ==0)|(rgb>255))
    rgb(a1,j,2)=255;
end
c=0;

for i = 1:257;
    if ((XYZ1(a1,j,3)-r1(3,i))<0.5)
        rgb(a1,j,3) = a(i);
        c=c+1;
        break;
    end
end
if ((c ==0)|(rgb>255))
    rgb(a1,j,3)=255;
    c=c+1;
end

Any suggestions will be highly appreciated

1

There are 1 best solutions below

2
On BEST ANSWER

You can use logical indexing or find instead of your loops. So instead of

c = 0;
for i = 1:257;
    if ((XYZ1(a1,j,1)-r1(1,i))<0.5)
        rgb(a1,j,1) = a(i);
        c=c+1;
        break;
    end
end

you can:

c   = find((XYZ1(a1,j,1)*ones(1,257) - r1(1,1:257)) > 0.5, 1, 'last');
if (~isempty(c))
    rgb(ai,j,1) = a(c-1);
else
    c = 0;
end