function m = nanreplace(m,val,mode) <m> is a matrix <val> (optional) is a scalar. default: 0. <mode> (optional) is 0 means replace all NaNs in <m> with <val>. 1 means if the first element of <m> is not finite (i.e. NaN, -Inf, Inf), fill entire matrix with <val>. 2 means if it is not true that all elements of <m> are finite and real, fill entire matrix with <val>. 3 means replace any non-finite value in <m> in <val>. default: 0. example: isequal(nanreplace([1 NaN],0),[1 0]) isequal(nanreplace([NaN 2 3],0,1),[0 0 0])
0001 function m = nanreplace(m,val,mode) 0002 0003 % function m = nanreplace(m,val,mode) 0004 % 0005 % <m> is a matrix 0006 % <val> (optional) is a scalar. default: 0. 0007 % <mode> (optional) is 0008 % 0 means replace all NaNs in <m> with <val>. 0009 % 1 means if the first element of <m> is not finite (i.e. NaN, -Inf, Inf), fill entire matrix with <val>. 0010 % 2 means if it is not true that all elements of <m> are finite and real, fill entire matrix with <val>. 0011 % 3 means replace any non-finite value in <m> in <val>. 0012 % default: 0. 0013 % 0014 % example: 0015 % isequal(nanreplace([1 NaN],0),[1 0]) 0016 % isequal(nanreplace([NaN 2 3],0,1),[0 0 0]) 0017 0018 % input 0019 if ~exist('val','var') || isempty(val) 0020 val = 0; 0021 end 0022 if ~exist('mode','var') || isempty(mode) 0023 mode = 0; 0024 end 0025 0026 % do it 0027 switch mode 0028 case 0 0029 m(isnan(m)) = val; 0030 case 1 0031 if ~isfinite(m(1)) 0032 m(:) = val; 0033 end 0034 case 2 0035 if ~all(isreal(m(:)) & isfinite(m(:))) 0036 m(:) = val; 0037 end 0038 case 3 0039 m(~isfinite(m)) = val; 0040 end