How to multiply numbers if they meet a certain condition?

1 view (last 30 days)
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 Comment
Voss
Voss on 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
temp = 1x9
1 2 4 7 8 9 11 12 14
idx = rem(temp,3)==0
idx = 1x9 logical array
0 0 0 0 0 1 0 1 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
ans = 1x2
9 12

Sign in to comment.

Accepted Answer

Voss
Voss on 26 Mar 2024
Edited: Voss on 26 Mar 2024
V = [5, 17, -3, 8, 0, -7, 12, 15, 20, -6, 6, 4, -7, 16]
V = 1x14
5 17 -3 8 0 -7 12 15 20 -6 6 4 -7 16
idx = V>0 | rem(V,3)==0
idx = 1x14 logical array
1 1 1 1 1 0 1 1 1 1 1 1 0 1
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)
V_pos_or_3x = 1x12
5 17 -3 8 0 12 15 20 -6 6 4 16
Another example, get the elements of V that are positive and divisible by 3:
idx = V>0 & rem(V,3)==0
idx = 1x14 logical array
0 0 0 0 0 0 1 1 0 0 1 0 0 0
V_pos_and_3x = V(idx)
V_pos_and_3x = 1x3
12 15 6

More Answers (0)

Community Treasure Hunt

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

Start Hunting!