How to avoid this for loops to improve computation time

1 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2017-2-4
编辑:Guillaume 2017-2-4
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 个评论
Gopichandh Danala
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Feature Detection and Extraction 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by