我有一个1s和0s的二进制向量。我想找到一个函数范围/数字岛1。 例如:x = 0001111001111111000110 ... 我需要这样的答案:4-7(或4 5 6 7),10-16,20-21 ...... 谢谢你的帮助!
答案 0 :(得分:1)
在原始数组的两端添加零可保证偶数个转换(从0到1开始,从1到0结束)然后它基本上是diff
的问题并且微调输出
x = [0 0 0 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0];
% how to make that out from a string xx="0001111001111111000110" is left
% as an exercise
y = [0 x 0]; % make sure x="11"; has proper amount of transitions
R = 1:length(y)-1; % make an array of indices [1 2 3 4 5 ... end-1]
F = R(y(2:end) != y(1:end-1)); % finds the positions [4,8,10,17,20,22]
start_pos = F(1:2:end-1); % gets 4,10,20
end_pos = F(2:2:end)-1; % gets 7,16,21 adjusted
免责声明:未经测试。
答案 1 :(得分:1)
Aki解决方案的变体(未经过大量测试):
x = [0 0 0 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0];
dx = diff([0, x, 0]);
start_pos = find(dx == 1);
end_pos = find(dx == -1) - 1;