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 次查看(过去 30 天)
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

采纳的回答

Voss
Voss 2022-4-3
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by