Repeative selecting unique values of matrix
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Jos (10584)
il 13 Mag 2014
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
Più risposte (4)
W. Owen Brimijoin
il 13 Mag 2014
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 Commenti
W. Owen Brimijoin
il 13 Mag 2014
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
il 13 Mag 2014
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 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!