Borrar filtros
Borrar filtros

Write a random row vector x of size 1x10000. Find in the same for loop the number of elements of x that are btw 0.2 and 0.4.

1 visualización (últimos 30 días)
Can you help me? I solved this problem but I am not sure it's true because when I run the code, answer is too small, like 0 or 1.
Write a random row vector x of size 1x10000. Find in the same for loop the number of elements of x that are btw 0.2 and 0.4.
-------
% add in the same for loop the number of the elements of x that are btw 0.2 and 0.4
% assign x with 10000 random numbers
x = rand(10000,1);
% assign theCount with 0
theCount = 0;
% assign countBetween with 0
countBetween = 0;
% loop runs for 1 to 10000
% check the number is less than 0.2
% increment count by 1
for i = 1:10000
if(x(i) < 0.2)
theCount = theCount + 1;
end
end
% check the number is btw 0.2 and 0.4
% increment count by 1
if (x(i) > 0.2 && x(i) < 0.4)
countBetween = countBetween + 1;
end

Respuesta aceptada

Voss
Voss el 3 de Abr. de 2022
The check for x(i) between 0.2 and 0.4 also has to be inside the for loop (or in its own separate for loop); otherwise you are only ever checking the last element of x, since i is 10000 after the loop finishes.
% add in the same for loop the number of the elements of x that are btw 0.2 and 0.4
% assign x with 10000 random numbers
x = rand(10000,1);
% assign theCount with 0
theCount = 0;
% assign countBetween with 0
countBetween = 0;
% loop runs for 1 to 10000
% check the number is less than 0.2
% increment count by 1
for i = 1:10000
if(x(i) < 0.2)
theCount = theCount + 1;
end
% end
% check the number is btw 0.2 and 0.4
% increment count by 1
if (x(i) > 0.2 && x(i) < 0.4)
countBetween = countBetween + 1;
end
end
disp(theCount);
2024
disp(countBetween);
2047

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by