Only returning NaNs when trying to do a double for loop

조회 수: 2 (최근 30일)
A LL
A LL 2021년 7월 5일
편집: A LL 2021년 7월 5일
I have a matrix of size (361,361) named sivTotEASE.
At specific index i.e. sivTotEASE(m,n) I want to compute the mean (omiting NaNs) of the 8 closest neighbors of sivTotEASE(m,n) and replace the computed value at the location of sivTotEASE(m,n).
I try to do this in a double for loop (first loop for the index corresponding to the rows and second loop for the index corresponding to the columns) but I end up with a matrix containing only NaNs. I don't even have the original values of my matrix anymore... It is just NaNs everywhere...
When I try to compute it manually I do get a real value. For exampe, for index m = 1000, n = 1000 I get the value 8.0114 and not NaN.
Here is my code:
%Load data (see attached files for data)
load('SICnoSIVrow.mat');
load('SICnoSIVcol.mat');
load('sivTotEASE.mat');
%Mean of the 8 closest neighbors for sivTotEASE(m,n)
sivTotNeighbor = sivTotEASE;
for m = SICnoSIVrow
for n = SICnoSIVcol
NeighborIt = nanmean(sivTotEASE(m-1:m+1,n-1:n+1),'all');
sivTotNeighbor(m,n) = NeighborIt;
end
end
%Manual test (the following line gives 8.0114)
%test = nanmean(sivTotEASE(m(1000)-1:m(1000)+1,n(1000)-1:n(1000)+1),'all')
Can anyone help me figure out what is the issue?
Thank you
****ACCEPTED ANSWER (see comments)****
%Edited code:
%Load data (see attached files for data)
load('SICnoSIVrow.mat');
load('SICnoSIVcol.mat');
load('sivTotEASE.mat');
%Compute neighbor's average
sivTotNeighbor = sivTotEASE;
for ii = 1:length(SICnoSIVrow)
for jj = 1:length(SICnoSIVcol)
m=SICnoSIVrow(ii);
n=SICnoSIVcol(jj);
NeighborIt = mean(sivTotEASE(m-1:m+1,n-1:n+1),'all','omitnan');
sivTotNeighbor(m,n) = NeighborIt;
end
end

채택된 답변

Amit Bhowmick
Amit Bhowmick 2021년 7월 5일
use this
mean(sivTotEASE(m-1:m+1,n-1:n+1),"omitNan")
  댓글 수: 11
A LL
A LL 2021년 7월 5일
편집: A LL 2021년 7월 5일
I missed your comment but I indeed think you are right with your suggestion to edit my code but jj and n would have to be for the variable SICnoSIVcol (and not for SICnoSIVrow):
for ii = 1:length(SICnoSIVrow)
for jj = 1:length(SICnoSIVcol)
m=SICnoSIVrow(ii);
n=SICnoSIVcol(jj);
This is also what I ended with (see comment above)!
Thank you

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by