How to avoid having duplicate index result?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Jan
2019년 2월 21일
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.
Jos (10584)
2019년 2월 21일
편집: Jos (10584)
2019년 2월 21일
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, [])
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!