查找MATLAB
问题描述:
在Vector中第一个最长的连续组1周的的我在MATLAB以下向量:查找MATLAB
[1 0 1 1 1 0 0 1 1 0 1 1 1]
我希望能够找到最长连续集1的(的所以在这种情况下,将是3),然后打印出现该集合的索引(3
和5
)。
在这种情况下,1 1 1
显示了两次,我希望它确保它打印第一组的位置的索引。
我可以使用什么编码 - 但不使用任何内置的matlab函数,只能用于循环。
答
这里是没有内置函数中的溶液。我知道你需要第一个最长序列的开始和结束的索引。
data=[1 0 1 1 1 0 0 1 1 0 1 1 1];
x=[data 0];
c=0;
for k=1:length(x)
if x(k)==1
c=c+1;
else
ind(k)=c;
c=0;
end
end
a=ind(1);
for k=2:length(ind)
if ind(k)>a
a=ind(k);
b=k;
end
end
Ones_start_ind=b-a
Ones_end_ind=b-1
% results:
Ones_start_ind =
3
Ones_end_ind =
5
+0
'max'是一个内置函数 – Irreducible
+0
好吧,我编辑过,如果你不想使用'max' – Adiel
答
在这里的实施方式,而不MATLAB函数:
%Example Vector
V=[1 0 1 1 1 0 0 1 1 1 0 1 1 0 1 1 1 0] ;
%calculate the diff of input
diff_V=V(2:end)-V(1:end-1);
N=length(diff_V);
% prepare start and end variables
start_idx=[]; end_idx=[];
%loop to find start and end
for kk=1:N
if diff_V(kk)==1 %starts with plus
start_idx=[start_idx kk+1];
end
if diff_V(kk)==-1 %ends with minus
end_idx=[end_idx kk];
end
end
% check if vector starts with one and adapt start_idx
if start_idx(1)>end_idx(1)
start_idx=[1 start_idx];
end
% check if vector ends with one and adapt end_idx
if start_idx(end)>end_idx(end)
end_idx=[end_idx length(V)];
end
%alloc output
max_length=0;
max_start_idx=0;
max_end_idx=0;
%search for start and length of longest epoch
for epoch=1:length(start_idx)
epoch_length=end_idx(epoch)-start_idx(epoch)+1;
if epoch_length> max_length
max_length=epoch_length;
max_start_idx=start_idx(epoch);
max_end_idx=end_idx(epoch);
end
end
输出
max_length =
3
max_start_idx =
3
max_end_idx =
5
是'if else'不允许吗?你有尝试过什么吗? –
相关问题:[分析序列matlab](https://*.com/q/9192507/5358968),[Matlab:如何找到范围?](https://*.com/q/18909268/5358968) – Steve
@SardarUsama是的,我可以使用,如果其他语句,我已经尝试了很多循环,但似乎无法让它正常工作 – mathshelp101