Add value x to negaive numbers and subtract value x from positiv numbers in same double

2 vues (au cours des 30 derniers jours)
Hi there,
lets say i the double [5 4 3 2 1 -1 -2 -3 -4 -5] and the value x=0.5.
I would like to subtract x from all positiv numbers of the double and add x to all negative numbers. How to go about this ?
Thanks for your time and help
Ben !

Réponse acceptée

John D'Errico
John D'Errico le 11 Juil 2023
Modifié(e) : John D'Errico le 11 Juil 2023
Trivial. Though you do not say what happens to zero.
V = [5 4 3 2 1 -1 -2 -3 -4 -5];
x = 0.5;
V - x*sign(V)
ans = 1×10
4.5000 3.5000 2.5000 1.5000 0.5000 -0.5000 -1.5000 -2.5000 -3.5000 -4.5000
As I said, It is very important in computing to consider the special cases, as if you don't do that then you will find bugs arise.
sign(0)
ans = 0
So what happens if V has an exactly zero element? Since sign(0) is zero, it leaves the zero alone.

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by