Created
October 5, 2016 22:16
-
-
Save npyoung/b5aa17bfc14eff0cfe136ab2c248e9f7 to your computer and use it in GitHub Desktop.
A simple Java Vector-like class for Matlab.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
classdef Vec < handle | |
%VEC An efficient expandable array class | |
% Vec tries to emulate the behind-the-scenes array doubling behavior of the Vector class from Java. | |
properties(SetAccess = private, GetAccess = private) | |
ptr = 0 | |
data = [] | |
end | |
properties(Dependent) | |
length | |
end | |
methods | |
function obj = Vec(n) | |
if nargin == 1 | |
obj.data = zeros(n, 1); | |
end | |
end | |
function append(obj, x) | |
obj.ptr = obj.ptr + 1; | |
if obj.ptr > length(obj.data) | |
obj.grow(); | |
end | |
obj.data(obj.ptr,1) = x; | |
end | |
function l = get.length(obj) | |
l = obj.ptr; | |
end | |
function m = mean(obj) | |
m = mean(obj.data(1:obj.ptr,1)); | |
end | |
end | |
methods(Access = private) | |
function grow(obj) | |
len = length(obj.data); | |
obj.data = [obj.data zeros(len, 1)]; | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment