/ concept-collection / jupyterlite-numbl-kernel
Sign in
concept-collection / jupyterlite-numbl-kernel
jupyterlite-numbl-kernel / demo / content / Vec2.m
35 lines · 893 BBlameHistoryRaw
1classdef Vec2
2 % A value class with operator overloading.
3 properties
4 x = 0
5 y = 0
6 end
7 methods
8 function obj = Vec2(x, y)
9 if nargin > 0
10 obj.x = x;
11 obj.y = y;
12 end
13 end
14 function r = plus(a, b)
15 r = Vec2(a.x + b.x, a.y + b.y);
16 end
17 function r = minus(a, b)
18 r = Vec2(a.x - b.x, a.y - b.y);
19 end
20 function r = mtimes(a, b)
21 % Scalar multiply, with the scalar on either side.
22 if isa(a, 'Vec2')
23 r = Vec2(a.x * b, a.y * b);
24 else
25 r = Vec2(b.x * a, b.y * a);
26 end
27 end
28 function n = norm(obj)
29 n = sqrt(obj.x^2 + obj.y^2);
30 end
31 function s = char(obj)
32 s = sprintf('(%g, %g)', obj.x, obj.y);
33 end
34 end
35end
moveopenescclose