在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函數,只能用於循環。
在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
'max'是一個內置函數 – Irreducible
好吧,我編輯過,如果你不想使用'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://stackoverflow.com/q/9192507/5358968),[Matlab:如何找到範圍?](https://stackoverflow.com/q/18909268/5358968) – Steve
@SardarUsama是的,我可以使用,如果其他語句,我已經嘗試了很多循環,但似乎無法讓它正常工作 – mathshelp101