Repeative selecting unique values of matrix
1 回表示 (過去 30 日間)
古いコメントを表示
Helo All!
I am new on this forum so please be understanding. My problem is follows:
I have matrix M [3x9] containing three 9-element vectors (rows) of values 1..9 in a different order. For example:
M(1,1:9) = [2 3 8 1 4 7 6 5 9]
M(2,1:9) = [1 3 8 9 4 6 5 2 7]
M(3,1:9) = [2 8 1 4 6 3 9 5 7]
I want to take 9 elements from M, by 3 elements from each row with no duplicates, starting from begin of each row. In this example will be: 2 -> 1 -> 8 (because 2 was before) -> 3 -> 9 (because 3 and 8 were before) -> 4 (because 8 and 1 was before) etc...
As a result I want to obtain R matrix [3x3] of values R = [2 3 7; 1 9 6; 8 4 5]
I have started like this:
P = zeros(3,9); % buffer containing already selected elements of M
for X=1:9
for Y=1:3
if ismember(M(Y,X),P)==0 % if the current element has not been already selected
P(Y,X)=M(Y,X); % copy this element from matrix M to buffer P
else
*** What should be here? ***
end
end
end
Thanks in advance!
Lukas
0 件のコメント
採用された回答
Jos (10584)
2014 年 5 月 13 日
Here is a working algorithm
M = [2 3 8 1 4 7 6 5 9 ;
1 3 8 9 4 6 5 2 7 ;
2 8 1 4 6 3 9 5 7]
P = zeros(n,m,1) ;
Mcopy = M ;
for rankX = 1:3,
for userX = 1:3,
tmp = Mcopy(userX,:) ; % select current user
tmp = tmp(tmp>0) ; % find the remaining values
P(userX, rankX) = tmp(1) ; % select the first (most desired)
Mcopy(Mcopy==tmp(1)) = 0 ; % remove them from M
end
end
P
その他の回答 (4 件)
W. Owen Brimijoin
2014 年 5 月 13 日
You don't really need the three vectors to begin with, you can make a matrix containing a random permutation (randperm.m) of the numbers 1:9 as follows:
R = reshape(randperm(9),3,3);
Unless I am misunderstanding what you're trying to achieve?
0 件のコメント
W. Owen Brimijoin
2014 年 5 月 13 日
Ok, now I understand what you're trying to do. The first three values will always be the first three three from user 1, then the first different ones from user 2, and so on.
R = M(1,1:3);
r = M(2,setdiff(M(2,:),M(1,1:3)));
R(2,:) = r(1:3);
R(3,:) = M(2,setdiff(M(2,:),R));
Better?
Andrei Bobrov
2014 年 5 月 13 日
M = [2 3 8 1 4 7 6 5 9
1 3 8 9 4 6 5 2 7
2 8 1 4 6 3 9 5 7];
ii = ndgrid(1:size(M,1),1:size(M,2));
[a,b] = unique(M(:),'stable');
i0 = ii(b);
out = zeros(3);
for jj = 1:3
out(jj,:) = a(find(i0==jj,3));
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!