Hi!
I'd like to create structures and store them, but I don't know how to do it. For example, for a function, we write something like
function f=MyFunction(arg1,...,argN)
...
end
and then we write the different operations. This allows us to write MyValue=MyFunction(...). I'd like to do the same for structures, something like MyObject=MyStruct(...). Could someone give me a reference document which explains how to do this for structures please? So far, the only thing I found is how to create structures from the command window. Thanks!

댓글 수: 2

Jan
Jan 2021년 11월 12일
Stucts can be defined in the code exactly as they are created in the command window. See:
doc struct
doc cell2struct
doc table2struct
Florian Spicher
Florian Spicher 2021년 11월 12일
I saw this doc. I might be wrong, but to create a structure like this we have to assign values to the fields right? Like stuct.field=sth. What I'd like is only have "a skeleton" of my struct, ie. only store its fields without any values assigned to them.

댓글을 달려면 로그인하십시오.

 채택된 답변

Jan
Jan 2021년 11월 12일

1 개 추천

MyStruct = cell2struct(cell(2, 1), {'field1'; 'field2'})
MyStruct = struct with fields:
field1: [] field2: []
Now the fields exist, but contain empty matrices only.

추가 답변 (1개)

Image Analyst
Image Analyst 2021년 11월 12일

1 개 추천

Not sure what you mean. You can call the function whatever you want and it can take in and return whatever you want. If you want to create a custom structure, there is already a function called struct() to do that.

댓글 수: 5

Florian Spicher
Florian Spicher 2021년 11월 12일
Oh ok! So I could write something like MyStuct=stuct('field1', 'field2',...) and just save it in a .m file? It would just be a one line file then?
Image Analyst
Image Analyst 2021년 11월 12일
편집: Image Analyst 2021년 11월 12일
I believe so. Call repmat() if you want to create an array of those structs.
Florian Spicher
Florian Spicher 2021년 11월 12일
Could you elaborate a bit on that, please? It's probably basic but I started to use Matlab like a few weeks ago and I literally discoverd structures an hour ago. Things aren't straight forward for me yet.
Looks like Jan showed you how to create one struct. If you want an array of them, call repmat():
MyStruct = cell2struct(cell(2, 1), {'field1'; 'field2'})
structArray = repmat(MyStruct, 5, 2 )
structArray will be a 5 by 2 array of structures.
If that helps, can you "Vote" for my answer?
Florian Spicher
Florian Spicher 2021년 11월 12일
Nice, it is definitely going to be useful to know that. Thanks a lot!
I already voted for your answer though!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

질문:

2021년 11월 12일

댓글:

2021년 11월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by