给定 idx
的索引向量是什么是最佳的matlab/octave成语,以获取idx +/-1
的分类向量?
我有一个n x 7数据矩阵,第3列是一个整数标签,我有兴趣查看其上的不连续性。因此,我得到了相应的索引:
idx = find(diff(data(:,3)) > 0)
5297
6275
6832
...
20187
然后,如果我想在列上查看该邻域/- 1(例如在(MX2(矩阵[idx-1; idx+1]
上(,我需要形成idx-1, idx+1
的向量,或者求解。我发现了一些笨拙的方法,正确的方法是什么?(我尝试了有关重新排列矩阵的所有八度章节(
% 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
您希望只有两种方法可以解开2xm矩阵,但是...
您可以使用隐式Singleton扩展(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
(,则可以使用像So
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] );
嗯,我终于找到了这个八度矩阵操纵:
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)]
显示索引和数据,并排