A = [ 1 0 0 4
1 0 3 4
1 2 0 4
1 2 3 4];
D = [ 0 22.2794 33.7859 45.0000
22.2794 0 15.4008 23.0367
33.7859 15.4008 0 14.9726
45.0000 23.0367 14.9726 0];
d = size(A);
B = nonzeros(A');
jj = [B(1:end-1),B(2:end)];
jj = jj(diff(jj,1,2) > 0,:);
k = cumsum([true;diff(jj(:,1))<=0]);
idx = sub2ind(d,jj(:,1),jj(:,2));
t = jj(:,1) == 1;
p = 50*t;
p(~t) = 180;
result = accumarray(k,D(idx).*p);