Need to run this code 6 times?
Show older comments
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;
Answers (2)
Walter Roberson
on 3 Apr 2021
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
on 4 Apr 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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!