2
我有一個有兩列的矩陣L。我想找到它的子矩陣在第二列上有相同的值。我想用MATLAB來做這個,不用任何for循環。 例如:將矩陣分解爲具有相等第二列的子矩陣而不使用for循環
L=[1 2;3 2;4 6;5 3;7 3;1 3;2 7;9 7]
那麼子矩陣是:
[1 2;3 2] , [4 6] , [5 3;7 3;1 3] and [2 7;9 7]
我有一個有兩列的矩陣L。我想找到它的子矩陣在第二列上有相同的值。我想用MATLAB來做這個,不用任何for循環。 例如:將矩陣分解爲具有相等第二列的子矩陣而不使用for循環
L=[1 2;3 2;4 6;5 3;7 3;1 3;2 7;9 7]
那麼子矩陣是:
[1 2;3 2] , [4 6] , [5 3;7 3;1 3] and [2 7;9 7]
您可以使用arrayfun
+ unique
組合來獲取 -
[~,~,labels] = unique(L(:,2),'stable')
idx = arrayfun(@(x) L(labels==x,:),1:max(labels),'Uniform',0)
顯示輸出 -
>> celldisp(idx)
idx{1} =
1 2
3 2
idx{2} =
4 6
idx{3} =
5 3
7 3
1 3
idx{4} =
2 7
9 7
您可以直接使用accumarray
,也可以使用排序的數組,具體取決於您希望行的順序是否穩定,或者使submatricxes的順序穩定。
說你要對行穩定:
>> [L2s,inds] = sort(L(:,2));
>> M = accumarray(L2s,inds,[],@(v){L(v,:)});
>> M(cellfun(@isempty,M)) = []; % remove empty cells
>> celldisp(M)
M{1} =
1 2
3 2
M{2} =
5 3
7 3
1 3
M{3} =
4 6
M{4} =
2 7
9 7
哦,順便說一下,我不認爲arrayfun是一個矢量/無環的解決方案!無論如何,如果你的輸出不規則,你不能有一個矢量化的解決方案。 – Divakar 2014-11-06 11:24:54