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
댓글 수: 0
채택된 답변
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);
disp(countBetween);
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!