Leader

Saturday 21 March 2015

Alternative function: nansum (multi-dimensional)

Download
nansum.m

Explanation
See nanmean3 for a walk through of the code, the structure of the code is exactly the same, this version just uses SUM instead of MEAN.




Final code
function m=nansum3(data,dim)

if nargin == 1
    dim = 1;
end

dims=ndims(data);

% Permute data so target dimension is dimension 1
if dim>1
    dim_vec=1:dims;
    target_dims=dim:-1:1;
    dim_vec(1:length(target_dims))=target_dims;
    
    r_data=permute(data,[dim_vec]);
else 
    r_data=data;
end

% Perform nansum
r_data_size=size(r_data);
r_data_lin=r_data(:);

step=length(r_data(:,1));
ind=[0-(step-1), 0];
range=[1:length(r_data_lin)/length(r_data(:,1))];
sums=zeros(1,max(range));
for i= range
    ind=ind+step;
        
    col=r_data_lin(ind,1);
    m = sum(col(~isnan(col)));
    sums(i) = m;
end
sums=reshape(sums,[1, r_data_size(2:end)]);

% Permute back so target dimension goes back where it came from
if dim>1
    m=permute(sums,dim_vec);
else
    m=sums;
end

No comments:

AdSense