How can I change range codes in to conditional?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2020-4-9
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 个评论
Walter Roberson
2020-4-9
Yup, you want to increment the appropriate variable by the constant 1. For example
if x > 7 & x < 43
x7 = x7+1;
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!