0

Do polymorphic returns exist in MATLAB? I wish I could say what I'd to be returned if a function calls one of the methods of an object and then specify that for calculations it returns a value from a designated property. But I'm probably asking nonsense now. Please confirm that I'm dreaming. Thanks.

1 Answer 1

2

You can't actually specify the return type in Matlab, you just return a value. The same function can easily return different types under different conditions. You can verify that there is no type information in function definitions by looking at the documentation.

For example, look at this function, which can return a string or matrix, based on the input argument:

function r = strange(arg)
   if arg == 1
       r = 'string';
   else
       r = [1, 2; 3 4];
   end
end

Now, that example may be handleable by static analysis, but consider this:

function r = evenstranger()
    if rand < 0.5
        r = 'string';
    else
        r = [1, 2; 3, 4];
    end
end

No way to know beforehand how that will turn out.

3
  • Thanks. That documentation link doesn't really demonstrate 'return different types under different conditions' though. What does 'different conditions' mean? Nov 24, 2015 at 9:15
  • @ZakiMohzani I've added an example of a function returning different types based on an argument or on some other argument. Nov 24, 2015 at 9:36
  • Yea, as I thought it would be. Thanks for the clarification. Nov 24, 2015 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.