a simple object code pattern using struct

4 ビュー (過去 30 日間)
Mohammad Rahmani
Mohammad Rahmani 2021 年 6 月 10 日
コメント済み: Mohammad Rahmani 2021 年 6 月 10 日
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?

回答 (1 件)

Walter Roberson
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
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.
Mohammad Rahmani
Mohammad Rahmani 2021 年 6 月 10 日
Thank you for providing such insights!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeScope Variables and Generate Names についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by