Repeative selecting unique values of matrix
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Lukasz
am 13 Mai 2014
Beantwortet: Andrei Bobrov
am 13 Mai 2014
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 Kommentare
Akzeptierte Antwort
Jos (10584)
am 13 Mai 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
Weitere Antworten (4)
W. Owen Brimijoin
am 13 Mai 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 Kommentare
W. Owen Brimijoin
am 13 Mai 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
am 13 Mai 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!