% Nr of rows and columns
nrows = 30;
ncols = 30;
% Random raster with nrows and ncols
% as costs
C = rand(nrows,ncols);
% The number of cells in the cost raster
n = numel(C);
% Gray weighted distance transform including
% a back link (Transfer matrix)
[Z,T] = graydistwbl(C,1);
% Initial amount of water in each cell
R = ones(nrows,ncols);
% Solving the system of equations to
% calculate flow accumulation
V = (speye(n)-T')\R(:);
% Reshape back to matrix
V = reshape(V,nrows,ncols);
% ... and show
surf(Z,V)