How to replace the numbers in matrix?
3 views (last 30 days)
_ on 18 Jan 2022
Here is a way to do it using linear interpolation on each row. It will interpolate between the non-zero numbers to fill in the zeros (at least two non-zero numbers are required on a given row in order to interpolate) and leave zeros at the beginning or end of the row unchanged. Demonstrated with a slightly more general case:
A = [1,2,3,0,5,6,0,8,9 ; 1,3,0,0,0,11,13,15,17; 0 0 0 0 0 0 0 0 0; 0 0 3 0 0 7 0 0 0]
c = 1:size(A,2);
for i = 1:size(A,1)
idx = A(i,:) == 0;
if nnz(~idx) < 2
A(i,idx) = interp1(c(~idx),A(i,~idx),c(idx),'linear',0);
More Answers (1)
Adam Danz on 17 Jan 2022
>I'm trying to replace the zeros to the intermediate numbers
I assume you mean you want to replace 0s with the value immediatly above or below the 0. If the entire columns contains 0s, nothing will change.
A = [1,2,3,0,5,6,0,8,9 ; 1,3,0,0,0,10,12,14,16]
A(A==0) = A(flipud(A)==0)