matrix differential FORMAT [dfdx] = pr_spm_diff(f,x,...,P,n) f - [inline] function f(x,P) x - argument[s] P - parameter[s] n - argument or parameter to differentiate w.r.t. dfdx - df(x,P)/dx{n} ___________________________________________________________________________ @(#)pr_spm_diff.m 2.1 Karl Friston 03/03/03
0001 function [J] = pr_spm_diff(varargin) 0002 % matrix differential 0003 % FORMAT [dfdx] = pr_spm_diff(f,x,...,P,n) 0004 % 0005 % f - [inline] function f(x,P) 0006 % x - argument[s] 0007 % P - parameter[s] 0008 % n - argument or parameter to differentiate w.r.t. 0009 % 0010 % dfdx - df(x,P)/dx{n} 0011 %___________________________________________________________________________ 0012 % @(#)pr_spm_diff.m 2.1 Karl Friston 03/03/03 0013 0014 0015 % create inline object 0016 %--------------------------------------------------------------------------- 0017 f = fcnchk(varargin{1}); 0018 x = varargin(2:(end - 1)); 0019 n = varargin{end}; 0020 dx = 1e-6; 0021 0022 if length(n) == 1 0023 0024 % dfdx 0025 %------------------------------------------------------------------ 0026 f0 = feval(f,x{:}); 0027 J = sparse(length(f0(:)),length(x{n}(:))); 0028 for i = 1:length(x{n}(:)) 0029 xi = x; 0030 xi{n}(i) = xi{n}(i) + dx; 0031 dfdx = (feval(f,xi{:}) - f0)/dx; 0032 J(:,i) = sparse(dfdx(:)); 0033 end 0034 else 0035 % dfdxdx 0036 %------------------------------------------------------------------ 0037 f0 = pr_spm_diff(f,x{:},n(1)); 0038 J = cell(1,length(x{n(2)}(:))); 0039 for i = 1:length(x{n(2)}(:)) 0040 xi = x; 0041 xi{n(2)}(i) = xi{n(2)}(i) + dx; 0042 dfdx = (pr_spm_diff(f,xi{:},n(1)) - f0)/dx; 0043 J{i} = sparse(dfdx); 0044 end 0045 end