Matlab 从给定索引运行的连续值的开始和结束

Matlab 从给定索引运行的连续值的开始和结束,matlab,vectorization,Matlab,Vectorization,我想检测向量中等于某个值的第一个和最后一个数字,在该值的相同连续运行中,而不使用循环 在一个例子中,假设我有向量 x = [1 2 2 3 1 1 1 2 2 3] 我想知道从第6个元素开始的第一个和最后一个连续元素的位置 因此,在这种情况下,它意味着从x的第6个元素开始计算有多少个连续的1(之前和之后)。预期输出:y=[5 7]您可以使用find两次,一次从参考索引向后工作,一次向前工作 从你的例子来看: x = [1 2 2 3 1 1 1 2 2 3]; idx = 6; % Logi

我想检测向量中等于某个值的第一个和最后一个数字,在该值的相同连续运行中,而不使用循环

在一个例子中,假设我有向量

x = [1 2 2 3 1 1 1 2 2 3]
我想知道从第6个元素开始的第一个和最后一个连续元素的位置


因此,在这种情况下,它意味着从x的第6个元素开始计算有多少个连续的1(之前和之后)。预期输出:
y=[5 7]
您可以使用
find
两次,一次从参考索引向后工作,一次向前工作

从你的例子来看:

x = [1 2 2 3 1 1 1 2 2 3];
idx = 6;

% Logical index for elements equal to x(idx)
same = (x == x(idx));

% Get last index (up to idx) where not equal to x(idx)
istart = find(~same(1:idx-1), 1, 'last')
% Get first index (after idx) where not equal to x(idx)
iend   = find(~same(idx+1:end), 1, 'first');

% Account for edge cases where consecutive run spans to the end of the array
% Could use NaN or anything else. These values will result in the value idx.
if isempty(istart); istart = idx-1; end;     
if isempty(iend); iend = 1; end;

y = [istart+1, idx+iend-1];
输出:

disp(y)
% >> y = [5 7]