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

14 views (last 30 days)
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!

Accepted Answer

Image Analyst
Image Analyst on 30 Jul 2020
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 Comments
robert
robert on 31 Jul 2020
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 on 31 Jul 2020
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.

Sign in to comment.

More Answers (1)

John D'Errico
John D'Errico on 30 Jul 2020
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!