フィルターのクリア

How can I generate a Matrix (4x4) with random different figures from 1 to 4 ?

53 ビュー (過去 30 日間)
Lorenz
Lorenz 2013 年 4 月 10 日
Hello, How can I generate a Matrix (size 4x4) with random different figures from 1 to 4 ? Figures must be different in the lines and the columns. in example:
A=[1 2 3 4; 2 1 4 3; 3 4 1 2; 4 3 2 1]
thank you.

採用された回答

Jan
Jan 2013 年 4 月 10 日
編集済み: Jan 2013 年 4 月 10 日
You can start with a valid matrix:
A = [1:4; 1:4, 1:4, 1:4];
Then perform only operations, which do not destroy the validity: Interchange rows and columns in pairs:
for k = 1:1000
index = randperm(4, 2); % older Matlab versions accept 1 input only
A(index(1), :) = A(index(2), :);
index = randperm(4, 2);
A(:, index(1)) = A(:, index(2));
end
Or a constructive method which rejects not matching input:
A = zeros(4, 4);
A(1, :) = randperm(4, 4);
index = 2;
while index <= 4
newRow = randperm(4, 4);
match = bsxfun(@ne, A(1:index - 1, :), newRow);
if all(match(:))
A(index, :) = newRow;
index = index + 1;
end
end
Actually trivial ideas with just some tricks in the implementation.
  1 件のコメント
Lorenz
Lorenz 2013 年 4 月 10 日
Thank you, the second method works correctly.

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2013 年 4 月 10 日
編集済み: Andrei Bobrov 2013 年 4 月 17 日
n = 4;
A = rem(bsxfun(@plus,1:n,(0:n-1)')-1,n)+1;
or [EDIT]
A = hankel(1:n,[n 1:n-1]);
A = A(randperm(n),:);
A = A(:,rendperm(n));
  2 件のコメント
Lorenz
Lorenz 2013 年 4 月 17 日
Hi, thank you for your answer. How can I now permute the whole rows and whole columns in the order I want? For example row 2 goes to 3 and 3 to 2 and 1 goes to 4 and 4 to 1. The same for the columns.
fliplr, permute, flimud are not very efficient. thank you
Andrei Bobrov
Andrei Bobrov 2013 年 4 月 17 日
編集済み: Andrei Bobrov 2013 年 4 月 17 日
see EDIT

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by