Assigning classdef objects to other types does not automatically call existing converter methods

looking specifically at the example of Converters and Subscripted Assignment at Object Converters - MATLAB & Simulink

A = [1:5];
B = myclass
A(4) = B

the logic is supposedly that first it will look for a method of class myclass that matches the class of A, which would be double in this case. If no myclass method double exists, then it passes B as an argument to the A class constructor to see if it can handle a class of type myclass. if not it throws an error.

given a test class

classdef myclass
  properties
    ## no properties
  endproperties

  methods (Access = public)
    function this = myclass (varargin)
      if (nargin != 0 )
        error ("Invalid call");
      endif
    endfunction
  endmethods

  methods (Access = public)
    function retval = double (this)
      retval = NaN;
    endfunction

    function retval = single (this)
      retval = single (NaN);
    endfunction

    function retval = char (this)
      retval = ' ';
    endfunction
  endmethods
endclassdef

according to that description it should look to myclass, find the double() method, then return NaN.

however I instead get:

>> A(4)=B
error: operator =: no conversion for assignment of 'object' to indexed 'matrix'

am i doing it wrong, or does this just not work in Octave yet?

Sure looks like you’re doing it right. That’s how it works in Matlab.

I think this is not possible in Octave yet, also not with Octave 7.

However, if you help Octave’s interpreter a bit

A(4) = double(myclass)

it works :innocent:

Probably worth a bug report?

yeah, i could probably help it, but i was toying with creating a compatible form of missing. it looked easy, but requires casting the output according to the class of the item on the left side of the assignment. so compatible context means I can’t ‘help’ it, and I don’t know any other way to conditionally convert the output.

will create a bug report and add it to the classdef ‘todo’ list.

searching ‘converter’ on the bug list brings up GNU Octave - Bugs: bug #32651, Function precedence for derived... [Savannah]

seems this was an issue before classdef, so maybe a fix is just as ‘easy’ as that one was. new bug report created here: GNU Octave - Bugs: bug #61676, classdef converter methods are not... [Savannah]

1 Like