Arrays Matlab数组,它存储任意基的数字
这是我写的第一个Matlab代码,所以它可能相当粗糙 一位朋友在Matlab工作,他提到他们希望有一个数组,可以在任何基中获取和返回数字。这是我想出来的,但它不起作用Arrays Matlab数组,它存储任意基的数字,arrays,matlab,oop,Arrays,Matlab,Oop,这是我写的第一个Matlab代码,所以它可能相当粗糙 一位朋友在Matlab工作,他提到他们希望有一个数组,可以在任何基中获取和返回数字。这是我想出来的,但它不起作用 classdef BaseArray properties Value end methods function obj = BaseArray(Elements, Base) Value = base2dec(Elements, Base) end
classdef BaseArray
properties
Value
end
methods
function obj = BaseArray(Elements, Base)
Value = base2dec(Elements, Base)
end
function add (Obj, Element, Base)
% This might need some sort of "void" return type
Obj.Value = [Obj.Value base2dec(Element, Base)]
end
function get (Obj, Base)
% How do I get this to actually return
str2num(dec2base(Obj.Value, Base))
end
end
当我试着打电话时
a=BaseArray([011, 101, 110], 2)
从同一个文件(这是错误的?)我得到一个错误,说BaseArray没有定义
我希望全班同学都像这样工作:
a=BaseArray([2, 4, 8], 10)
a.Add(10, 3)
a.get(2)
% returns [10, 100, 1000, 11]
a = BaseArray({'2', '4', '8'}, 10);
有人能给我指一下正确的方向吗?你几乎可以让它工作了。让我们总结一下要使其充分发挥作用所需的更改: (1) 如果希望对象在运行方法后保持其更改,则需要从
handle
类继承。这可以通过将以下内容附加到classdef
定义中来实现:
classdef BaseArray < handle
请注意,我声明了一个字符串数组。我们不能将其放入一个普通数组中,否则字符串将相互连接,并形成一个单独的248
,这显然不是我们想要的
(3) 当您添加一个数字时,当您创建初始对象时,值
属性实际上将是一列数字,这是由于base2dec
的性质造成的。因此,您需要垂直地而不是水平地连接数字。因此,您的add方法需要是:
function add(obj, Element, Base)
%//This might need some sort of "void" return type
obj.Value = [obj.Value; base2dec(Element, Base)];
end
另外,请确保通过以下方式调用add
:
a.add('3', 10);
。。。不a.添加(10,3)
,就像以前一样。你翻了号码和底数。。。您还需要确保3
是一个字符串
(4) 您错过了get
方法末尾的end
语句
(5) get
方法几乎是正确的。您只需创建一个输出变量,并将调用从str2num
分配给该变量。因此:
function val = get(obj, Base)
%//How do I get this to actually return
val = str2num(dec2base(obj.Value, Base));
end
有了所有这些,这就是最终的类定义。确保将其保存到名为
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
b
为我们提供了:
b =
10
100
1000
11
{'2','4','8'}=arrayfun(@(x)num2str(x),[2,4,8],'UniformOutput',false)
@Yvon-尽管这肯定是等价的。。。。我喜欢{'2'、'4'、'8'}
更好:)。不过观察得不错。是的,我现在看到了。使用[2,4,8]
只能使用十进制输入。对于字符串,你可以使用{'A','10D'}
等等。@Yvon-Woah我完全忘记了十六进制。接得好@迟到总比不迟到好。谢谢你的接受。
b =
10
100
1000
11