random matrix with a given number of specified elements

조회 수: 3 (최근 30일)
sko
sko 2020년 8월 3일
댓글: sko 2020년 8월 3일
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일
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일
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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by