Trying to extract numbers between bounds and counting them

7 vues (au cours des 30 derniers jours)
Mingjia Wang
Mingjia Wang le 15 Avr 2020
Réponse apportée : Tommy le 15 Avr 2020
I'm trying to create a function that finds the amount of numbers in a given table that are greater than or equal to 60 and lower than 70, but I can't us the find function. This is what i have for testing at the moment. The result however always comes out as n = 0 only once. It seems like it either doesnt recognise the x values or it doesn't respect the if statement.
x = randi(100,10,1);
disp(x);
n = 0;
for k = x(:,1)
if (60 <= x) & (x<70)
n = n+1;
disp(n);
end
end
disp(n)
The function itself looks like this
function n = mycount(x)
n = 0;
% Put your code here
for k = x(:,1)
if (60 <= x) & (x<70)
n = n+1;
end
end
end

Réponses (2)

Mohammad Sami
Mohammad Sami le 15 Avr 2020
Modifié(e) : Mohammad Sami le 15 Avr 2020
If you can use logical vectors then you can do it like this
x = randi(100,10,1);
count = sum(x >= 60 & x < 70);
If you have to use the for loop, you need to make correction to your loop.
function n = mycount(x)
n = 0;
% Put your code here
for k = 1:length(x)
if x(k) >= 60 & x(k) < 70
n = n+1;
end
end
end

Tommy
Tommy le 15 Avr 2020
Currently, your for loop only runs once, during which time k is equal to the entirety of x. By using
for k = x(:,1)'
or just
for k = x'
instead, the loop will run 10 times, and on the ith iteration of the loop, k will equal the ith element of x. You should then compare k, not the entirety of x, to 60 and 70:
if (60 <= k) && (k<70)
Better yet, loop through an array of indices of x, rather than x itself:
for i = 1:numel(x)
and then use those indices to determine which element of x to test during a given iteration:
if (60 <= x(i)) && (x(i) < 70)
So in total:
x = randi(100,10,1);
disp(x);
n = 0;
for i = 1:numel(x)
if (60 <= x(i)) && (x(i) < 70)
n = n+1;
disp(n);
end
end
disp(n)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by