# How to change a value in an array when a condition is met?

11 views (last 30 days)
Danny Helwegen on 26 Nov 2018
Commented: Danny Helwegen on 27 Nov 2018
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?

Stephen on 26 Nov 2018
Edited: Stephen on 26 Nov 2018
idx = Velocity(:,3)==0;
vec = [1;-1];
Velocity(idx,4) = vec(randi(numel(vec),nnz(idx),1))
Danny Helwegen on 27 Nov 2018
Thx this works

Jos (10584) on 26 Nov 2018
Something like this?
idx = Velocity(:,3) == 0 % where to change
N = sum(idx) % how many to change
p = [-1 1] % change to one of these values
r = randi(numel(p), N, 1) % random indices into p
New4 = p(r) % create new column
Velocity(idx,4) = New4 % replace