normalize all but the zeros in a vector?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
mark palmer
le 24 Déc 2023
Commenté : Walter Roberson
le 24 Déc 2023
I have a vector that contains 0s, something like this [44 0 23 19 0 0 30]
and I want to normalize the non-0 elements to 1-10, for instance, but the 0s keep messing it up.
Is there a way (hopefully without using loops) to normalize while not affecting the 0s? In other words, take the values from 19-44 and convert them to stretch over 1-10.
0 commentaires
Réponse acceptée
Dyuman Joshi
le 24 Déc 2023
Modifié(e) : Dyuman Joshi
le 24 Déc 2023
%Input
in = [44 0 23 19 0 0 30];
%Lazy preallocation, assuming all values are finite and not NaNs
out = 0*in;
%Indexing for non-zeros values
idx = in~=0;
%Output
out(idx) = rescale(in(idx), 1, 10)
6 commentaires
Dyuman Joshi
le 24 Déc 2023
"But as soon as I say that, it will happen."
Haha, yes.
Mine used to be that too, but I am not sure how it changed into multiplying with 0. I think I'll go back to using zeros() soon, specially noting the difference in speed.
However, keeping performance in mind, maybe I should revisit this thread - https://in.mathworks.com/matlabcentral/answers/51411-initialize-a-mxn-matrix-with-the-same-number#answer_453549
Walter Roberson
le 24 Déc 2023
y = zeros(size(x), 'like', x);
for extra robustness.
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!