matlab統計 頻數、頻率和累積頻率

lhbbzh發表於2017-11-19
function result = HistRate(x)
  HistRate(x),統計陣列 x 中的元素出現的頻數、頻率和累積頻率,以表格形式顯示在螢幕上.
  x可以是數值型陣列、字串、字元型陣列、字串元胞陣列和名義尺度陣列。
%
  result = HistRate(x),返回矩陣或元胞陣列result,它是多行4列的矩陣或元胞陣列,
  四列分別對應取值、頻數、頻率、累積頻率。當x是數值型陣列時,result為矩陣;當x
  是字串、字元型陣列、字串元胞陣列和名義尺度陣列時,result為元胞陣列。
%
  使用者還可參考tabulate函數,該函式比tabulate函數的效率高
 
  Copyright xiezhh,2010.3.8
if isnumeric(x)
    x = x(:);
    x = x(~isnan(x));
    xid = [];
else
    [x,xid] = grp2idx(x);
    x = x(~isnan(x));
end
x = sort(x(:));    % 排序
m = length(x);
x1 = diff(x);    % 求差分
x1(end + 1) = 1;
x1 = find(x1);
CumFreq = x1/m;
value = x(x1);
x1 = [0; x1];
Freq1 = diff(x1);
Freq2 = Freq1/m;
if  nargout == 0
    if isempty(xid)
        fmt1 = 's   %8s   %6s    %6sn';
        fmt2 = '  d     �     %6.2f%%     %6.2f%%n';
        fprintf(1, fmt1, '取值', '頻數', '頻率', '累積頻率');
        fprintf(1, fmt2, [value'; Freq1'; 100*Freq2'; 100*CumFreq']);
    else
        head = {'取值', '頻數', '頻率(%)', '累積頻率(%)'};
        [head;xid,num2cell([Freq1, 100*Freq2, 100*CumFreq])]
    end
else
    if isempty(xid)
        result = [value Freq1 Freq2 CumFreq];
    else
        result = [xid,num2cell([Freq1, Freq2, CumFreq])];
    end
end


如何統計一個陣列中各數字(元素)出現的頻數、頻率和累積頻率?這裡以案例形式做一個總結。
第一種方法:呼叫MATLAB自帶的函式tabulate統計一個陣列中各數字(元素)出現的頻數、頻率
【例1】統計數值型陣列中各元素出現的頻數、頻率。
>> x = [2                 2
                      5
                      5];
>> tabulate(x(:))
  Value    Count   Percent
        <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>

相關文章