Output of class function in Matlab

▼魔方 西西 提交于 2019-12-11 11:42:20

问题


I'm working with classes a long time ago but yet I couldn't get one thing that how to OUTPUT from a function/Constructor of like a function. I have seen multiple examples but coulnd't clear the point. Here I'v a simple example of myFunc outputting an array, and same function in class, How to output from class like a function. How to take output from any function of class just like a function?

myFunc:

function M=myFunc(n)
[M]=[];
i=0;
for ii=1:n
    M(ii)=i;
    %% Counter
    i=i+4;
end
end

MyClass:

    classdef myClass
        properties (Access=private)
            n
            M
            i
        end
        methods
            function obj = myClass(n)
                obj.n = n;
            end
            function myFunc(obj)

                for ii=1:obj.n
                    obj.M(ii)=obj.i;
                    %% Counter
                    obj.i=obj.i+4;
                end
            end
        end
    end

**EDIT 1:**
classdef myClass
    properties (Access=private)
        n
        M
        i
    end
    methods
        function obj = myClass(n)
            obj.n = n;
        end


    function M = myFunc(obj)

            for ii=1:obj.n
                obj.M(ii)=obj.i;
                %% Counter
                obj.i=obj.i+4;
            end
            M = obj.M;
    end
    end
end

回答1:


A method works just like a normal function, except that the first input of a non-static method is always expected to be a class instance

You call the method defined as

methods
   function [out1, out2] = fcnName(object, in1, in2)
      % do stuff here (assign outputs!)
   end
end

like so:

[out1, out2] = object.fcnName(in1,in2)

or

[out1, out2] = fcnName(object,in1,in2)

Applied to your example:

methods
    function M = myFunc(obj)

            for ii=1:obj.n
                obj.M(ii)=obj.i;
                %% Counter
                obj.i=obj.i+4;
            end
            M = obj.M;
     end
 end

you call myFunc as

 obj = myClass(3);
 M = myFunc(obj);


来源:https://stackoverflow.com/questions/23826559/output-of-class-function-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!