How to avoid having duplicate index result?

I have written this code it works correct but one thing is that when I run it it gives me duplicate result how can I avoid repetion if I run it for 24 times.
x=zeros(4,4);
temp=0;
test=zeros(3,3);
b=sum(x,1);
r=randperm(4);
for i=1:4
temp=0;
for j=1:4
% r=randi([1,3]);
if temp~=r(j)
temp=r(j);
if sum(x(i,:))==0 && b(temp)==0
x(i,temp)=1;
end
end
end
b=sum(x,1);
end
x

3 comentarios

The question is not clear yet. Which "index" is duplicated? What is repeated?
The code is not clear also. Why do you create the variable test which is not used anywhere? Defining b=sum(x,1) could be simplified to: b=zeros(1, 4).
The purpose of the code is not clear also, because you do not provide meaningul comments.
Do I understand correctly, that your code creates a 4x4 matrix of zeros with one 1 in each row and column? Then this is easier:
x = zeros(4, 4);
x(sunb2ind(size(x), 1:4, randperm(4,4))) = 1;
Stephen23
Stephen23 el 21 de Feb. de 2019
Editada: Stephen23 el 21 de Feb. de 2019
Original (better explained) question, with simple three line answer:
@Hardi Mohammed: why do refuse to use perms, which is the best way to generate those 6/24/... permutations that you request. Please explain why perms does not work for you.
Hardi Mohammed
Hardi Mohammed el 25 de Feb. de 2019
@Stephen Cobeldick
it works well but I have problem when I change the size of matrix for 2 row 3 column
then it does not give all the possiblites

Iniciar sesión para comentar.

Respuestas (2)

Jan
Jan el 21 de Feb. de 2019
If I assume, that this code satisfies your needs for 1 call:
x = zeros(4, 4);
x(sub2ind(size(x), 1:4, randperm(4,4))) = 1;
I assume, that this creates all wanted results:
order = perms(1:4);
n = size(order, 1);
order = order(randperm(n, n), :); % If a random order is wanted
x = zeros(4, 4, n);
for k = 1:n
index = sub2ind([4, 4, n], 1:4, order(k, :), repmat(k, 1, 4));
x(index) = 1;
end
Now x(:, :, k) is the wanted submatrix.

2 comentarios

you can leave out the sub2ind ...
x = eye(4) ;
x = x(randperm(4),:)
Jan
Jan el 21 de Feb. de 2019
Editada: Jan el 21 de Feb. de 2019
@Jos: Your are correct, but the sub2ind method is not needed for the random permutation, but for the construction of all 24 different matrices.

Iniciar sesión para comentar.

Jos (10584)
Jos (10584) el 21 de Feb. de 2019
Editada: Jos (10584) el 21 de Feb. de 2019
This also produces the N! possibilities. No loop, no sub2ind, only the outcome of perms as column indices ...
N = 4
X = eye(N) ;
X = reshape(X(:, perms(1:N).'), N, N, [])

Categorías

Etiquetas

Preguntada:

el 21 de Feb. de 2019

Comentada:

el 25 de Feb. de 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by