How to place a number (1) in a random position in Line 1 in a matrix of zeros?
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
robert
le 30 Juil 2020
Commenté : John D'Errico
le 31 Juil 2020
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 commentaires
Réponse acceptée
Image Analyst
le 30 Juil 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 commentaires
John D'Errico
le 31 Juil 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.
Plus de réponses (1)
John D'Errico
le 30 Juil 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.
Voir également
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!