How to change a value in an array when a condition is met?
4 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
More Answers (1)
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
0 Comments
See Also
Categories
Find more on Holidays / Seasons in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!