Convert a Nested Struct to a Class

Dear all,
I created a 3-layer nested structure in Matlab. Currently I name it as S. However, I will also need to have many variales with the same structure. I need S1, S2.....S100.
I realize that using class will be more helpful. If I have a class S_Class, my variables S1, S2.....S100 can be defined as:
  • S1 = S_Class;
  • S2 = S_Class;
Therefore, by using the class, I don't have to create the same structure for 100 times. Is my understaning correct?
If it is the case, how could I convert current 3-layer nested struct to a class?
Take the following code as an example
classdef S_Class
properties
V1
V2
V3
end
end
I would like V2 to be a stucture with several fields or even another structure inside. Is this possible?
Best regards,
Mingliang

3 个评论

"However, I will also need to have many variales with the same structure. I need S1, S2.....S100."
Having lots of numbered variables is a sign that you are doing something wrong. It invariably leads to beginners writing code where they force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
"Therefore, by using the class, I don't have to create the same structure for 100 times. Is my understaning correct?"
It is not clear how the use of a class would mean that you do not have to create 100 class instances.
Thanks for your help.
I do realize that defining so many variables is not necessary. I will read the tutorial carefully
Class properties can be anything you want, including objects of other classes or arrays of objects of other classes. They can be structs if you really want, though if you are converting the top level to classes I would strongly recommend converting the rest to appropriate classes too.
Objects can be stored in an array just like doubles so an array of 100 objects makes a lot more sense than 100 individual variables, each of 1 object.

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Structures 的更多信息

产品

版本

R2017a

评论:

2019-1-16

Community Treasure Hunt

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

Start Hunting!

Translated by