How to place a number (1) in a random position in Line 1 in a matrix of zeros?
14 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
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 个评论
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
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!