annotate toolboxes/FullBNT-1.0.7/KPMtools/mk_stochastic.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function [T,Z] = mk_stochastic(T)
Daniel@0 2 % MK_STOCHASTIC Ensure the argument is a stochastic matrix, i.e., the sum over the last dimension is 1.
Daniel@0 3 % [T,Z] = mk_stochastic(T)
Daniel@0 4 %
Daniel@0 5 % If T is a vector, it will sum to 1.
Daniel@0 6 % If T is a matrix, each row will sum to 1.
Daniel@0 7 % If T is a 3D array, then sum_k T(i,j,k) = 1 for all i,j.
Daniel@0 8
Daniel@0 9 % Set zeros to 1 before dividing
Daniel@0 10 % This is valid since S(j) = 0 iff T(i,j) = 0 for all j
Daniel@0 11
Daniel@0 12 if (ndims(T)==2) & (size(T,1)==1 | size(T,2)==1) % isvector
Daniel@0 13 [T,Z] = normalise(T);
Daniel@0 14 elseif ndims(T)==2 % matrix
Daniel@0 15 Z = sum(T,2);
Daniel@0 16 S = Z + (Z==0);
Daniel@0 17 norm = repmat(S, 1, size(T,2));
Daniel@0 18 T = T ./ norm;
Daniel@0 19 else % multi-dimensional array
Daniel@0 20 ns = size(T);
Daniel@0 21 T = reshape(T, prod(ns(1:end-1)), ns(end));
Daniel@0 22 Z = sum(T,2);
Daniel@0 23 S = Z + (Z==0);
Daniel@0 24 norm = repmat(S, 1, ns(end));
Daniel@0 25 T = T ./ norm;
Daniel@0 26 T = reshape(T, ns);
Daniel@0 27 end