You almost have it working. Let's go through a summary of the changes you need to get this fully working:
(1) You need to inherit from the handle
class if you want your object to maintain its changes after you run through your methods. This can be done by appending the following to your classdef
definition:
classdef BaseArray < handle
Check out a related post on why this is so: How to modify properties of a Matlab Object
(2) base2dec
requires a string representation of the number. As such, you can't use an array of numbers or MATLAB is going to complain. As such, when you create an object of type BaseArray
, you need to do it like this:
a = BaseArray({'2', '4', '8'}, 10);
Take note that I declared a cell
array of strings. We can't throw this into a normal array, or else the strings will just concatenate with each other and it will form a single string of 248
, which is obviously not what we want.
(3) When you're adding in a number, when you created your initial object, your Value
property will actually be a column of numbers due to the nature of base2dec
. As such, you need to concatenate the numbers vertically instead of horizontally. As such, your add method needs to be:
function add(obj, Element, Base)
%//This might need some sort of "void" return type
obj.Value = [obj.Value; base2dec(Element, Base)];
end
Also, make sure you call add
this way:
a.add('3', 10);
... not a.add(10,3)
as you had it before. You flipped the number and the base... you also need to ensure that 3
is a string.
(4) You missed an end
statement at the end of the get
method
(5) The get
method is almost correct. You just have to create an output variable, and assign the call from str2num
to that variable. As such:
function val = get(obj, Base)
%//How do I get this to actually return
val = str2num(dec2base(obj.Value, Base));
end
With all of this, this is what your final class definition looks like. Make sure you save this to a file called BaseArray.m
:
classdef BaseArray < handle
properties
Value;
end
methods
function obj = BaseArray(Elements, Base)
obj.Value = base2dec(Elements, Base);
end
function add(obj, Element, Base)
obj.Value = [obj.Value; base2dec(Element, Base)];
end
function val = get(obj, Base)
val = str2num(dec2base(obj.Value, Base));
end
end
end
Going with your example, we thus have:
a = BaseArray({'2', '4', '8'}, 10);
a.add('3', 10);
b = a.get(2);
b
gives us:
b =
10
100
1000
11