问题描述
给定idx
一个索引向量,以获得idx +/-1
的排序向量,最好的Matlab/Octave惯用法是什么?
What's the best Matlab/Octave idiom, given idx
a vector of indices, to get the sorted vector of idx +/-1
?
我有一个n x 7数据矩阵,第3列是一个整数标签,并且我有兴趣查看其上不连续的区域.因此,我得到了相应的索引:
I have an n x 7 data matrix, column 3 is an integer label, and I'm interested in viewing the neighborhood of discontinuities on it.Hence I get the corresponding indices:
idx = find(diff(data(:,3)) > 0)
5297
6275
6832
...
20187
然后,如果我想在我的列上(例如(mx2)矩阵[idx-1; idx+1]
上)查看该邻域+/- 1,则需要形成按顺序连接或重新排序的idx-1, idx+1
向量.我发现了一些笨拙的方法,正确的方法是什么?(我尝试了所有有关重新排列的八度章节矩阵)
Then if I want to view that neighborhood +/- 1 on my column (e.g. on the (mx2) matrix [idx-1; idx+1]
), I need to form the vector of idx-1, idx+1
either concatenated in-order, or resorted.I found some clunky ways of doing this, what's the proper way?(I tried all of the octave chapter on Rearranging Matrices)
% 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矩阵,但是...
You would expect there are only two ways to unstack a 2xm matrix, but ...
推荐答案
您可以使用隐式单例扩展(R2016b或更新的MATLAB,Octave本身)进行扩展
You can do this with implicit singleton expansion (R2016b or newer MATLAB, native to 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
是行还是列,则可以通过使用
If you don't know whether idx
is a row or column, you can be more robust by using
neighbours = reshape( idx(:)' + [-1,1], [], 1)
如果您不想使用隐式扩展(并再次处理行或列idx
),则可以使用像这样的重塑
If you don't want to use implicit expansion (and again coping with either row or column idx
), you can use reshape like so
neighbours = reshape( [idx(:)-1, idx(:)+1]', [], 1 )
注意:您可能还希望将整个内容包装在对unique
的调用中.在我的示例中,您两次获得了索引8
,我不确定这是否符合您的情况.
Note: you may also want to wrap the whole thing in a call to unique
. In my example, you get the index 8
twice, I'm not sure if this is desirable or not in your situation.
但是,unique
会执行排序(除非您使用'stable'
标志,但这会使它变慢),因此,如果要删除重复项,也可以使用原始方法:
However, unique
performs a sort (unless you use the 'stable'
flag but that can make it even slower), so you might as well use your original approach if you want to remove duplicates:
% Remove duplicates and sort the result using unique
neighbours = unique( [idx-1, idx+1] );
这篇关于获取给定索引前后的矢量索引(窗口+/- 1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!