How to fill empty matrix elements based on surrounding values

조회 수: 9 (최근 30일)
I have a matrix with a lot of empty values and some numbers. A column could look like this (simplified for the sake of this question):
[1 0 0 0 5 0 0 0 0 0 8 0 3]'
The first and last element of the row is always non-zero.
Now I need to fill the matrix column per column, such that the zeros are replaced by linear interpolation values between the surrounding values as such:
[1 0 0 0 5 0 0 0 0 0 8 0 3]' %inital column
[1 2 3 4 5 5.5 6 6.5 7 7.5 8 5.5 3]' %filled column with linear interpolation
The way I would do it now is with loops and iterations: find a non-zero element, find the next non-zero element, replace the elements between those with linear interpolation values. Do this for all values in the column, and for each column.
This certainly is not the most optimal way of doing it. I don't see however how I could change this into a matrix operation, nor did I find a specific function or tool to do this. So I was wondering if anyone has suggestions on how optimise this, or knows a function that performs this operation?

채택된 답변

Stephen23
Stephen23 2022년 4월 6일
편집: Stephen23 2022년 4월 6일
V = [1;0;0;0;5;0;0;0;0;0;8;0;3];
The new approach:
Z = fillmissing(V + 0./(V~=0), 'linear', 1)
Z = 13×1
1.0000 2.0000 3.0000 4.0000 5.0000 5.5000 6.0000 6.5000 7.0000 7.5000
The old approach (repeat for each column if they have zeros in different locations):
Xi = find(V);
Xq = 1:numel(V);
Z = interp1(Xi,V(Xi),Xq(:))
Z = 13×1
1.0000 2.0000 3.0000 4.0000 5.0000 5.5000 6.0000 6.5000 7.0000 7.5000
  댓글 수: 1
Simon Allosserie
Simon Allosserie 2022년 4월 6일
Hi Stephen, this is exactly what I was looking for. Unfortunately my googling terms did not show up this useful function. Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2022년 4월 6일
You tagged it as "Image Processing". For an image, you might look at the function regionfill().
  댓글 수: 1
Simon Allosserie
Simon Allosserie 2022년 4월 7일
Indeed, because in the end it is a grayscale image that I'm edititing. However, the filling must be happening in columns (and not in regions) so the solution proposed by Stephen proved to be the fitting one here. regionfill is not giving the results I need at this moment. Thanks for your input though!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Image Segmentation and Analysis에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by