I am running an M file from another M file. I need to access the variables of first m file from the second.
MATLAB: I need to access variables of the file from one m file to another
m-filevariable
Related Solutions
M files can contain scripts or functions but variables can only be passed to functions so the m-file must be written as a function [see Scripts vs Functions and Create Function in Files].
For example,
mfile2
function [output] = mfile2(input) % add 1 to the input and pass the result to mfile2.
y = input + 1; % Send y to mfile1 and get the result
% mfile1 divides y by 2 to z equals (input+1)/2
z = mfile1(y); end
mfile1
function [output] = mfile1(input) % divide the input by two
output = input/2;end
All variables needed in a function must either be passed into the function as inputs or defined within the function. If your functions interact with your GUI, pass the handle structure into the function.
MATLAB: How to include many uicontrol object definition defined in one .m file into another . m file
- 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.
- 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);endfunction [a,b] = fcn1(c,d)...endfunction [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);endfunction [a,b] = fcn1(c,d)...endfunction [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.
Best Answer