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에서 Particle & Nuclear Physics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!