matlab max/min/median函式用法以及自定義函式求最大最小值和中位數
題目:
1. 用matlab內建函式max, min, median求取B的最大,最小和中位數的值,儲存在相應的變數。
2. 自定義函式求取某個影象矩陣的最大,最小和中位數的值,儲存在相應的變數。
函式原型為function [maxVale, minValue, meanValue, medianValue] = FindInfo(oriIm);
3. 比較用matlab內建函式求得的各值與自定義函式返回值大小,用if-else結構輸出比較結果。
程式碼:
1. 主函式部分
2. 自定義函式部分maxB = max(max(B)) minB = min(min(B)) meanB = mean(mean(B)) medianB = median(B(:)) [maxValue, minValue, meanValue, medianValue] = FindInfo(B) % compare my computed four statistics with the four statistics obtained from the Matlab built-in functions disp('results of comparison: ') if maxB == maxValue disp('max : same ') end if minB == minValue disp('min : same ') end if meanB == meanValue disp('mean : same ') end if medianB == medianValue disp('median : same ') end
function [maxValue, minValue, meanValue, medianValue] = FindInfo(oriIm) % calculate the maximum, minimum, mean, and median intensity value of a grayscale input image A = double(oriIm); % change oriIm to double B = sort(A(:)); % to calculate median value of oriIm [row,col] = size(A); num = row * col; % total number of elements in A % initiate sum, max and min sum = 0; maxValue = B(end); minValue = B(1); %The max and min values should be B(end) and B(1), so there is no need for loop. % for i = 1 : num-1 % sum = sum + A(i); % sum needs to add the last element % if A(i) < A(i+1) % if maxValue < A(i+1) % maxValue = A(i+1); % get max % end % if minValue > A(i) % minValue = A(i); % get min % end % end % end sum = sum + A(num); meanValue = sum / num; % get mean % calculate medain if num/2 == 0 medianValue = (B(num/2)+B(num/2+1))/2; else medianValue = B(num/2); end
值得注意的地方:
1. 對於灰度影象使用max/min/dedian 函式的時候要巢狀兩層,比如maxB = max(max(B))和meanB = mean(mean(B)),這是因為maxB = max(B)求的是每一行的最大值,返回的是一個列向量(一列數字,分別是每一行的最大值),再加一層max函式即可得到整個B的最大值。
2. median函式的正確使用方法:
注意區分medianB = median(B(:))以及 median(median(B))。
根據第一條提到的,median(median(B))得到的是列向量的中位數,它是把一列數字求中位數,舉個例子比如一列有10個數,這種寫法會把第5和第6個加起來求平均值,得不到我們題目要求的整個矩陣的中位數。所以應該這麼寫:medianB = median(B(:))這句話的意思是在整個B所有行和列中取中值。冒號表示所有元素。
3. 在博主的自定義函式中,求取最大最小值的for迴圈是沒有必要的。這是助教給我改完作業的批註: The max and min values should be B(end) and B(1), so there is no need for loop. 翻譯是:B的最大最小值為B(end) 和 B(1),所以for迴圈是不必要的。這個for迴圈求最大最小值的演算法是博主在高階演算法課程中學到的,是運用線性掃描求陣列最值的演算法, 使得比較的次數最小化。