How can I change range codes in to conditional?
1 view (last 30 days)
Show older comments
SeungHyun Cha
on 9 Apr 2020
Commented: Walter Roberson
on 9 Apr 2020
numVec = randi([0,99],1,10000);
range0to24 = length(find(numVec>=0 & numVec<=24));
range25to49 = length(find(numVec>=25 & numVec<=49));
range50to74 = length(find(numVec>=50 & numVec<=74));
range75to99 = length(find(numVec>=75 & numVec<=99));
This is what I want to change into using for-loop and conditionals with 'if' codes.
I did like
for Vector = randi ([0,99],1,10000)
if Vector>=0 && Vector<=24
from0to24 = length (find (Vector>=0 & Vector<=24));
elseif Vector>=25 && Vector<=49
from25to49 = length (find (Vector>=25 & Vector<=49));
elseif Vector>=50 && Vector<=74
from50to74 = length (find (Vector>=50 & Vector<=74));
elseif Vector>=75 && Vector<=99
from50to74 = length (find (Vector>=75 & Vector<=99));
else
end
fprintf ('%f \n', Vector)
end
But they did not work at all.
How can I change the first with for-loop and conditionals?
0 Comments
Accepted Answer
Walter Roberson
on 9 Apr 2020
for Vector = randi ([0,99],1,10000)
At any one time, Vector is going to be a scalar. That makes the name misleading, but it is permitted.
if Vector>=0 && Vector<=24
This is valid because it is testing a scalar on both sides with && which is correct usage of &&
from0to24 = length (find (Vector>=0 & Vector<=24));
Vector is a scalar, and it is known that the value is in range -- otherwise you would not match on the if that has the same test. So there is going to be exactly one matching element, the scalar that is in Vector. find() is going to return 1, the index of that value. length() of that single index is going to be 1. So you can be sure that from0to24 will be assigned 1, overwriting any previous value.
At the end of the if/elseif, one variable will be assigned 1, and the other 3 variables will be left exactly as they are.
The code is not syntactically wrong... it just probably doesn't do what you want. What you probably want is to increment the appropriate variable by the constant 1, without having done any find().
By the way, have you considered using histcounts() instead of all of this?
2 Comments
Walter Roberson
on 9 Apr 2020
Yup, you want to increment the appropriate variable by the constant 1. For example
if x > 7 & x < 43
x7 = x7+1;
end
More Answers (0)
See Also
Categories
Find more on Particle & Nuclear Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!