unexpected value for nargout when returning a class/struct

1 visualización (últimos 30 días)
Markus Leuthold
Markus Leuthold el 10 de Jun. de 2014
Editada: Philip Borghesani el 11 de Jun. de 2014
What values for nargout would you expect for the last two lines in the run block: 0 or 1?
Class A
classdef A < handle
methods
function r=fctA(~)
disp(['nargout=' num2str(nargout)])
r=B;
end
end
end
Class B
classdef B < handle
methods
function fctB(~,~)
end
end
end
run
a=A;
a.fctA.fctB;
a.fctA.fctB(1);
  2 comentarios
Matt J
Matt J el 10 de Jun. de 2014
Editada: Matt J el 10 de Jun. de 2014
I think the bigger surprise is that you can directly dot-index the output of a function call. Since when has that been possible????
Markus Leuthold
Markus Leuthold el 10 de Jun. de 2014
Editada: Markus Leuthold el 10 de Jun. de 2014
it only works with methods from new-style classes (classdef). Following code doesn't work, as you've expected:
function r=fcn
r.value=1;
end
this won't work
fcn.value
Even worse, this code crashes Matlab:
function matlabcrash
mytest.value
function a=mytest
a.value=1;
end
end
So I'm asking myself if dot-index the output of a method is illegal as well and only works by coincidence?

Iniciar sesión para comentar.

Respuestas (1)

Philip Borghesani
Philip Borghesani el 11 de Jun. de 2014
Editada: Philip Borghesani el 11 de Jun. de 2014
In general you cannot index into the output of a function call in MATLAB.
You have found an under documented feature of dot indexing on objects and a bug in that feature. The ability to index into the output of a dot function call on MATLAB class objects leaked into a previous version. This ability has always existed for Java objects. Because this feature just worked in many places it has been frequently exploited in MATLAB code and removing it would be quite difficult making supporting it necessary. In general we believe that the following code is more conformant MATLAB code for calling a method and will have similar performance:
a=A;
Bobj=fctA(a);
fctB(Bobj);
Nargout in your example code should be 1 and this is fixed in a future version of MATLAB. Note that a.fctA().fctB also returns 1.
I have entered a bug report for the crash with a nested function but I would not expect that code to be legal MATLAB code in the foreseeable future.
Information stated here is not an official guarantee of support or statement of policy from MathWorks.

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by