How to Share Data Between These Functions?

조회 수: 3 (최근 30일)
Rightia Rollmann
Rightia Rollmann 2017년 3월 15일
댓글: Jan 2017년 3월 15일
Imagine I have myfun1 that loads struct A from disk. I have other functions that should use some fields of A to do some calculations.
function myfun1
global A
A = open( 'C:\A.mat' )
end
function myfun2
global A
A.B = 1;
end
function myfun3
global A
A.C = 2;
end
What is the best solution to allow these functions have access to struct A? I thought of Global Variables, so I make struct A global and then use it wherever I want. Is there a safer and better solution?

답변 (1개)

Adam
Adam 2017년 3월 15일
편집: Adam 2017년 3월 15일
You haven't given any code that calls the functions, but the whole point of functions (or at least one of the main points) is that they take input arguments into a sealed workspace and then provide output arguments. Make use of them - pass your variable as n output argument from myfun1 and then just pass in the variables you need to the other functions, either the full struct or even just certain fields of it. Having a vast amount of data all on one struct is not a good design in the first place so multiple collections of data are generally better.
Don't use global variables though, they are bad for so many reasons (just do a google search or a search on this forum for global variables to see the overwhelming opinion on them) and have no place in proper code design, especially when you can simply pass arguments to a function to achieve the same thing.
  댓글 수: 3
Steven Lord
Steven Lord 2017년 3월 15일
For sharing data among callback functions of graphics objects in particular, see the techniques described in this documentation page.
Jan
Jan 2017년 3월 15일
+1 "Don't use globals" is a very valuable advice.
The topic is discussed frequently. Search in the forum for "share data between callbacks".

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

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by