a simple object code pattern using struct

I am wondering if this is a good practice to create a simple object using the struct in Matlab!
See below code
% These are experimental and are not recommended to use
function u = afs()
u=struct;
u.r = [];
u.p = @(r) fn(r);
u.g = @(omega) plt(omega);
function y=fn(x)
for i=1:10
y=x+i;
end
end
function plt(omega)
x=linspace(-pi,pi);
y=sin(omega.*x);
plot(x,y)
title('Object plot')
end
end
Then you can have
w=afs;
>> w.r=2;
>> w.p(4)
ans =
14
>> w.g(2.5)
>>
I know we can use OOP in Matlab, but this is a very simple object paeetrn and very handy!
What do you think?
Is this a good practice?

Answers (1)

C++'s implementation of classes started by cross-compiling the C++ to C with the methods represented as fields in a struct that were pointers to functions. So the approach is usable.
C++ eventually got its own native implementation in which methods were implemented a bit differently. This was for performance reasons for one thing, but also changes in the way that C++ keeps track of information about which method matches which kinds of inputs; also, changes in the way that C++ keeps track of class hierarchies and inheriting .

3 Comments

Thanks Walter!
Why the OOP may be recommended here, but for simple purposes and just to encapsulate data and methods in an undergraduate numerical course, this may be helpful!
So, as you confirmed the method is usable and not a bad practice I like to go for that!
It is the classic way that the Unix I/O subsystem was implemented. An initialization routine would be called on a device driver, and the device driver was responsible for returning a struct of pointers to functions, with fields for tasks such as fopen(), fclose(), fread(), fwrite(), set_param(), get_param() . The higher level code would only have to know that ask to open the device, and the driver manager would get the driver to fill in the pointers. This made I/O to different kinds of devices much more flexible than the original CPM kind of organization where you had to know the detailed names of each different device's implementation functions.
Thank you for providing such insights!

Sign in to comment.

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Products

Release

R2020a

Asked:

on 10 Jun 2021

Commented:

on 10 Jun 2021

Community Treasure Hunt

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

Start Hunting!