How to place a number (1) in a random position in Line 1 in a matrix of zeros?

14 ビュー (過去 30 日間)
robert
robert 2020 年 7 月 30 日
コメント済み: John D'Errico 2020 年 7 月 31 日
I have a Matrix M of zeros (10,10) and I would like to know how to place randomly a variable with the value of 1 into a random spot of the Matrix but ONLY in LINE 1 of the matrix M. How would i code this for M=zeros(10,10); ?
I guess randi and numel(M) would be a good idea but i have no idea of the code.
I would really appreciate an answer and would be really thankful!
Thank you!

採用された回答

Image Analyst
Image Analyst 2020 年 7 月 30 日
Try this:
M = zeros(10, 10);
yourVariable = 1;
column = randi(size(M, 2))
M(1, column) = yourVariable % Stuff the variable into the random column of row 1.
  3 件のコメント
robert
robert 2020 年 7 月 31 日
But is there a way to randomly place two number `1` in the Matrix, line 1, that always stay besides each other?
Thank you!
John D'Errico
John D'Errico 2020 年 7 月 31 日
If you want to place TWO 1's , side by side, then you just need to locate the FIRST 1. That must fall in position 1 through 9, randomly. The second 1 will always be the next element.
So if you understand how to put one 1 in some random position, then you should understand how to put two of them also.

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

その他の回答 (1 件)

John D'Errico
John D'Errico 2020 年 7 月 30 日
M = zeros(10,10);
M(1,randi(10)) = 1;
However, if you had no idea how to solve a basic problem of matrix indexing, you REALLY DESPERATELY NEED to start learning MATLAB. This is a basic issue, one that would be covered in the very first tutorials.

Community Treasure Hunt

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

Start Hunting!

Translated by