Borrar filtros
Borrar filtros

How to minimize the loop function?

2 visualizaciones (últimos 30 días)
siti
siti el 31 de Oct. de 2014
Editada: Mohammad Abouali el 31 de Oct. de 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)

Respuesta aceptada

Mohammad Abouali
Mohammad Abouali el 31 de Oct. de 2014
Editada: Mohammad Abouali el 31 de Oct. de 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 comentarios
siti
siti el 31 de Oct. de 2014
ohh..thanks a lot..but can i minimize looping without using hist function?
Mohammad Abouali
Mohammad Abouali el 31 de Oct. de 2014
Editada: Mohammad Abouali el 31 de Oct. de 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);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by