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

1 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

回答(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