필터 지우기
필터 지우기

How can i make my rounds() function be very precised when handling around 400 values at a time?

조회 수: 1 (최근 30일)
I have made this function rounds() which rounds the values to the nearest multiple of 0.5, ie, rounds(2.685)=2.5 rounds(2.332)=2.5 rounds(2.7554)=3.0 rounds(2.245)=2.0 it works well in the way mentioned above, but while handling large number of values the precision drop. It does not give me the desired results. I have 30 functions, each of them computes 14 values which I pass in rounds() as a whole vector containing those 14 values. The results are like, for values for which it should return 3.0 such as rounds(2.7554) it only returns 2.5 and that affects my overall accuracy alot. Individually it works well for all values even 2.7554 returns 3.0 when i pass it to check its working. Can anyone tell me why this happens that while handling large number of values its performance decreases and also tell me the solution.
function [newVal] = rounds(x)
dist = mod(x, 0.5);
floorVal = x - dist;
if dist >=0.25
newVal = floorVal + 0.5;
else
newVal = floorVal;
end
end
The above is the rounds function and below i am showing how i have used it.
if true
calc(1) = x+y;
calc(2) = x-y;
calc(3) = x*y+a;
.......
.......
.......
calc(14) = a+b*c+x;
calc = calc';
final_calc = rounds(calc);
end
Even in a single function the rounds function handles only 14 values at once still the result is not precised, while if i pass those same values individually it gives the correct output. Please solve this issue someone. Thanks in advance.

채택된 답변

Matt J
Matt J 2018년 8월 13일
편집: Matt J 2018년 8월 13일
It happens because you are passing the vector expression dist >= 0.25 to if...end, incorrectly thinking that the if...end will be evaluated separately for each element of x(i). The better way to vectorize this computation is as follows,
newVal=round(x/0.5)*0.5

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by