MATLAB: How to change a value in an array when a condition is met

arraylogical indexingreplace

Hi, I have the following array:
Velocity = [x, y, velocityx, velocityy]
Velocity =
2 9 -1 -1
2 3 -1 1
10 8 1 -1
6 3 0 -1
7 4 -1 0
7 4 0 -1
9 3 0 0 %This is the problem part
7 3 0 -1
7 8 1 1
10 7 0 -1
I want to change the 0 in the last column by a 1 or a -1 when there is a 0 in the third column. I have already tried this with the code below, but the problem with this code is that than all values will be the same instead of changing between 1 and -1.
idx = Velocity(:,3) == 0
p = [1 -1]
Velocity(idx,4) = p(randperm(length(p),1))
How can I solve this problem?

Best Answer

idx = Velocity(:,3)==0;
vec = [1;-1];
Velocity(idx,4) = vec(randi(numel(vec),nnz(idx),1))