从MATLAB中的不同脚本调用类的方法?
我想从类中调用一个方法。例如,我有:从MATLAB中的不同脚本调用类的方法?,matlab,Matlab,我想从类中调用一个方法。例如,我有: classdef SweepLine properties y; count; sections; end methods function obj = SweepLine(y) obj.y = y; obj.count = 0; end function AddSection(obj, section) obj
classdef SweepLine
properties
y;
count;
sections;
end
methods
function obj = SweepLine(y)
obj.y = y;
obj.count = 0;
end
function AddSection(obj, section)
obj.count = obj.count + 1;
fprintf('%d\n', obj.count);
fprintf('Indext is: %d\n', section.index);
obj.sections(obj.count) = section;
end
end
end
当我在另一个脚本中调用方法AddSection
时,如下所示:
AddSection(sweepLine, Sections(i)); % Sections contains 10 section objects
我得到了这个错误:
The following error occurred converting from Section to double:
Error using double
Conversion to double from Section is not possible.
Error in SweepLine/AddSection (line 20)
obj.sections(obj.count) = section;
我猜这是因为我没有做内存预分配,但我仍然不确定。
我刚从Java转到MatlabOOP,感觉有很多东西很难处理
非常感谢您对这个问题和MATLAB编程的任何帮助 看起来您正在尝试将
节
数组与新值连接起来。当您这样做时,您假设已经分配了obj.sections
,通过分配,您将得到该错误。因此,你所怀疑的是正确的。要解决此问题,请尝试在类的AddSections
方法中执行以下语句:
obj.sections = [obj.sections section];
这将把节
与当前建立的对象节
连接起来。这实质上是将部分
添加到数组的末尾,这就是前面的代码所做的。这对于空阵列和已分配阵列都是安全的
我还建议您的
sweedline
类继承句柄
类。我假设当您调用AddSection
时,不希望返回对象。您只想修改对象,不返回任何内容…对吗?如果是这种情况,则必须继承句柄
类。但是,如果在每次方法调用后返回对象的当前实例,则不需要这样做
在任何情况下,您都应该这样做:
classdef SweepLine < handle
properties
y;
count;
sections;
end
methods
function obj = SweepLine(y)
obj.y = y;
obj.count = 0;
end
function AddSection(obj, section)
obj.count = obj.count + 1;
fprintf('%d\n', obj.count);
fprintf('Index is: %d\n', section.index);
obj.sections = [obj.sections section];
end
end
end
classdef扫掠线