How to change a value in an array when a condition is met?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(1 个)
Jos (10584)
2018-11-26
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!