changeset 487:b43c4d841afe

Add isEquidistant function for testing vectors
author Jonatan Werpers <jonatan@werpers.com>
date Tue, 08 Aug 2017 08:26:25 +0200
parents e9e3973456c0
children 13d2f20c0c0d 95e41f7a6f1a
files isEquidistant.m isEquidistantTest.m
diffstat 2 files changed, 50 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
diff -r e9e3973456c0 -r b43c4d841afe isEquidistant.m
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/isEquidistant.m	Tue Aug 08 08:26:25 2017 +0200
@@ -0,0 +1,19 @@
+% Tests if consecutive elements of vector v are euidistant
+function b = isEquidistant(v)
+    if length(v) < 2
+        error('sbplib:isEquidistant:inputTooShort', 'Input vector is too short');
+    end
+
+    tol = 1e-8;
+
+    d = v(2:end) - v(1:end-1);
+    err = abs(d - d(1));
+
+    relErr = err./abs(d);
+
+    I_zero = find(d < tol);
+
+    relErr(I_zero) = err(I_zero);
+
+    b = all(relErr < tol);
+end
diff -r e9e3973456c0 -r b43c4d841afe isEquidistantTest.m
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/isEquidistantTest.m	Tue Aug 08 08:26:25 2017 +0200
@@ -0,0 +1,31 @@
+function tests = isEquidistantTest()
+    tests = functiontests(localfunctions);
+end
+
+function testTooShortInput(testCase)
+    testCase.verifyError(@()isEquidistant([]), 'sbplib:isEquidistant:inputTooShort')
+end
+
+function testCorrectOutput(testCase)
+    cases = {
+        % {input, expected},
+        {[0,0,0,0,0], true},
+        {[1,1,1,1,1], true},
+        {[1,2,3,4,5], true},
+        {[1,3,4,5], false},
+        {[1,2,3,5], false},
+        {[1,2,4,5], false},
+        {linspace(0,pi, 3), true},
+        {linspace(0,1, 4), true},
+        {linspace(0,1, 4123), true},
+        {linspace(0,sin(1), 123), true},
+    };
+
+    for i = 1:length(cases)
+        input = cases{i}{1};
+        expected = cases{i}{2};
+        result = isEquidistant(input);
+
+        testCase.verifyEqual(result,expected);
+    end
+end