a simple object code pattern using struct
3 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
Walter Roberson
2021-6-10
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 个评论
Walter Roberson
2021-6-10
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!