필터 지우기
필터 지우기

random matrix with fix summation

조회 수: 1 (최근 30일)
fatema saba
fatema saba 2015년 1월 15일
편집: Adam 2015년 1월 15일
Hello
please.
this is my simple code that create (3*3) random matrix that all elements are 0 or 1.
a=randi([0,1],[500,500])
but is there any way that I define the number of elements that are 1. for example number of elements that are 1 be 7000 or in other word summation of matrix "a" be 7000
Thank you.

채택된 답변

Matt J
Matt J 2015년 1월 15일
편집: Matt J 2015년 1월 15일
For older versions of MATLAB without the randperm(n,k) syntax enabled,
n=500^2;
m=7000;
idx=randperm(n);
z=[ones(1,m), zeros(1,n-m)];
a=reshape(z(idx),500,500);
  댓글 수: 1
fatema saba
fatema saba 2015년 1월 15일
Thank you Matt and Adam. it is splendid

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Adam
Adam 2015년 1월 15일
편집: Adam 2015년 1월 15일
You can just create 7000 random indices instead and place the 1s at those indices
e.g. if you have a [500,500] matrix you have 250000 indices so create 7000 random indices from 1 to 250000 and then just assign 1s to all those indices of a 500 x 500 matrix.
  댓글 수: 2
Mohammad Abouali
Mohammad Abouali 2015년 1월 15일
just change "... so create 70 random indices ..." to "... so create 7000 random indices ..."
Matt J
Matt J 2015년 1월 15일
편집: Matt J 2015년 1월 15일
+1. This is really the way to go with a current MATLAB version.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by