首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算重复出现的元素的最大数量?

如何计算重复出现的元素的最大数量?
EN

Stack Overflow用户
提问于 2014-07-21 11:25:49
回答 3查看 144关注 0票数 1
代码语言:javascript
复制
Grid_outage(:,1) = 1;
Grid_outage(:,2) = 1;
Grid_outage(:,3) = 1;
Grid_outage(:,4) = 0;
Grid_outage(:,5) = 0;
Grid_outage(:,6) = 0;
Grid_outage(:,7) = 0;
Grid_outage(:,8) = 0;
Grid_outage(:,9) = 0;
Grid_outage(:,10) = 0;
Grid_outage(:,11) = 0;
Grid_outage(:,12) = 1;
Grid_outage(:,13) = 0;
Grid_outage(:,14) = 1;
Grid_outage(:,15) = 0;
Grid_outage(:,16) = 0;
Grid_outage(:,17) = 1;
Grid_outage(:,18) = 0;
Grid_outage(:,19) = 1;
Grid_outage(:,20) = 0;
Grid_outage(:,21) = 0;
Grid_outage(:,22) = 0;
Grid_outage(:,23) = 1;
Grid_outage(:,24) = 0;

我想计算一个序列中出现的最大零点数,例如,上面的结果是8,它显示了一起发生的最大零数,而不是总零数为16。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-07-21 11:34:35

为了提高透明度,一个非常简单的algoritm。

假设您可以将序列放在向量X中:

代码语言:javascript
复制
% Create X containing some zeros.
X = round(rand(30,1));

% Use a counter to count the number of sequential zeros.
count = 0;
% Use a variable to keep the maximum.
max_count = 0;

% Loop over every element
for ii=1:length(X);
    % If a zero is encountered increase the counter
    if(X(ii)==0)
        count=count+1;
    % If no zero is encountered check if the number of zeros in the last sequence was largest.
    elseif count>max_count
        max_count=count;
        count=0;
    % Else just reset the counter
    else
        count=0;
    end
end
% Check if the last number of the vector exceeded the largest sequence.
if(count>max_count)
   max_count=count;
end

编辑:Dan的解决方案从大约200个元素开始,效率更高。

票数 3
EN

Stack Overflow用户

发布于 2014-07-21 11:32:09

代码语言:javascript
复制
max(diff(find(diff(Grid_outage))))
  1. 使用diff查找连续数字序列更改的位置
  2. 使用find获取发生这种情况的实际索引号
  3. 再次使用diff来计算每个“转换”之间的元素数
  4. 最后,调用max以获得最大的连续数序列。

请注意,如果最大的序列发生在边缘,那么您可能会遇到麻烦,在本例中,我建议您首先在矩阵中添加一个倒置位,如:[1-Grid_outage(1), Grid_outage, 1-Grid_outage(end)];

票数 3
EN

Stack Overflow用户

发布于 2014-07-21 11:53:54

为了找出参数x在一个序列中一起发生的次数,可以使用:

代码语言:javascript
复制
if a(:) == x
    result = length(a); % Whole vector has the x parameter
else
    result = max(find(a~=x,1,'first') - 1, length(a) - find(a~=x,1,'last')); % Maximum difference in the edge   
    if ~isempty(max(diff(find(a~=x))) - 1)
        if isempty(result)
            result = max(diff(find(a~=x))) - 1; % Maximum difference in the body
        elseif result < max(diff(find(a~=x))) - 1
            result = max(diff(find(a~=x))) - 1; % Maximum difference in the body
        end;
    end;
end;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24863920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档