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的零的总数。 我如何在matlab中编写代码
答案 0 :(得分:3)
max(diff(find(diff(Grid_outage))))
diff
find
diff
来计算每个"转换" max
以获取最大的连续数字序列。请注意,如果最大的序列出现在边缘,则可能会遇到问题,在这种情况下,我建议您先添加并向您的矩阵附加一个倒置位,如下所示:[1-Grid_outage(1), Grid_outage, 1-Grid_outage(end)];
答案 1 :(得分:3)
为了透明的目的,这是一个非常简单的算法。
假设您可以将序列放在向量X:
中% 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个元素开始提高效率。
答案 2 :(得分:1)
为了查找参数x
在序列中一起出现的次数,您可以使用:
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;