Why do I keep getting complex values from an if/else statement?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ryan Mahoney
le 3 Déc 2020
Commenté : Star Strider
le 3 Déc 2020
I'm trying to create values for a variable (called r2 in my code) using random numbers on [0,1] and an if/else statement. However, I keep getting complex values for r2 when that shouldn't happen. Is there an issue with the way I wrote my code? Here it is:
r = rand(25,1)
if r < 0.5
r2 = 0.5-sqrt(0.25-(r/2));
else
r2 = 0.5+sqrt((r/2)-0.25);
end
0 commentaires
Réponse acceptée
Star Strider
le 3 Déc 2020
The problem is in the if block logic and the way MATLAB evaluates vectors.
if r < 0.5
implies:
if all(r < 0.5)
that of course is not true, so the first section never evaluates.
You could put it in a loop, however this is more efficient:
r2 = (0.5-sqrt(0.25-(r/2))).*(r<0.5) + (0.5+sqrt((r/2)-0.25)).*(r>=0.5);
.
2 commentaires
Plus de réponses (0)
Voir également
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!