While loop not performing
2 views (last 30 days)
Show older comments
Uendi Hajderaj
on 15 Feb 2019
Commented: Luigi Mario
on 27 Feb 2019
Hi,
I have the following code. My aim is to make each and every entry of vector a zero, i.e. to make it a vector of zeros. I am doing this by using a while loop and choosing a random number within a's dimensions and making that entry 0. It should do this until all entries become zero and it should, in addition, count the times it took to make the vector zero.
My problem is that the loop doesn't work at all. How can I make it better, or where is the mistake I cannot see here?Hi,
I have the following code. My aim is to make each and every entry of vector a zero, i.e. to make it a vector of zeros. I am doing this by using a while loop and choosing a random number within a's dimensions and making that entry 0. It should do this until all entries become zero and it should, in addition, count the times it took to make the vector zero.
My problem is that the loop doesn't work at all. How can I make it better, or where is the mistake I cannot see here?
a=ones(1,10);
while(a==zeros(1,10))
N=1;
x=randi([1 10])
a(x)=0
N=N+1;
end
a
end
0 Comments
Accepted Answer
Walter Roberson
on 15 Feb 2019
When you use if or while with a condition, then MATLAB only considers the condition to be true if all the values being tested are non-zero.
You initialize a to a vector of 1's, and test whether that vector == 0. None of the entries are equal to 0, so not all of the values are true (non-zero), so the while ends immediately.
You could test
while any(a)
which would be equivalent to testing
while any(a ~= 0)
4 Comments
Walter Roberson
on 16 Feb 2019
N = 10;
a = ones(1, N);
C = 0;
while any(a ~= 0)
C = C + 1;
idx = randi([1 N]);
a(idx) = 0;
end
fprintf('Needed %d iterations\n', C);
More Answers (1)
Uendi Hajderaj
on 16 Feb 2019
Edited: Uendi Hajderaj
on 16 Feb 2019
1 Comment
Luigi Mario
on 27 Feb 2019
You already know the answer. Just add another array.
a=ones(1,10);
timesItTakes = zeros(1,10);
for M=1:10
while (a(M)~=0);
x=randi([1 10])
a(x)=0
timesItTakes(x) = timesItTakes(x) + 1
end
end
a
See Also
Categories
Find more on Operating on Diagonal Matrices 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!