我要做的是:给定一个2D矩阵,得到每行中满足特定条件的元素的列索引。
例如,假设我的矩阵是
M = [16 2 3 13; 5 11 10 8; 9 7 6 12; 4 14 15 1]
我的情况是
M>6
那么我想要的输出应该是Indices = {[1 4]'; [2 3 4]'; [1 2 4]'; [2 3]';}
在阅读了this similar question的答案之后,我用
find
和accumarray
得出了这个部分解:[ix, iy] = find(M>6);
Indices = accumarray(ix,iy,[],@(iy){iy});
这几乎给出了我想要的结果——事实上,指数是好的,但它们并没有按我预期的顺序排列例如,
Indices{2} = [2 4 3]'
而不是[2 3 4]'
,我不明白为什么2
中有3例ix
,分别出现在3
、6
和9
指数处在这些指数处,相应的iy
值依次为2
、3
和4
究竟是什么创造了观察到的秩序这是武断吗有没有办法强迫它成为我想要的,除了在之后对Indices
的每个元素进行排序之外? 最佳答案
这里有一种解决方法arrayfun
-
idx = arrayfun(@(x) find(M(x,:)>6),1:size(M,1),'Uni',0)
显示输出wtih
celldisp(idx)
-idx{1} =
1 4
idx{2} =
2 3 4
idx{3} =
1 2 4
idx{4} =
2 3
要继续使用
accumarray
,可以用iy
包装sort
,以获得所需的输出,这可能看起来不太漂亮-Indices = accumarray(ix,iy,[],@(iy){sort(iy)})
输出-
>> celldisp(Indices)
Indices{1} =
1
4
Indices{2} =
2
3
4
Indices{3} =
1
2
4
Indices{4} =
2
3