Get vector indices before and after (window +/- 1) taking into account indices

What is the best Matlab / Octave needle bar given idxby an index vector to get a sorted vector idx +/-1?

I have an nx 7 data matrix, column 3 is a whole label, and I am interested in looking at the neighborhood of the gaps on it. Therefore, I get the corresponding indexes:

idx = find(diff(data(:,3)) > 0)

5297
6275
6832
...
20187

Then, if I want to look at this neighborhood +/- 1 in my column (for example, on the matrix (mx2) [idx-1; idx+1]), I need to form the vector idx-1, idx+1either in concatenated order, or resort to help. I found some awkward ways to do this, which is correct? (I tried the entire octave chapter on matrix reordering )

% WAY 1: this works, but is ugly - a needless O(n) sort
sort([idx-1; idx+1])

% horzcat,vertcat,vec only stack it vertically
horzcat([idx-1; idx+1])
horzcat([idx-1; idx+1]')

% WAY 2?
%One of vec([idx-1; idx+1]) or vec([idx-1; idx+1]') should work? but doesn't, they always stack columnwise
horzcat([idx-1; idx+1]')

ans =
Columns 1 through ...
5297    6275    6832 ...  20187    5299    6277    6834 ... 20189

% TRY 3...
reshape([idx-1; idx+1], [36,1]) doesn't work either

You expect there are only two ways to unfasten the 2xm matrix, but ...

0
2

(R2016b MATLAB, Octave)

idx = [2, 6, 9]; % some vector of integers
% Use reshape with [] to tell MATLAB "however many rows it takes"
neighbours = reshape( idx + [-1;1], [], 1 );

>> neighbours = [1; 3; 6; 8; 8; 10];

, idx , ,

neighbours = reshape( idx(:)' + [-1,1], [], 1)

( idx), reshape :

neighbours = reshape( [idx(:)-1, idx(:)+1]', [], 1 )

. unique. 8, , .

unique ( 'stable', ), , :

% Remove duplicates and sort the result using unique 
neighbours = unique( [idx-1, idx+1] );
+1

, :

vec([idx-1, idx+1]')
ans =

5297
5299
6275
6277
6832
6834
...
20187
20189

Wolfie :

[idx-1, idx+1]' (:)  
( idx(:)' + [-1; 1] )(:) 

idx = ( find(diff(data(:,3)) > 0 )' + [-1; 1] )(:)

... [idx , data(idx,3)] ,

0

Source: https://habr.com/ru/post/1625898/


All Articles