1 |
function theResult = ncload(fileIn, varargin); |
2 |
|
3 |
% ncload -- Load NetCDF variables. |
4 |
% ncload('fileIn', 'var1', 'var2', ...) loads the |
5 |
% given variables of 'fileIn' into the Matlab |
6 |
% workspace of the "caller" of this routine. If no names |
7 |
% are given, all variables are loaded. |
8 |
|
9 |
global useNativeMatlabNetcdf; if isempty(useNativeMatlabNetcdf); useNativeMatlabNetcdf = ~isempty(which('netcdf.open')); end; |
10 |
|
11 |
f = ncopen(fileIn, 'nowrite'); |
12 |
if isempty(f), return, end |
13 |
vars=ncvars(f); |
14 |
if isempty(varargin); varargin = vars; end; |
15 |
|
16 |
if (useNativeMatlabNetcdf); |
17 |
|
18 |
for i = 1:length(varargin) |
19 |
if sum(strcmp(vars,varargin{i}))>0; |
20 |
%get variable |
21 |
varid = netcdf.inqVarID(f,varargin{i}); |
22 |
aa=netcdf.getVar(f,varid); |
23 |
%inverse the order of dimensions |
24 |
bb=length(size(aa)); aa=permute(aa,[bb:-1:1]); |
25 |
%replace missing value with NaN |
26 |
[atts]=ncatts(f,varid); |
27 |
if strcmp(atts,'missing_value')&isreal(aa); |
28 |
spval = double(netcdf.getAtt(f,varid,'missing_value')); |
29 |
elseif strcmp(atts,'_FillValue')&isreal(aa); |
30 |
spval = double(netcdf.getAtt(f,varid,'_FillValue')); |
31 |
else; |
32 |
spval=[]; |
33 |
end; |
34 |
if ~isempty(spval); aa(aa==spval)=NaN; end; |
35 |
else; |
36 |
aa=[]; |
37 |
end; |
38 |
assignin('caller', varargin{i}, aa) |
39 |
end |
40 |
|
41 |
|
42 |
|
43 |
|
44 |
else;%try to use old mex stuff |
45 |
|
46 |
|
47 |
for i = 1:length(varargin) |
48 |
if ~isstr(varargin{i}), varargin{i} = inputname(i+1); end |
49 |
oldfld = f{varargin{i}}(:); |
50 |
spval = f{varargin{i}}.missing_value(:); |
51 |
if isempty(spval); |
52 |
spval = f{varargin{i}}.FillValue_(:); |
53 |
end |
54 |
fld = oldfld; |
55 |
if ~isempty(spval)&~ischar(fld); |
56 |
replace = find(oldfld == spval); |
57 |
nreplace = length(replace); |
58 |
if nreplace>0 |
59 |
fld(replace) = NaN*ones(1,nreplace); |
60 |
end %if |
61 |
end %if |
62 |
%NaN-substitution messes up backward compatibility so I comment it out |
63 |
% assignin('caller', varargin{i}, fld); |
64 |
%and revert to oldfld |
65 |
assignin('caller', varargin{i}, oldfld) |
66 |
end |
67 |
|
68 |
end |
69 |
|
70 |
ncclose(f); |
71 |
|
72 |
result = varargin; |
73 |
|
74 |
if nargout > 0 |
75 |
theResult = result |
76 |
else |
77 |
ncans(result) |
78 |
end |
79 |
|