matlab - find array elements that match one of multiple conditions, sorted by condition matched -
i have m-by-n matrix (n > 3) 2 first columns have lot of repetition of values. have 2 vectors, call them uniquecol1
, uniquecol2
, contain possible values 2 columns.
i want find sub-matrices, p-by-n (p =< m), 2 first columns match given values in uniquecol1
, uniquecol2
. there length(uniquecol1) * length(uniquecol2)
such sub-matrices.
i use ismember()
find these sub-matrices, can't see way of doing know parts of output matched condition.
alternatively can loop, shown below, extremely slow. there way of vectorizing below? imagine solution have output cell array of these sub-matrices, each sub-matrix not same size (so multi-dimensional array not work).
mybigmatrix = round(wgn(1000,6,1) * 3); uniquecol1 = unique(mybigmatrix(:,1)); uniquecol2 = unique(mybigmatrix(:,2)); = 1:length(uniquecol1) j = 1:length(uniquecol2) mysubmatrix = mybigmatrix( ... mybigmatrix(:,1) == uniquecol1(i) & ... mybigmatrix(:,2) == uniquecol2(j) , :); % mysubmatrix, % it's clear , j condition matched end end
you can use powerful accumarray
function task:
[uniquecol1, ~, u1] = unique(mybigmatrix(:,1)); [uniquecol2, ~, u2] = unique(mybigmatrix(:,2)); r = accumarray([u1 u2], (1:size(mybigmatrix,1)).', [], @(x) {mybigmatrix(sort(x),:)})
then r{m,n}
contains submatrix matches m
-th element of uniquecol1
, n
-th element of uniquecol2
.
example:
mybigmatrix = 3 5 3 3 2 2 3 5 1 3 2 1 1 5 4 4 3 4
gives
>> uniquecol1.' ans = 1 3 4 >> uniquecol2.' ans = 2 3 5 >> r r = [] [] [1x3 double] [2x3 double] [] [2x3 double] [] [1x3 double] [] >> r{2,1} %// submatrix corresponding 3 in first col , 2 in second col ans = 3 2 2 3 2 1 >> r{3,2} %// submatrix corresponding 4 in first col , 3 in second col ans = 4 3 4
Comments
Post a Comment