Speeding up matrix comparison within a loop (logical indexing???)

1 view (last 30 days)
At the moment as part of a larger programme I have the following code, however it takes a 10s of minutes to run. I've seen people on these forums reference something called "logical indexing" that removes the need for the loop however googling logical indexing I couldn't figure out quite what it is or how it works.
for i=2:12
sizeOfIm=size(squeeze(imlab50(i,:,:,:)));
outputIm=zeros(sizeOfIm(1),sizeOfIm(2),sizeOfIm(3));
outputIm(:,:,:)=squeeze(imlab50(i,:,:,:));
outputIm=uint8(outputIm);
for loopy = 1 : sizeOfIm(1)
for loopx = 1:sizeOfIm(2)
if (squeeze((backGrndColour(i,:)).'-mindif(:))>squeeze(imlab50(i,loopy,loopx,:)))
if (squeeze(backGrndColour(i,:)).'-maxdif(:) <squeeze(imlab50(i,loopy,loopx,:)))
outputIm(loopy,loopx,:)=0;
end
end
end
end
In short how do I do the following comparison for every value in the matrices, without having three serperate nested loops that vary i, loopy, and loopx?
if (squeeze((backGrndColour(i,:)).'-mindif(:))>squeeze(imlab50(i,loopy,loopx,:)))

Answers (2)

Sara
Sara on 27 Jan 2015
Without having any data to test it, I'd say you could do:
for i=2:12
x = squeeze(imlab50(i,:,:,:));
outputIm=uint8(x);
[j,k] = find(squeeze((backGrndColour(i,:)).'-mindif(:)) > x);
outputIm(j,k,:) = 0;
end
In the find, check if it should be x or outputIm.
  1 Comment
Andriy Boubriak
Andriy Boubriak on 27 Jan 2015
I got the followng error
"Error using > Number of array dimensions must match for binary array op.
Error in locator (line 32) [j,k] = find(squeeze((backGrndColour(i,:)).'-mindif(:)) > x);"

Sign in to comment.


Image Analyst
Image Analyst on 27 Jan 2015
What is imlab50? Is it a uint8 video?
And this code:
outputIm=zeros(sizeOfIm(1),sizeOfIm(2),sizeOfIm(3));
outputIm(:,:,:)=squeeze(imlab50(i,:,:,:));
outputIm=uint8(outputIm);
can most likely be replaced with this to save some time possibly.
outputIm = uint8(squeeze(imlab50(i,:,:,:)));
Another thing - you made a very common error, getting x and y wrong. You're calling the first index x and the second one y - that's wrong. The first index is the row index and thus should be y not x, and the second index is the column and thus should be called x, not y.
  3 Comments
Image Analyst
Image Analyst on 28 Jan 2015
If imlab50 is a CIELAB color space image, why does it have 4 dimensions? Is it CMYK or something???

Sign in to comment.

Categories

Find more on Data Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!