How can I include many uicontrol object definition defined in one .m file into another . m file?

1 次查看(过去 30 天)
My Matlab Program includes many functions definitions and UIcontrol objects definitions. In order to reduce the number of lines of this script, I'd like to transfer all these definitions in an external .m file and recall it inside the main script. How can I proceed? Thank you for your help.

采纳的回答

Jan
Jan 2017-1-23
  1. Separate the GUI parts from the calculations. On one hand it is easier to debug or modify the calculationsm on the other hand you can change the GUI later much easier.
  2. If the callbacks of the UI-Controls contain calls to many different functions, you can either create one function file per function and store it in the same folder or the subfolder "\private". Or you can create one wrapper-file to obtain the function handles:
function FcnHandle = myWrapper(FuncName)
FcnHandle = str2func(FuncName);
end
function [a,b] = fcn1(c,d)
...
end
function [a,b,c] = fcn2(d)
...
end
...
Now the many functions files can be stored together in one file and you can get the function handles to define the callbacks like this:
fcn1 = myWrapper('fcn1');
ButtonH = uicontrol('Sytle', 'PushButton', 'Callback', {@myPushCB, fcn1});
...
function myPushCB(ObjectH, EventData, FcnHandle)
c = rand;
d = rand;
[a,b] = FcnHandle(c, d);
Hmmm. This works, but I'm not convinced, that this is smart: During debugging it is hard to get the inforamtion, which function is called in the callback. Another method might be nicer:
function [a,b,c,d] = myWrapper2(FuncName, varargin)
switch FuncName
case 'fcn1'
[a,b] = fcn1(varargin{1:2});
case 'fcn2'
[a,b,c] = fcn1(varargin{1});
otherwise
error('Unknown function: %s', FuncName):
end
...
FcnHandle = str2func(FuncName);
end
function [a,b] = fcn1(c,d)
...
end
function [a,b,c] = fcn2(d)
...
end
Now the bunch of functions can be called through one wrapper function:
function myPushCB(ObjectH, EventData, FcnHandle)
c = rand;
d = rand;
[a,b] = myWrapper2('fcn1', c, d);
This allows to see directly, which function is called.
This is only useful, if there is a need to keep all functions in one file. It would be easier to create one file per function, because then the wrapping is not needed.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by