Need help with my Matlab assignment Write a code that will use the random-number
ID: 3807876 • Letter: N
Question
Need help with my Matlab assignment
Write a code that will use the random-number generator rand to determine the following: I. The number of random numbers it takes to add up to 20 . II. The number of random numbers it takes before a number between 0.8 and 0.85 occurs. III. The number of random numbers it takes before the mean of those numbers is within 0.01 of 0.5 (the mean of this random-number generator). Compute the cumulative product of the elements in a vector. The cumulative product of the j^th element of the vector x, Xj, is defined by: P_j = x_1x_2x_3 .... x_j for j = 1:length of the vector x. Create 2 different versions of this function: I. One that uses two for-loops to explicitly carry out the calculations, element by element. An "inner" loop should accumulate the product and an "outer" loop should move through the elements of the vector p. II. One that uses the built-in function prod to replace the inner loop. In each case, you can check your results with the built-in function, compared.Explanation / Answer
As the rand function is used,the count varies every time we execute the code
i.
sum = 0; % initialize sum to 0
count = 0; % counter to get the number of times
while sum <20 % loop until 20 is exceeded
count = count + 1; % increment till the sum is reached
x = rand(1,1); %randomly generate the number
sum = sum + x; % add the randomly generated number
end
disp(['The number of random numbers taken to add up to 20 is ',int2str(count)])
ii.
count = 0;
while 1 % loop infinite times till we get number < 0.85 and > 0.8
count = count + 1;
x = rand(1,1); % get a number
if (x < 0.85) & (x > 0.8) % check number
break % once the above condition is %met exit the loop by break statement
end
end
disp(['The number of random numbers taken before a number bw 0.8 and 0.85 occurs is ',int2str(count)])
iii.
cnt = 0;
avg = 0; % avegare check variable
while abs(avg - 0.5) > 0.01
cnt = cnt + 1;
avg = ((cnt-1)*avg + rand(1,1))/cnt; % calculate mean %verage value.Get random number add to previous avg and %divding by new count gives the latest avg
end
disp(['The number of random numbers it takes before the mean of those numbers is within 0.01 of 0.5 is ',int2str(cnt)])
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.