Effacer les filtres
Effacer les filtres

How to minimize the loop function?

2 vues (au cours des 30 derniers jours)
siti
siti le 31 Oct 2014
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)

Réponse acceptée

Mohammad Abouali
Mohammad Abouali le 31 Oct 2014
Modifié(e) : Mohammad Abouali le 31 Oct 2014
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 commentaires
siti
siti le 31 Oct 2014
ohh..thanks a lot..but can i minimize looping without using hist function?
Mohammad Abouali
Mohammad Abouali le 31 Oct 2014
Modifié(e) : Mohammad Abouali le 31 Oct 2014
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);

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by