changeset 206:50a323da7c7f feature/grids

blockmatrix: Added function to convert blockmatrix to a regular matrix.
author Jonatan Werpers <jonatan@werpers.com>
date Wed, 15 Jun 2016 16:31:24 +0200
parents f0ef314e2070
children d521e17f72b6
files +blockmatrix/toMatrix.m +blockmatrix/toMatrixTest.m
diffstat 2 files changed, 88 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/+blockmatrix/toMatrix.m	Wed Jun 15 16:31:24 2016 +0200
@@ -0,0 +1,26 @@
+function A = toMatrix(bm)
+    if ~blockmatrix.isBlockmatrix(bm)
+        error('blockmatrix:toMatrix:NotABlockmatrix', 'Input is not a blockmatrix');
+    end
+
+    div = blockmatrix.getDivision(bm);
+    n = div{1};
+    m = div{2};
+
+    N = sum(n);
+    M = sum(m);
+
+    A = sparse(N,M);
+
+    n_ind = [0 cumsum(n)];
+    m_ind = [0 cumsum(m)];
+
+    for i = 1:size(bm,1)
+        for j = 1:size(bm,2)
+            if isempty(bm{i,j})
+                continue
+            end
+            A(n_ind(i)+1:n_ind(i+1),m_ind(j)+1:m_ind(j+1)) = bm{i,j};
+        end
+    end
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/+blockmatrix/toMatrixTest.m	Wed Jun 15 16:31:24 2016 +0200
@@ -0,0 +1,62 @@
+function tests = toMatrixTest()
+    tests = functiontests(localfunctions);
+end
+
+function testError(testCase)
+    testCase.verifyError(@()blockmatrix.toMatrix([]), 'blockmatrix:toMatrix:NotABlockmatrix')
+end
+
+function testToMatrix(testCase)
+    cases = {
+        {
+            {},
+            [],
+        },
+        {
+            {1, 2; 3, 4},
+            [1,2; 3,4],
+        }
+        {
+            {
+            [2 2; 2 1], [1; 2];
+            [2 2], [1]
+            },
+            [2 2 1;
+             2 1 2;
+             2 2 1],
+        },
+        {
+            {
+            [2 2; 2 1], [];
+            [2 2], [1]
+            },
+            [2 2 0;
+             2 1 0;
+             2 2 1],
+        },
+        {
+            {
+            [2 2; 2 1], [];
+            [2 2], []
+            },
+            [2 2;
+             2 1;
+             2 2],
+        },
+        {
+            {
+            [2 2; 2 1], [1; 2];
+            [], []
+            },
+            [2 2 1;
+             2 1 2],
+        },
+    };
+
+    for i = 1:length(cases)
+        in = cases{i}{1};
+        out = full(blockmatrix.toMatrix(in));
+        expected = cases{i}{2};
+        testCase.verifyEqual(out, expected);
+    end
+end