How can I average every other value in a 500 by 500 matrix

조회 수: 1 (최근 30일)
Martin Jordan
Martin Jordan 2019년 8월 20일
답변: Kritika Bansal 2019년 8월 23일
I have a matrix that is missing every other value and i am trying to interpolate it by taking the value of the number before and after and averaging the 2
this is what I have so far but it is not working any help is greaty appreciated!
[M,N] = size(B)
for i = 1:N
if N(i) == 0
H(i) = (N(i-1) + N(i+1))/2
else
H(i) = N(i)
end
end
for j = 1:M
if M(j) == 0
K(j) = (M(j-1) + M(j+1))/2
else
K(j) = M(j)
end
end
disp(B)
  댓글 수: 3
Martin Jordan
Martin Jordan 2019년 8월 21일
the pattern is
0 A 0 B 0 C
D 0 E 0 F 0
0 G 0 H 0 I

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

답변 (1개)

Kritika Bansal
Kritika Bansal 2019년 8월 23일
Hi,
There are few ways to do so in MATLAB. Some of them are listed below:
  1. Using interp2 function of MATLAB. As per my understanding of this function, if your data is non gridded, then there is a possibility that all the missing values are not interpolated. You can read more about this function here: https://www.mathworks.com/help/matlab/ref/interp2.html
  2. Using inpaint_nans function from the file exchange available at https://www.mathworks.com/matlabcentral/fileexchange/4551-inpaint_nans
If you want to do the averaging of the neighbours as you mentioned, you can take a look at the following code:
%x is the input matrix
[m,n] = size(x);
y=zeros(m,n);
for i=1:m
for j=1:n
if x(i,j)==0
if j==1
l=j;
else
l=j-1;
end
if j==n
r=j;
else
r=j+1;
end
val = (x(i,l)+x(i,r))/2;
y(i,j) = val;
else
y(i,j) = x(i,j);
end
end
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by