user3396151
user3396151

Reputation:

Output of class function in Matlab

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

Upvotes: 1

Views: 1115

Answers (1)

Jonas
Jonas

Reputation: 74940

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);

Upvotes: 2

Related Questions