changeset 184:d90f540f4137 feature/grids

Added sparse2cell function.
author Jonatan Werpers <jonatan@werpers.com>
date Thu, 03 Mar 2016 14:00:27 +0100
parents 3587cb106b54
children fad5e81389c1
files sparse2cell.m sparse2cellTest.m
diffstat 2 files changed, 71 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
diff -r 3587cb106b54 -r d90f540f4137 sparse2cell.m
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sparse2cell.m	Thu Mar 03 14:00:27 2016 +0100
@@ -0,0 +1,28 @@
+% sparse2cell breaks a sparse matrix up into a cell matrix of sparse matrices.
+% any zero submatrix creates a empty cell in the cell matrix.
+%  A -- NxM sparse matrix
+%  d1, d2 -- vectors of sub matrix sizes for each dimensions. Must have sum(di) == Ni.
+% Example:
+%   C = sparse2cell(A,[5 10], [10 5])
+function C = sparse2cell(A, d1, d2)
+    [n, m] = size(A);
+    if n ~= sum(d1) || m ~= sum(d2)
+        error('sparse2cell:NonMatchingDim','The elements of d1 and d2 must sum to N and M.');
+    end
+
+    C = cell(length(d1), length(d2));
+    I = 1;
+    for i = 1:length(d1)
+        J = 1;
+        for j = 1:length(d2)
+            Asub = A(I:(I + d1(i)-1), J:(J + d2(j)-1));
+            if nnz(Asub) == 0
+                C{i,j} = [];
+            else
+                C{i,j} = Asub;
+            end
+            J = J + d2(j);
+        end
+        I = I + d1(i);
+    end
+end
diff -r 3587cb106b54 -r d90f540f4137 sparse2cellTest.m
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sparse2cellTest.m	Thu Mar 03 14:00:27 2016 +0100
@@ -0,0 +1,43 @@
+function tests = sparse2cellTest()
+    tests = functiontests(localfunctions);
+end
+
+function testErrorNonMatchingDim(testCase)
+    in  = {
+        {magic(5), [1 2 3], [4]},
+        {magic(5), [1 1 1 1 1 1], [5]},
+        {magic(5), [5], [1 1 1 1 1 1]},
+        {ones(4,2),[2 3],[2]},
+        {ones(4,2),[2 2],[3]},
+    };
+
+    for i = 1:length(in)
+        testCase.verifyError(@()sparse2cell(in{i}{:}),'sparse2cell:NonMatchingDim');
+    end
+end
+
+function testOutput(testCase)
+    in = {};
+    out = {};
+    in{1}{1} =[17 24 1 8 15; 23 5 7 14 16; 4 6 13 20 22; 10 12 19 21 3; 11 18 25 2 9];
+    in{1}{2} = [1 4];
+    in{1}{3} = [2 3];
+
+    out{1} = {
+        [17 24], [1 8 15];
+        [23 5; 4 6; 10 12; 11 18], [7 14 16; 13 20 22; 19 21 3; 25 2 9];
+    }
+
+    in{1}{1} = [17 24 1 8 15; 23 5 0 0 0; 4 6 0 0 0; 10 12 0 0 0; 11 18 0 0 0];
+    in{1}{2} = [1 4];
+    in{1}{3} = [2 3];
+
+    out{1} = {
+        [17 24], [1 8 15];
+        [23 5; 4 6; 10 12; 11 18], [];
+    }
+
+    for i = 1:length(in)
+        testCase.verifyEqual(sparse2cell(in{i}{:}), out{i});
+    end
+end
\ No newline at end of file