我有一个长度为n
的数组。该数组具有制动能量值,索引号表示以秒为单位的时间。
数组的结构如下:
Index 1 to 140, array has zero values.
(车辆不刹车)
Index 141 to 200, array has random energy values.
(车辆正在制动并再生能量)
Index 201 to 325, array has zero values.
(车辆不刹车)
Index 326 to 405, array has random energy values.
(车辆正在制动并再生能量)
...以此类推,长度为n
的数组。
我要做的是获取每组能量值的开始和结束索引号。
例如,上面的序列给出了以下结果:
141 - 200
326 - 405
...
有人可以建议我可以使用什么方法或技术来获得此结果吗?
答案 0 :(得分:3)
使用diff
是执行此操作的快速方法。
这是一个演示(请参阅评论以获取详细信息):
% Junk data for demo. Indices shown above for reference
% 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
x = [0, 0, 0, 2, 3, 4, 0, 0, 1, 1, 7, 9, 3, 4, 0, 0, 0];
% Logical converts all non-zero values to 1
% diff is x(2:end)-x(1:end-1), so picks up on changes to/from zeros
% Instead of 'logical', you could have a condition here,
% e.g. bChange = diff( x > 0.5 );
bChange = diff( logical( x ) );
% bChange is one of the following for each consecutive pair:
% 1 for [0 1] pairs
% 0 for [0 0] or [1 1] pairs
% -1 for [1 0] pairs
% We inflate startIdx by 1 to index the non-zero value
startIdx = find( bChange > 0 ) + 1; % Indices of [0 1] pairs
endIdx = find( bChange < 0 ); % Indices of [1 0] pairs
我将保留它作为练习,以捕获如果数组以非零值开始或结束时添加起始索引或终止索引的情况。提示:您可以分别处理每种情况,也可以在初始x
处加上其他最终值。
以上内容的输出
startIdx
>> [4, 9]
endIdx
>> [6, 14]
因此您可以设置其格式,但是您希望获得跨度4-6, 9-14
。
答案 1 :(得分:0)
此任务通过两种方法执行。两种方法均可正常工作。
狼人方法:
bChange = diff( EnergyB > 0 );
startIdx = find( bChange > 0 ) + 1; % Indices of [0 1] pairs
endIdx = find( bChange < 0 ); % Indices of [1 0] pairs
结果:
startIdx =
141
370
608
843
endIdx =
212
426
642
912
第二种方法:
startends = find(diff([0; EnergyB > 0; 0]));
startends = reshape(startends, 2, [])';
startends(:, 2) = startends(:, 2) - 1
结果:
startends =
141 212
370 426
608 642
843 912