random matrix with a given number of specified elements

Hello,
How can we generate a matrix n x n Whose elements can be only two values AND where number of one of those two elements is given?
For instance, in the 3 x 3 matrix elements can be only 0 et 1, But I want exactly 4 elements to be zeros (and therefore 5 elements to be ones)
Thank you

2 件のコメント

madhan ravi
madhan ravi 2020 年 8 月 3 日
編集済み: madhan ravi 2020 年 8 月 3 日
Did you try something for your homework ?
sko
sko 2020 年 8 月 3 日
I only did research on random numbers generation but I didn’t find the answer on the second part of my needs i.e. specifying the number (amount) of a given element (number).

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

 採用された回答

madhan ravi
madhan ravi 2020 年 8 月 3 日
編集済み: madhan ravi 2020 年 8 月 3 日

1 投票

v = [repelem(1, 5), repelem(0, 4)];
Wanted = v(reshape(randperm(numel(v)), 3, []))

1 件のコメント

sko
sko 2020 年 8 月 3 日
Thank you very much.
This is what I need!
Best wishes

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 8 月 3 日
編集済み: Bruno Luong 2020 年 8 月 3 日

1 投票

User inputs
matsz = [3,3];
n1 = 4; % number of desired 1s, no need to specify for 0s
Generate
B = zeros(matsz); % + 0;
B(randperm(numel(B),n1)) = 1;
Quick check
B

1 件のコメント

sko
sko 2020 年 8 月 3 日
This works too!
Thank you very much.

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

カテゴリ

ヘルプ センター および File ExchangeRandom Number Generation についてさらに検索

製品

リリース

R2017b

質問済み:

sko
2020 年 8 月 3 日

コメント済み:

sko
2020 年 8 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by