如何找到具有负值的索引并将其替换为恰好为正的最接近的索引值? [英] How to find indices with a negative value and replace the value with the nearest index's value that happens to be positive?
问题描述
我知道如何从矩阵中找到具有负值的索引.
I know how to find indices with a negative value from a matrix.
matrix(matrix<0) = %something should be done;
但是不知道如何用恰好为正的最接近的索引值替换它们的值.
But don't know how to replace their values with the nearest index's value that happens to be positive.
-
此处最近的索引应位于放置观察到的索引的同一行.
The nearest index here should be in the same row where the observed index is laid.
如果该行中没有索引为正的索引,则该行的每个索引都应插入0.
If there is no index with a positive value in the row, 0 should be interpolated to every index of that row.
如果在同一行中有多个索引最接近观察到的索引,请选择正确的索引.
If there is more than one index that is the nearest to the observed index in the same row, choose the right one.
我正在处理1003x1170单矩阵.因此,最好的解决方案是不带太多开销.
I am dealing with 1003x1170 single matrix. So it would be best if the solution doesn't come with so much overhead.
例如,
[-255 4 6;
-5 -4 5;
-400 3 6;
-6 -7 -8;
3 -5 4]
成为
[4 4 6;
5 5 5;
3 3 6;
0 0 0;
3 4 4]
推荐答案
You can do it using the fillmissing
function, as follows:
- 用
NaN
替换负值.之所以需要这样做,是因为对于single
或double
输入,fillmissing
会将NaN
条目视为缺失值. - 将
fillmissing
与'nearest'
选项一起使用,并沿尺寸2
操作.如果有两个等距的数据值,显然fillmissing
会选择右边的一个(我没有找到这个文档,并且我无法从源代码中确认它). - 用
0
替换所有剩余的NaN
值(对应于不包含非负值的行).
- Replace negative values by
NaN
. This is needed because, forsingle
ordouble
input,fillmissing
considersNaN
entries as missing values. - Use
fillmissing
with the'nearest'
option and operating along dimension2
. If there are two equidistant data values,fillmissing
apparently chooses the one to the right (I haven't found this documented, and I haven't been able to confirm it from the source code). - Replace any remaining
NaN
values (corresponding to rows that didn't contain non-negative values) by0
.
matrix = [-255 4 6; -5 -4 5; -400 3 6; -6 -7 -8; 3 -5 4]; % data
matrix(matrix<0) = NaN; % step 1
matrix = fillmissing(matrix, 'nearest', 2); % step 2
matrix(isnan(matrix)) = 0; % step 3
这篇关于如何找到具有负值的索引并将其替换为恰好为正的最接近的索引值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!