How to avoid this for loops to improve computation time

1 view (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 4 Feb 2017
Edited: Guillaume on 4 Feb 2017
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')
  1 Comment
Gopichandh Danala
Gopichandh Danala on 5 Feb 2017
Thanks for the detailed explanation, I need the segment_label_images so, I can avoid 'i,j' for loops and improve a lot of time.

Sign in to comment.

More Answers (0)

Categories

Find more on Images 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!