How can I create a random matrix without repeating any value between column

1 回表示 (過去 30 日間)
Wan
Wan 2023 年 5 月 23 日
コメント済み: Wan 2023 年 5 月 28 日
I get two columns with the same value when I generate the matrix. For example,
1 1 3 2 4
4 4 1 4 3
2 2 2 3 1
3 3 4 1 2
I want to get something like the 10 combinations from the 24 combinations(4 factorial).
1 1 3 2 4 1 2 4 3 2
2 4 1 4 3 3 3 1 2 1
3 2 2 3 1 4 1 3 4 3
4 3 4 1 2 2 4 2 1 4
I need the matrix to form the chromosomes for GA.
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 5 月 23 日
As Steven mentions, it's not clear what is the pattern you are following to obtain the output.
From a cursory glance, it can be observed from the output that the 1st column is sorted and the 6th column corresponds to the indices of the sorted values of the 1st column. But the it's not clear what's the logic behind the columns 7-10.
Wan
Wan 2023 年 5 月 28 日
Sorry for not making my question clear. There are no special rules to follow. So long as the matrix generates non-repeated combinations from the 24 combinations, then it is good enough. It does not need to be exactly like the second matrix. The second matrix is just an example.

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

採用された回答

David Goodmanson
David Goodmanson 2023 年 5 月 24 日
編集済み: David Goodmanson 2023 年 5 月 24 日
Hello Wan,
all columns contain 1 through 4, and all columns are different
a = perms(1:4) % all 24 permutations of 1:4
ind = randperm(24);
ind = ind(1:10) % an index of 10 random integers from 1 to 24, no repeats
b = a(ind,:)' % 10 random choices from the rows of a,
% then transpose to get 4x10 matrix
  1 件のコメント
Wan
Wan 2023 年 5 月 28 日
Wow, it works very well. Thanks a lot, David. I really appreciate it and there are explanations.

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

その他の回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023 年 5 月 23 日
You can use reshape(), randperm(), numel(), size() fcns to create ramdom swaps of the already existing matrix elements:
A1 = [1 1 3 2 4;
4 4 1 4 3;
2 2 2 3 1;
3 3 4 1 2];
A_new = [reshape(A1(randperm(numel(A1))), size(A1)), reshape(A1(randperm(numel(A1))), size(A1))]
A_new = 4×10
3 4 4 3 2 2 2 3 4 2 1 3 4 2 1 1 1 2 1 4 3 4 4 1 2 1 4 4 3 3 1 3 2 1 2 3 3 4 1 2
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 5 月 23 日
@Sulaymon Eshkabilov, every column must contain all the numbers [1 2 3 4]. The output from your code does not.
Wan
Wan 2023 年 5 月 28 日
Ya, I need every column to contain 1,2,3,4 like what @Dyuman Joshi mentions.

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

カテゴリ

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