create a class and a function which will return an optional variable in matlab

Here is an example of defining a class with a function that returns an optional variable:

main.m
classdef MyClass
    methods
        function out = myFunction(obj, in)
            if in > 0
                out = sqrt(in);
            else
                out = [];
            end
        end
    end
end
209 chars
12 lines

This class has one method, myFunction, which takes an input variable in and returns an output variable out. If in is greater than zero, the function returns the square root of in. Otherwise, it returns an empty matrix [].

To create an instance of the MyClass class and call the myFunction method, you can do the following:

main.m
% create an instance of the MyClass class
obj = MyClass();

% call the myFunction method with an input of 16
result1 = obj.myFunction(16); % result1 = 4

% call the myFunction method with an input of -1
result2 = obj.myFunction(-1); % result2 = []
248 chars
9 lines

In this example, result1 will be 4, and result2 will be an empty matrix [].

related categories

gistlibby LogSnag