MATLAB: How to avoid this for loops to improve computation time

for loopimage processing

In this code, I have a cluster image with 10 classes and i want to extract 10 different images for each level and save as a 10 images Below is the code, I used
tic
numberOfClasses = 10;
segment_label_images = cell(1,numberOfClasses);
pixelCount = zeros(1,numberOfClasses);
[rs, cs] = size(classImage);
% classImage has intensity range from 1-numberOfClasses
for k = 1:numberOfClasses
for i = 1:rs
for j = 1:cs
if classImage(i,j) == k
segment_label_images{k}(i,j) = 1;
else
segment_label_images{k}(i,j) = 0;
end
end
end
pixelCount(k) = sum(segment_label_images{k}(:));
%figure, imshow(segment_label_images{k},[]);
end
toc
Here, I have 3 for loops and I think that is affecting computational time. Elapsed time is 0.089413 seconds.
Any suggestions to avoid for loop to improve comp time.? Thanks, Gopi

Best Answer

First issue: you've predeclared segment_label_images and pixelCount however, you don't predeclare the matrices in each cell of segment_label_images, so these grow at each step of the i and j loops.
Workaround: before the i loop:
for k = 1:numerofClasses
segment_label_images{k} = zeros(size(classImage));
for i = 1:rs
%...
However, there's no point in the i and j loop, and thus actually no need to predeclare the matrices:
for k = 1:numberofClasses
segment_label_images{k} = classImage == k;
pixelcount(k) = sum(segment_label_images{k}(:));
figure;
imshow(segment_label_images{k}); %no need for []
end
If you need the segment_label_images, there's no way to avoid the k loop (or arrayfun). If you only need pixelCount, then:
pixelCount = histogram(classimage, 1:NumberOfClasses, 'BinMethod', 'integers')