Including files in matlab

189 views (last 30 days)
Raviteja
Raviteja on 10 Sep 2011
I have 2 files of file1.m file2.m
I have written some portion of the code in file1.m
I want to write the remaining code in file2.m
Variables resulted in file1.m have to use in file2.m
Means, I want to include file1.m into file2.m
What I have to do this?

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 10 Sep 2011
It seems like that you could benefit from going through the "Getting Started" portion of the MATLAB document.
If both are M-scripts, not M-function, you could simply add "file1" without the quote at the first line of file2.m. It will execute file1.m and then the rest of file2.m. All the variables in file1.m will be in the MATLAB base workspace and thus available to file2.m too.

More Answers (1)

Rick Rosson
Rick Rosson on 10 Sep 2011
One approach would be to make file1.m into a function that accepts input arguments when called by file2.m and returns output arguments back to file2.m.
Here is a very simple example of a MATLAB function with three input arguments and two output arguments:
function [ x, y ] = mytransform(a,b,c)
x = a*b + c;
y = b*c + a;
end
As a general rule, you should name the .m file with the same name as the name of the function in the function declaration. So in this case, you would want to save this function to a file named mytransform.m.
You can then call this function from the command line and/or from another MATLAB file (either a script or another function). Here is how you might call it from the command line:
>> [ u,v ] = mytransform(5,3,24);
This command should return:
u = 39
v = 77
Notice that I can pass literal numbers (or variables that are defined in the Workspace) as inputs to the function, and the names of the variables to which I ask it to assign the output arguments do not have to be the same as the names of the output arguments in the function definition itself.
HTH.
Rick

Community Treasure Hunt

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

Start Hunting!