필터 지우기
필터 지우기

How to minimize the loop function?

조회 수: 2 (최근 30일)
siti
siti 2014년 10월 31일
편집: Mohammad Abouali 2014년 10월 31일
hello,,i need to simplify this coding,maybe by minimizing only one loop..i really don't know how to do it..please help me asap.
function S = IraHistFunction (im)
I = imread ('lena.jpg'); [m,n] = size (I); S = zeros (256, 1);
for GrayValue = 0 : 255
for i = 1 : m
for j = 1 : n
if I(i,j) == GrayValue
S(GrayValue+1) = S(GrayValue+1) + 1 ;
end
end
end
end
figure, bar(S)

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 10월 31일
편집: Mohammad Abouali 2014년 10월 31일
Change
for GrayValue = 0 : 255
for i = 1 : m
for j = 1 : n
if I(i,j) == GrayValue
S(GrayValue+1) = S(GrayValue+1) + 1 ;
end
end
end
end
to a single line as follow:
n=hist(I(:),0:255);
You can then plot it as follow:
bar(0:255,n);
  댓글 수: 2
siti
siti 2014년 10월 31일
ohh..thanks a lot..but can i minimize looping without using hist function?
Mohammad Abouali
Mohammad Abouali 2014년 10월 31일
편집: Mohammad Abouali 2014년 10월 31일
If you insist on not using * hist * you can do it this way:
change this:
for GrayValue = 0 : 255
for i = 1 : m
for j = 1 : n
if I(i,j) == GrayValue
S(GrayValue+1) = S(GrayValue+1) + 1 ;
end
end
end
end
to a code with only one loop as
for GrayValue = 0 : 255
S(GrayValue+1)=sum(I(:)==GrayValue);
end
or even shorter without any loop as
S=arrayfun(@(x) (sum(I(:)==x)), 0:255);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by