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;

답변 (2개)

Walter Roberson
Walter Roberson 2021년 4월 3일

0 개 추천

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 2021년 4월 4일

0 개 추천

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.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2021년 4월 3일

답변:

2021년 4월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by