我有一个长度为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. (车辆制动和再生能源)...and等用于长度为n的数组。
我想做的是获取每一组能量值的起始和结束索引数。
例如,上面的序列给出了这个结果:
141 - 200
326 - 405
... 有人能建议我用什么方法或技术来获得这个结果吗?
发布于 2018-12-04 14:22:43
使用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。
发布于 2018-12-04 15:13:37
该任务由两种方法执行,两种方法都工作得很好。
Wolfie方法:
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
843endIdx =
212
426
642
912第二种方法:
startends = find(diff([0; EnergyB > 0; 0]));
startends = reshape(startends, 2, [])';
startends(:, 2) = startends(:, 2) - 1结果:
星=
141 212
370 426
608 642
843 912https://stackoverflow.com/questions/53614718
复制相似问题