Skip to content

Commit 221391a

Browse files
jajoetargos
authored andcommitted
feat: add norm method (#57)
Add norm computation with frobenius and max norms.
1 parent 7ddf722 commit 221391a

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

__tests__/matrix/utility.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,21 @@ describe('utility methods', () => {
110110
expect(() => m2.det()).toThrow(/square/);
111111
});
112112

113+
it('norm Frobenius', () => {
114+
var m1 = new Matrix([[1, 1, 1], [3, 3, 3], [1, 1, 1]]);
115+
expect(m1.norm()).toBeCloseTo(5.7445626465380286, 2);
116+
});
117+
118+
it('norm Frobenius 2', () => {
119+
var m1 = new Matrix([[1, 1, 1], [3, 3, 3], [1, 1, 1]]);
120+
expect(m1.norm('frobenius')).toBeCloseTo(5.7445626465380286, 2);
121+
});
122+
123+
it('norm max', () => {
124+
var m1 = new Matrix([[1, 1, 1], [3, 3, 3], [1, 1, 1]]);
125+
expect(m1.norm('max')).toBe(3);
126+
});
127+
113128
it('transpose rectangular', () => {
114129
var matrix = new Matrix([[0, 1, 2], [3, 4, 5]]);
115130
var transpose = matrix.transpose();

src/abstractMatrix.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -923,6 +923,27 @@ export default function AbstractMatrix(superCtor) {
923923
return prod;
924924
}
925925

926+
/**
927+
* Returns the norm of a matrix.
928+
* @param {string} type - "frobenius" (default) or "max" return resp. the Frobenius norm and the max norm.
929+
* @return {number}
930+
*/
931+
norm(type = 'frobenius') {
932+
var result = 0;
933+
if (type === 'max') {
934+
return this.max();
935+
} else if (type === 'frobenius') {
936+
for (var i = 0; i < this.rows; i++) {
937+
for (var j = 0; j < this.columns; j++) {
938+
result = result + this.get(i, j) * this.get(i, j);
939+
}
940+
}
941+
return Math.sqrt(result);
942+
} else {
943+
throw new RangeError(`unknown norm type: ${type}`);
944+
}
945+
}
946+
926947
/**
927948
* Computes the cumulative sum of the matrix elements (in place, row by row)
928949
* @return {Matrix} this

0 commit comments

Comments
 (0)