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

5 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

Stephen23
Stephen23 el 26 de Nov. de 2018
Editada: Stephen23 el 26 de Nov. de 2018
idx = Velocity(:,3)==0;
vec = [1;-1];
Velocity(idx,4) = vec(randi(numel(vec),nnz(idx),1))

Más respuestas (1)

Jos (10584)
Jos (10584) el 26 de Nov. de 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

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by