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]
You can do it using the fillmissing
function, as follows:
NaN
. This is needed because, for single
or double
input, fillmissing
considers NaN
entries as missing values.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).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
Here is a possible solution:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.