Is it possible to use the descriptor properties of the object returned by the function without first binding to a temporary variable?

I have a function that returns a handle to an object. Sort of:

function handle = GetHandle() handle = SomeHandleClass(); end 

I would like to be able to use the return value as if I were writing a program in C:

 foo = GetHandle().property; 

However, I get an error from MATLAB when it tries to parse this:

 ??? Undefined variable "GetHandle" or class "GetHandle". 

The only way to get this to work without error is to use a temporary variable as an intermediate step:

 handle = GetHandle(); foo = handle.property; 

Is there a simple and elegant solution to this, or is it just not possible with MATLAB syntax?

+4
source share
3 answers

To define static properties, you can use the CONSTANT keyword (thanks, @Nzbuu)

Here is one example from MathWorks (with some bug fixes):

 classdef NamedConst properties (Constant) R = pi/180; D = 1/NamedConst.R; AccCode = '0145968740001110202NPQ'; RN = rand(5); end end 

Permanent properties are accessed as className.propertyName , for example. NamedConst.R . Property values ​​are set whenever a class is loaded for the first time (after the start of Matlab or after clear classes ). This way, NamedConst.RN will remain constant throughout the entire session unless you call clear classes .

+2
source

Hmm, I don't like disagreeing with Jonas and his 21.7 thousand points, but I think you can do this using hgsetget instead of the usual descriptor class, and then using the get function.

 function handle = GetHandle() handle = employee(); end classdef employee < hgsetget properties Name = '' end methods function e = employee() e.Name = 'Ghaul'; end end end 

Then you can use the get function to get the property:

 foo = get(GetHandle,'Name') foo = Ghaul 

EDIT: It's not like C, but pretty close.

+1
source

The only way to have a static property in MATLAB is with a constant:

 classdef someHandleClass < handle properties (Constant) myProperty = 3 end end 

then someHandleClass.myProperty will return 3 .

+1
source

All Articles