fill in zeros in a matrix

조회 수: 2 (최근 30일)
Mate 2u
Mate 2u 2013년 7월 9일
Hi all, I have a 1000x1 double matrix. It is full of numbers....but on some situations I get multiple 0s.
Whenever I encounter 0's, I want to fill the zeros with the average of the two numbers (the nearest non zero numbers above and below).
For example, if we had 3, 4, 0 ,3 , 2, 2, 0 ,0, 0, 3, 2, 1
we would get 3, 4, 3.5, 3, 2, 2, 2.5, 2.5, 2.5, 3, 2, 1.
The shorter and faster the code, the better....please remember the amount of consecutive zeros vary.

채택된 답변

Jan
Jan 2013년 7월 10일
x = [3, 4, 0 ,3 , 2, 2, 0 ,0, 0, 3, 2, 1];
m = (x == 0);
x(m) = interp1(find(~m), x(~m), find(m));

추가 답변 (1개)

Matt J
Matt J 2013년 7월 9일
I would recommend replacing the zeros with NaNs and using something like this,
instead.
  댓글 수: 1
Mate 2u
Mate 2u 2013년 7월 9일
Hi, looking for something much shorter and easier to implement, as it was a interview question....and would be nice to have something short which I can remember.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by