Repeative selecting unique values of matrix
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (4)
W. Owen Brimijoin
el 13 de Mayo de 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?
Lukasz
el 13 de Mayo de 2014
0 votos
W. Owen Brimijoin
el 13 de Mayo de 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?
1 comentario
Lukasz
el 13 de Mayo de 2014
Andrei Bobrov
el 13 de Mayo de 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
Categorías
Más información sobre Resizing and Reshaping Matrices en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!