How to place a number in a random position in a matrix of zeros?

조회 수: 13 (최근 30일)
Steven M
Steven M 2017년 4월 28일
댓글: Star Strider 2020년 4월 14일
I have a matrix "m" of zeros(6,7) and I would like to know how to place a variable equaling 1 into a random spot in the matrix. For example, the "1" could be randomly placed in m(1,2) or m(5,4), etc. How would I code this to pick a random row and random column?
Thank you for your help!

채택된 답변

Star Strider
Star Strider 2017년 4월 28일
편집: Star Strider 2017년 4월 28일
I would use linear indexing, taking advantage of how matrices are stored in MATLAB, to use one number to define both the row and column:
M = zeros(6,7);
M(randi(numel(M))) = 1
M =
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
EDIT You can do this with more lines of code, creating the linear index in one line, and using the ind2sub function to return the subscripts.
  댓글 수: 7
R. Pam
R. Pam 2020년 4월 14일
Hey, this is very helpful. Thanks. But what if I want the vector to be randomly shown as a row or a column? I'm quite confused, is it possible?
Star Strider
Star Strider 2020년 4월 14일
@R. Pam — It is possible. As I mentioned, it would be necessary to make the appropriate changes in the ind2sub call, reflecting the orientation (row or column) of the vector you want to insert. It would also be necessary to add code to check the sizes of the vector and the matrix to limit the initial index appropriately.
I leave that to you.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by