How to vectorize ?
Afficher commentaires plus anciens
according to my vectorization the output should be = [0 ; 1 ; 0 ; 1 ; 0; 1]. What am I missing ?
a=[600 300 510 250 700 300]';
a(a >=520)=0;
a(a<=500)=1;
a(a >500 & a <520)=0;
output=a
If I use loop, then it's fine
a=[600 300 510 250 700 300]';
for i=1:6
if a(i) >520
a(i)=0;
elseif a(i) <500
a(i)=1;
else
a(i)=0;
end
end
output=a
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 3 Nov 2022
output = 1*(a>=520) + 2*(a<=500) + 3*(a>500 & a<520)
Note: output will be 0 for any location that fails all three tests.
For finite real numbers, logically every number should fall into one of the three categories. When we extend to +inf and -inf, the tests will also succeed, calculating 1 for +inf and 2 for -inf -- so the test works for finite reals and for +inf and -inf.
Where can the test fail for real numbers? Answer: it can fail for nan . nan compared with anything is always false no matter what the other thing is (including nan). Well, except for the ~= case, since nan~=nan is true, since that is logically ~(nan == nan) and the == is false and ~false is true.
I mentioned real numbers. What about complex numbers? Well it happens that the < and <= and > and >= operators ignore imaginary parts, so for the purposes of the above expression if you have complex inputs, the expression above would effectively be the same as
output = 1*(real(a)>=520) + 2*(real(a)<=500) + 3*(real(a)>500 & real(a)<520)
Catégories
En savoir plus sur Annotations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!