a simple object code pattern using struct

2 visualizaciones (últimos 30 días)
Mohammad Rahmani
Mohammad Rahmani el 10 de Jun. de 2021
Comentada: Mohammad Rahmani el 10 de Jun. de 2021
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?

Respuestas (1)

Walter Roberson
Walter Roberson el 10 de Jun. de 2021
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 comentarios
Walter Roberson
Walter Roberson el 10 de Jun. de 2021
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.
Mohammad Rahmani
Mohammad Rahmani el 10 de Jun. de 2021
Thank you for providing such insights!

Iniciar sesión para comentar.

Categorías

Más información sobre Scope Variables and Generate Names en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by