如何找到具有负值的索引并将其替换为恰好为正的最接近的索引值? [英] How to find indices with a negative value and replace the value with the nearest index's value that happens to be positive?

查看:144
本文介绍了如何找到具有负值的索引并将其替换为恰好为正的最接近的索引值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何从矩阵中找到具有负值的索引.

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.

  1. 此处最近的索引应位于放置观察到的索引的同一行.

  1. 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:

  1. NaN替换负值.之所以需要这样做,是因为对于singledouble输入,fillmissing会将NaN条目视为缺失值.
  2. fillmissing'nearest'选项一起使用,并沿尺寸2操作.如果有两个等距的数据值,显然fillmissing 会选择右边的一个(我没有找到这个文档,并且我无法从源代码中确认它).
  3. 0替换所有剩余的NaN值(对应于不包含非负值的行).
  1. Replace negative values by NaN. This is needed because, for single or double input, fillmissing considers NaN entries as missing values.
  2. Use fillmissing with the 'nearest' option and operating along dimension 2. 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).
  3. Replace any remaining NaN values (corresponding to rows that didn't contain non-negative values) by 0.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆