MATLAB: I need to access variables of the file from one m file to another

m-filevariable

I am running an M file from another M file. I need to access the variables of first m file from the second.

Best Answer

An example for using input arguments to provide (not "share") variables in a function:
% M-file "fcn1.m"
function fcn1
A = 5;
B = rand(1, 19);
T = fcn2(A, B);
disp(T);
end
% M-file "fcn2.m"

function R = fcn2(A, B)
R = A + 2 * B;
% Remember: this would work also:
% function RRRR = fcn2(AAAA, BBBB) would work also
% RRRR = AAAA + 2 * BBBB;
end
An alternative is using a "script" instead of a function: The only difference is, that it does not start with "function ..." and has no trailing "end":
% M-file "fcn2.m"
R = A + 2 * B;
In this case, the variables of the caller are shared and modified directly. This works, but as soon as you have many scripts or more than some hundreds lines of code, the confusion will explode. Scripts are much harder to debug, because the effects concerns code in other M-files. Therefore in productive code relying on the clarity of exactly defined inputs and outputs is essential: Use functions to make your life easier.
Related Question