How to avoid this for loops to improve computation time

조회 수: 1 (최근 30일)
Gopichandh Danala
Gopichandh Danala 2017년 2월 3일
댓글: Gopichandh Danala 2017년 2월 5일
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
Gopichandh Danala 2017년 2월 5일
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에서 Images에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by