问题
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.
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.
I am dealing with 1003x1170 single matrix. So it would be best if the solution doesn't come with so much overhead.
For example,
[-255 4 6;
-5 -4 5;
-400 3 6;
-6 -7 -8;
3 -5 4]
Becomes
[4 4 6;
5 5 5;
3 3 6;
0 0 0;
3 4 4]
回答1:
You can do it using the fillmissing function, as follows:
- 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
回答2:
Here is a possible solution:
- Iterate columns from right to left.
- Replace each negative value in the column with the value to the right.
- Make sure that the most right column (one past matrix bounds) is initialized with zeros.
Code sample:
A = [ -255 4 6
-5 -4 5
-400 3 6
-6 -7 -8
3 -5 4];
[rows, cols] = size(A);
P = zeros(rows, 1); %Column to the right of c initialize to zeros (like padding right side of A with zeros column).
%Loop over columns from right to left
for c = cols:-1:1
if c < cols
P = A(:, c+1); %Column to the right of c - assumed to be all positive (or zeros).
end
C = A(:, c); %Column c.
C(C < 0) = P(C < 0); %Replace negative elements with elements from right column (all elements in P are positive or zeros).
A(:, c) = C; %Replace column in C
end
Result:
A =
4 4 6
5 5 5
3 3 6
0 0 0
3 4 4
来源:https://stackoverflow.com/questions/59742108/how-to-find-indices-with-a-negative-value-and-replace-the-value-with-the-nearest