在不增加y数据的情况下更新for循环中的直方图

时间:2018-07-03 15:17:14

标签: matlab histogram

我在网站上的其他地方都找不到运气,所以这是我的问题。我遍历了大约一千个Mat文件,每个文件包含约10,000个数据点。我正在尝试创建此数据的整体直方图,但是将所有这些数据连接到hist并不是很可行。

我希望能够使用hist(y)在每个循环中创建N和Bin变量,然后在下一次循环迭代中使用hist(y_new)重新计算N和Bin。等等等等。这样,源数据就不会增长,并且当循环最终结束时,我可以只使用bar()。如果这种方法行不通,那么我会对其他解决方案持开放态度。

此外,假设x数据在每次迭代中保持恒定可能也是不安全的。我正在使用2012a。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为这里最好的解决方案是循环浏览文件两次:一次设置垃圾箱,一次进行直方图。但是,如果在您的情况下这不可能,那么这是一种一次性解决方案,要求您事先设置纸槽宽度。

clear; close all;
rng('default') % for reproducibility

% make example data
N = 10; % number of data files
M = 5; % length of data files
xs = cell(1,N);
for i = 1:N
    xs{i} = trnd(1,1,M);
end

% parameters
width = 2;

% main
for i = 1:length(xs)
    x = xs{i}; % "load data"
    range = [min(x) max(x)];
    binsPos = 0:width:range(2)+width;
    binsNeg = fliplr( 0:-width:range(1)-width );
    newBins = [binsNeg(1:end-1) binsPos];
    newCounts = histc(x, newBins);
    newCounts(end) = []; % last bin should always be zero, see help histc

    if i == 1
        counts = newCounts;
        bins = newBins;
    else
        % combine new and old counts
        allBins = min(bins(1), newBins(1)) : width : max(bins(end), newBins(end));
        allCounts = zeros(1,length(allBins)-1);
        allCounts(find(allBins==bins(1)) : find(allBins==bins(end-1))) = counts;
        allCounts(find(allBins==newBins(1)) : find(allBins==newBins(end-1))) = ...
            allCounts(find(allBins==newBins(1)) : find(allBins==newBins(end-1)))  + newCounts;

        bins = allBins;
        counts = allCounts;
    end
end

% check
figure
bar(bins(1:end-1) + width/2, counts)

xFull = [xs{:}];
[fullCounts] = histc(xFull, bins);
fullCounts(end) = [];
figure
bar(bins(1:end-1) + width/2, fullCounts)
相关问题