Overwrite 'NaN' cells of an array with non NaN cells of another
5 次查看(过去 30 天)
显示 更早的评论
Hello,
i have a 3D array final_product(360,180,8) of satellite data over earth at 8 different wavelenghts. I also have a second 3D array B(360,180,3). There are a lot of empty cells (NaN). If a specific cell in array final_product is 'NaN' and the cell with same coordinates in array B is not 'NaN', i want the later to replace the cell in the array final_product, else, leave the original cell intact.
My progress is:
for i=1:1
filename=files(i).name;
A=ncread(filename,'Aerosol_Optical_Depth_Average_Ocean_QA_Mean');
final_product(:,:,2:8)=A;
B=ncread(filename,'Aerosol_Optical_Depth_Land_QA_Mean');
if final_product(isnan(final_product));
final_product(:,:,2:4)=B;
end
end
Ignore the "for" loop..
I get an error "NaN's cannot be converted to logicals"
If anyone can halp, Thanks in advance!
0 个评论
采纳的回答
neil jerome
2020-10-28
hi vasilis,
have a look through this: rather than using a loop (which should work fine, but probably slower) you can use indexing. comments below hopefully helpful; since you describe matrices of different sizes, there's an extra step to make them equal. there's lots of equivalent ways of working around this, depending how many assumptions you want to make (ie are the data always the same size, etc).
%% this part shows the logic
% simple 1D or 2D data (equal size)
FinalProduct = NaN(1,6); FinalProduct(4) = 45; B = NaN(1,6); B(3) = 12;
% FinalProduct = NaN(5); FinalProduct(find(eye(5))) = 123; B = fliplr(FinalProduct)/2;
% these are the indices you want to replace
targetIndices = find(isnan(FinalProduct) .* ~isnan(B));
%replace these indices in a using values from b
NewResult = FinalProduct; % just to illustrate
NewResult(targetIndices) = B(targetIndices);
% display output for sanity check
FinalProduct
B
NewResult
%% for the data you described:
% for 3D data of unequal dimensions, 'easiest' (?) to make dummy for B
% this allows the earlier logic to work exactly the same
% strictly, this assumes FinalProduct > B, otherwise need to 'fill out' smaller to fit larger
%% Read in your data here
% FinalProduct =
% B =
sizeOfFinalProd = size(FinalProduct);
sizeOfB = size(B);
dummyB = NaN(sizeOfFinalProd);
dummyB(1:sizeOfB(1),1:sizeOfB(2),1:sizeOfB(3)) = B; % or as many dimensions as needed :)
% now FinalProduct and dummyB are the same size, with B padded out with NaN
targetIndices = find(isnan(FinalProduct) .* ~isnan(dummyB));
NewResult = FinalProduct;
NewResult(targetIndices) = dummyB(targetIndices);
2 个评论
neil jerome
2020-11-1
no problem, glad it helped! grateful if you could 'accept' the answer :) cheers, n.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!