题目
来源于Mathwork上的Cody,Problem 672 - Longest run of consecutive numbers.
Given a vector a, find the number(s) that is/are repeated consecutively most often. For example, if you have
a = [1 2 2 2 1 3 2 1 4 5 1]
The answer would be 2, because it shows up three consecutive times.
If your vector is a row vector, your output should be a row vector. If your input is a column vector, your output should be a column vector. You can assume there are no Inf or NaN in the input. Super (albeit non-scored) bonus points if you get a solution that works with these, though.
代码
function val=longrun(a)
A(1,1)=a(1);%第一列记录出现的元素
A(1,2)=1;%第二列记录该元素连续出现的次数
j=1;
for i=2:length(a)
if a(i)==a(i-1)
A(j,2)=A(j,2)+1;%连续出现,第二列+1
else %新元素出现,对A的第j行初始化
j=j+1;
A(j,1)=a(i);
A(j,2)=1;
end
end
Num=A(:,1);
L=A(:,2);
if size(a,1)-size(a,2)>=0%使输入和输出同为行向量或

该博客介绍了一道MATLAB编程题——找出数组中连续重复最多的数字。例如,给定数组a=[1 2 2 2 1 3 2 1 4 5 1],答案是2,因为它连续出现了三次。文中提供了代码实现及验证过程。
最低0.47元/天 解锁文章
5992

被折叠的 条评论
为什么被折叠?



