problem in finding Mean value
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I want to find mean value of a mammogram only by choosing the values greater than zero. I used for loops with condition but it gives 255 as answer constantly. I don't know what's the mistake i have done.
Code:
[x,y] = size(I);
s = 0;
for i = 1:x
for j = 1:y
if I(i,j) > 0
s = s + I(i,j);
end
end
end
disp('s = ');
disp(s);
0 个评论
采纳的回答
Walter Roberson
2013-1-6
Change to
s = s + double(I(i,j));
Question: when you are calculating the mean, are you going to be dividing by the number of values in I, or by the number of non-negative values?
Also are you sure that I will be two-dimensional and not 3 dimensional?
更多回答(2 个)
Image Analyst
2013-1-6
Why are you doing two loops, which will make it slow? Why not just do:
nonZeroPixels = yourImage > 0;
meanValue = mean(yourImage(nonZeroPixels));
The way above is vectorized, faster, and very MATLABish.
0 个评论
Jan
2013-1-6
Alternative method without loops:
s = mean(double(I(I > 0)));
2 个评论
Jan
2013-1-6
Yes, Walter, because the underlying SUM uses the DOUBLE format as default, when 'native' is not specified. I would prefer to let functions reply the same type as the input as default, therefore I tend to cast more often than needed.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!