How to Make a Huge Struct Accessible to Many Functions?

조회 수: 2 (최근 30일)
Rightia Rollmann
Rightia Rollmann 2017년 3월 17일
답변: Image Analyst 2017년 3월 17일
I have a huge struct loaded by a function. I have other functions that will use some of the fields of the struct to calculate something. What is the best way to make this struct accessible to all other functions? More info: this struct will only be read and no information by other functions will be overwritten on it.
  댓글 수: 1
Adam
Adam 2017년 3월 17일
I'm not really sure how this question differs from this one where you appeared to be asking the same thing and Steven Lord gave you a link that explains about sharing between callbacks.
The answer in general is still the same, though with specific code, which you haven't included, may vary.
The fact that you have a 'huge struct' needed by many functions in the first place sounds like the start of the problem. Functions should ideally be given no more than they need to perform their own task within the overall system.

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

채택된 답변

Jan
Jan 2017년 3월 17일
Avoid globals, because they impede the debugging and expanding of code.
If y struct is provided as input, only the struct pointer is copied, but Matlab does not duplicate the contents of the struct. Therefore it does not matter if the struct is huge or tiny. Forwarding the struct as an input will work efficiently. As long as you do not reply the struct as output, there is no danger of changing its contents "by accident".
But Adam's objection is correct in general: Providing all information to all subfunctions seems to be a bad design. If the code is large and written by multiple programmers, a modification of this struct will be dangerous, because it is hard to check, which functions are effected. The less data are forwarded, the less side-effects must be checked for modifications. Or in other words: The leaner the code, the less chances to fail.
Phew, don't ask me for a proof :-)

추가 답변 (2개)

KSSV
KSSV 2017년 3월 17일
Read about global. Make your structure a global variable, hence you can access in any function without sending into the function.

Image Analyst
Image Analyst 2017년 3월 17일

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by