Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从MATLAB中的不同脚本调用类的方法?_Matlab - Fatal编程技术网

从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扫掠线