user3535716
user3535716

Reputation: 255

Call a method of a class from a different script in MATLAB?

I want to call a method from a class. For example, I have:

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

When I call the method AddSection in a different script, like so:

  AddSection(sweepLine, Sections(i)); % Sections contains 10 section objects

I got this error:

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;

I guess this is because I did not do the memory preallocation, but I'm still not sure. I just moved to MATLAB OOP from Java, and feel that there are a tons of things that are hard to get well with.

Any help about this question and MATLAB programming is really appreciated!

Upvotes: 1

Views: 117

Answers (1)

rayryeng
rayryeng

Reputation: 104503

It looks like you are trying to concatenate the sections array with a new value. When you do this, you are assuming that obj.sections has already been allocated, and by doing that assignment you are getting that error. As such, what you have suspected is correct. To get around this, try doing this statement instead in your AddSections method for your class:

obj.sections = [obj.sections section];

This will concatenate section with the currently established obj.sections. This essentially adds section to the end of the array, which is what your previous code is doing. This is safe for empty arrays as well as allocated ones.


I would also recommend that your SweepLine class inherit from the handle class. I'm assuming that when you call AddSection, you don't want the object to be returned. You just want to modify the object, and return nothing...right? If this is the case, then you must inherit from the handle class. However, if you are returning the current instance of the object after each method call, then this isn't required.

In any case, you should do this:

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

Upvotes: 1

Related Questions