Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you nest anonymous functions in default values for MATLAB classes?

In MATLAB, it seems like you can nest anonymous functions like this:

>> x = @() @() 1
x =
  function_handle with value:
    @()@()1

I run into problems, however, when doing this in default values for class properties. For example, if I define a class

classdef MyClass
    properties
        Property1 = @() @() 1
    end
end

and construct an instance, I get an error.

>> MyClass
Invalid default value for property 'Property1' in class 'MyClass':
Error: Invalid use of operator. 

What's up with this? Is there a way to do this properly?

(MATLAB R2019b)

Edit: Here is an interesting workaround that does not raise errors:

classdef MyClass
    properties
        Property1 = someLocalFcn
    end
end

function out = someLocalFcn
    out = @() @() 1;
end
like image 411
Duncan MacIntyre Avatar asked Jan 01 '26 02:01

Duncan MacIntyre


1 Answers

You might consider upgrading to MATLAB 2020a, your code works as expected:

>> x=MyClass

x = 

  MyClass with properties:

    Property1: @()@()1

>> y=x.Property1

y =

  function_handle with value:

    @()@()1

>> z=y()

z =

  function_handle with value:

    @()1

>> z()

ans =

     1
like image 106
Daniel Avatar answered Jan 04 '26 04:01

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!