Chenming Zhang
Chenming Zhang

Reputation: 2566

a handle to shorten the name of stuct/class in matlab

I have a struct with relative sophisticated data trees. for example:

class.data.head{1}.data2

What I wish to get is a variable named data2_link to link with address class.data.head{1}.data2, so that:

(1) if there is any change on class.data.head{1}.data2, it will automatically reflected to data2_link as well, and vise versa.

(2) I do not have to type the long name to access the data at class.data.head{1}.data2.

Thanks!

Upvotes: 2

Views: 137

Answers (3)

Daniel
Daniel

Reputation: 36710

Just got another idea, you could use subsref to access it and subassign to write. It is not really what I would call a reference because you still need S, but it probably comes as close to it as possible without using OOP.

S=substruct('.','data','.','head','{}',{1},'.','data2')
%previous line is the same as: S=struct('type',{'.','.','{}','.'},'subs',{'data','head',{1},'data2'})
f=subsref(class,S)

Upvotes: 1

Daniel
Daniel

Reputation: 36710

Matlab does not support references. The only exception is handle which allows references to objects.

To use it, data2 must be an object with superclass handle, then you could simply write:

data2_link=class.data.head{1}.data2

Note that object oriented matlab significantly slows down your code unless you use Matlab 2015b or newer.

Upvotes: 4

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

There is an extremely discouraged way to do it. you can create a function handle that evaluates the desired expression:

data2_link = @() evalin('caller', 'class.data.head{1}.data2')

Now every time you need that expression just call it using

>> data2_link()

The extra parentheses are necessary to invoke the function defined by function handle.

Upvotes: 2

Related Questions