Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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.

Réponse acceptée

Matt J
Matt J le 13 Août 2018
Modifié(e) : Matt J le 13 Août 2018
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

Plus de réponses (0)

Catégories

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

Community Treasure Hunt

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

Start Hunting!

Translated by