Only returning NaNs when trying to do a double for loop
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!