Filter löschen
Filter löschen

How to minimize the loop function?

2 Ansichten (letzte 30 Tage)
siti
siti am 31 Okt. 2014
Bearbeitet: Mohammad Abouali am 31 Okt. 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)

Akzeptierte Antwort

Mohammad Abouali
Mohammad Abouali am 31 Okt. 2014
Bearbeitet: Mohammad Abouali am 31 Okt. 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 Kommentare
siti
siti am 31 Okt. 2014
ohh..thanks a lot..but can i minimize looping without using hist function?
Mohammad Abouali
Mohammad Abouali am 31 Okt. 2014
Bearbeitet: Mohammad Abouali am 31 Okt. 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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by