Filter löschen
Filter löschen

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 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Voss
Voss am 3 Apr. 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by