rite a program that (a) generates a vector with 20 random integer elements with
ID: 3906721 • Letter: R
Question
rite a program that (a) generates a vector with 20 random integer elements with integers between 10 and 30, (b) replaces all the elements that are not even integers with random integers between 10 and 30, and (c) repeats (b) tegers. The program should also count how 16. W until all the elements are even in many times (b) is repeated before all the elements are even integers. When , the program displays the vector and a statement that states how many iterations were needed for generating the vector.Explanation / Answer
% generating
r = randi([10 30],1,20);
count = 20;
loops = 0;
% looping as long as there is at least 1 number that is odd
while count > 0
count = 0;
for i = 1:20
% if there is an odd number, going for one more random number
if mod(r(i), 2) != 0
r(i)= round((20)*rand(1) + 10);
count += 1;
end
end
if count > 0
r
loops += 1;
end
end
loops
% Output
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 21 26 29 22 16 25 26 20
Columns 17 through 20:
18 14 12 14
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 24 26 11 22 16 20 26 20
Columns 17 through 20:
18 14 12 14
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 24 26 23 22 16 20 26 20
Columns 17 through 20:
18 14 12 14
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 24 26 20 22 16 20 26 20
Columns 17 through 20:
18 14 12 14
loops = 4
% generating
r = randi([10 30],1,20);
count = 20;
loops = 0;
% looping as long as there is at least 1 number that is odd
while count > 0
count = 0;
for i = 1:20
% if there is an odd number, going for one more random number
if mod(r(i), 2) != 0
r(i)= round((20)*rand(1) + 10);
count += 1;
end
end
if count > 0
r
loops += 1;
end
end
loops
% Output
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 21 26 29 22 16 25 26 20
Columns 17 through 20:
18 14 12 14
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 24 26 11 22 16 20 26 20
Columns 17 through 20:
18 14 12 14
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 24 26 23 22 16 20 26 20
Columns 17 through 20:
18 14 12 14
r =
Columns 1 through 16:
12 20 28 28 16 20 22 22 24 26 20 22 16 20 26 20
Columns 17 through 20:
18 14 12 14
loops = 4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.