How to multiply numbers if they meet a certain condition?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a project where I need to multiply certain numbers in a vector if they meet certain conditions, like being positive or divisilble by three.
I tried something like this:
V = [5, 17, -3, 8, 0, -7, 12, 15, 20, -6, 6, 4, -7, 16];
if rem(find(V>0),3)==0
% multiply values
end
It didn't seem to work. How would I go about finding these values?
1 commentaire
Voss
le 26 Mar 2024
rem(find(V>0),3)==0
That tells you whether the index of each positive element of V is divisible by 3.
V = [5, 17, -3, 8, 0, -7, 12, 15, 20, -6, 6, 4, -7, 16];
temp = find(V>0) % elements #1,2,4,7,8,9,11,12,14 are positive
idx = rem(temp,3)==0
temp(idx) % this tells you that 9 and 12 (not elements #9 and 12 in V, which are 20 and 4) are divisible by 3
Réponse acceptée
Voss
le 26 Mar 2024
Modifié(e) : Voss
le 26 Mar 2024
V = [5, 17, -3, 8, 0, -7, 12, 15, 20, -6, 6, 4, -7, 16]
idx = V>0 | rem(V,3)==0
Now idx is a logical vector saying whether each element of V is positive or divisible by 3.
You can do stuff with that, e.g., get just those elements of V:
V_pos_or_3x = V(idx)
Another example, get the elements of V that are positive and divisible by 3:
idx = V>0 & rem(V,3)==0
V_pos_and_3x = V(idx)
0 commentaires
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!