From 4c1c0fdc1eab7fbe1e322ff651e9c98357a8ce15 Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Mon, 25 Feb 2013 10:03:55 -0500 Subject: [PATCH] Add diffusion_matrix_sparse() and its tests. --- diffusion_matrix_sparse.m | 26 ++++++++++++++++++++++++++ tests/diffusion_matrix_sparse_tests.m | 11 +++++++++++ 2 files changed, 37 insertions(+) create mode 100644 diffusion_matrix_sparse.m create mode 100644 tests/diffusion_matrix_sparse_tests.m diff --git a/diffusion_matrix_sparse.m b/diffusion_matrix_sparse.m new file mode 100644 index 0000000..dbe4e2a --- /dev/null +++ b/diffusion_matrix_sparse.m @@ -0,0 +1,26 @@ +function K = diffusion_matrix_sparse(integerN) + ## + ## A sparse representation of the matrix K in the advection-diffusion + ## equation. See advection_matrix.m for details. + ## + + if (integerN < 2) + K = NA; + return + end + + ## The negative ones directly above the diagonal. + top = [ [zeros(integerN-1, 1), -speye(integerN-1)]; ... + zeros(1, integerN)]; + + ## The negative ones directly below the diagonal. + bottom = [ [zeros(1, integerN-1); ... + -speye(integerN-1) ], zeros(integerN, 1)]; + + ## Combine the top and bottom. + K = top + bottom + 2*speye(integerN); + + ## Fill in the entries in the corner. + K(1, integerN) = -1; + K(integerN, 1) = -1; +end diff --git a/tests/diffusion_matrix_sparse_tests.m b/tests/diffusion_matrix_sparse_tests.m new file mode 100644 index 0000000..735c79b --- /dev/null +++ b/tests/diffusion_matrix_sparse_tests.m @@ -0,0 +1,11 @@ +expected_K = [2, -1, 0, 0, -1; + -1, 2, -1, 0, 0; + 0, -1, 2, -1, 0; + 0, 0, -1, 2, -1; + -1, 0, 0, -1, 2]; + +actual_K = diffusion_matrix_sparse(5); + +unit_test_equals("diffusion_matrix_sparse(5) looks right", ... + true, ... + isequal(actual_K, expected_K)); -- 2.33.1