Prev Next sparse_jac_pattern_xam.m Headings

@(@\newcommand{\B}[1]{ {\bf #1} } \newcommand{\R}[1]{ {\rm #1} }@)@
Octave: Jacobian Sparsity Patterns: Example and Test
function ok = sparse_jac_pattern_xam()
     %
     % load the Cppad Swig library
     m_cppad
     %
     % initialize return variable
     ok = true;
     % -----------------------------------------------------------------------
     % number of dependent and independent variables
     n = 3;
     %
     % create the independent variables ax
     x = m_cppad.vec_double(n);
     for i = [ 0 :(n -1) ]
          x(i) = i + 2.0;
     end
     ax = m_cppad.independent(x);
     %
     % create dependent variables ay with ay[i] = ax[j]
     % where i = mod(j + 1, n)
     ay = m_cppad.vec_a_double(n);
     for j = [ 0 :(n -1) ]
          i = j+1;
          if( i >= n  )
               i = i - n;
          end
          ay_i = ax(j);
          ay(i) = ay_i;
     end
     %
     % define af corresponding to f(x)
     af = m_cppad.a_fun(ax, ay);
     %
     % sparsity pattern for identity matrix
     pat_in = m_cppad.sparse_rc();
     pat_in.resize(n, n, n);
     for k = [ 0 :(n-1) ]
          pat_in.put(k, k, k);
     end
     %
     % loop over forward and reverse mode
     for mode = [ 0 :(2-1) ]
          pat_out = m_cppad.sparse_rc();
          if( mode == 0  )
               af.for_jac_sparsity(pat_in, pat_out);
          end
          if( mode == 1  )
               af.rev_jac_sparsity(pat_in, pat_out);
          end
          %
          % check that result is sparsity pattern for Jacobian
          ok = ok && n == pat_out.nnz();
          col_major = pat_out.col_major();
          row = pat_out.row();
          col = pat_out.col();
          for k = [ 0 :(n-1) ]
               ell = col_major(k);
               r = row(ell);
               c = col(ell);
               i = c+1;
               if( i >=  n  )
                    i = i - n;
               end
               ok = ok && c == k;
               ok = ok && r == i;
          end
     end
     %
     return;
end

Input File: build/lib/example/octave/sparse_jac_pattern_xam.m