Need to run this code 6 times?

I need to run the following code six different times so that six different zeros in my array are changed from 0 to 1. I know I have to use a for loop, but I'm not entirely to sure how to incorperate it. Any help would be appreciated. Thank you!
x = zeros(10,10);
m = randi(10);
n = randi(10);
x(m,n) = 1;

Réponses (2)

Walter Roberson
Walter Roberson le 3 Avr 2021

0 votes

No, you need to use a while loop. When you generate indices randomly, there is the possibility that you will generate the same one again before the end, but you are required to generate for six different locations being changed.
%outline, not actual code
while number of 1's in x is less than 6
generate a new location
set the value at the location
end
Steven Lord
Steven Lord le 4 Avr 2021

0 votes

Is the requirement that you have to use a loop imposed upon you (as part of a homework assignment, perhaps?) or do you believe you need to use a loop because you're not sure how to do it without a loop?
If the latter, see the section on linear indexing on this documentation page. You need to generate six linear indices without replacement. This other documentation page has information that may be useful to you in accomplishing that task.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by