convert struct in class?

7 visualizzazioni (ultimi 30 giorni)
Luca Re
Luca Re il 31 Ott 2023
Risposto: Walter Roberson il 31 Ott 2023
in my code I created a structure but when I use its data I have to call some methods .
Is it better to convert the structure into a class? (Would my speed deteriorate?)

Risposta accettata

Walter Roberson
Walter Roberson il 31 Ott 2023
class method invocations are generally slower than calling a fixed function name passing in an input.
On the other hand, if you are using handle classes, there can be advantages in not having to copy as much around, and advantages in conveniently updating all references to a particular instance.
Suppose that you your equity_base has different fields (or importantly different interpretations) than equity_stat, but suppose that it made sense to want to "plot" the respective values. The most common designs for that kind of architecture would probably be:
  • have distinct plot_equity_base and plot_equity_stat functions that do those specific tasks, and expect the user to call the right version on the right structure; Or
  • have a field in the equity_base and equity_stat structures that identifies which variety of structure each is; now write a single plot_equity function that can take either structure and which looks at the identification field to figure out which internal plotting routines to use; OR
  • have fields named things like 'plot' and 'disp' and whatever inside the two struct, that is populated with function handles, and the expected user interface would be like equity_base.plot(equity_base) -- so each struct would have handles to the functionality specific to the struct variety; OR
  • use seperate (sub-) classes for the two struct, and associate plot and whatever methods with the classes; then the user can invoke equity_base.plot() or plot(equity_base) to have the proper function invoked automatically.
The first of these would involve (one public function for each different operation to be performed) times (number of different structures).
The second of the list would involve one public function for each different operation to be performed (that then invokes appropriate private functions to do the work)
The third of the list would effectively need a "constructor" function for each different kind of structure, which filled in the slots with handles to appropriate private functions.
The last on the list involves classdef for each class or subclass. It is the most flexible in times of writing robust interfaces (such as creating set and get routines and triggering behaviours when various actions happen such as assigning new values to components.) But the flexibility does have a cost.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by