Matlab Attempt to execute script as a function

15,282

Solution 1

I think what you want is:

master('config');

Solution 2

You almost had it! Enclosing the filename in single quotes and dropping .m should do the trick. The following works for me on Matlab R2011b (Linux) with the files master.m and config.m in the same folder.

master.m:

function X = master( filename )
eval(filename);
X = a^2;
end

config.m:

a = 2;
disp('Testing config.m');

In console:

>> master('config')
Testing config.m
ans =
     4
Share:
15,282
E.Cross
Author by

E.Cross

Updated on June 04, 2022

Comments

  • E.Cross
    E.Cross almost 2 years

    I have a matlab script, lets call it "master.m", that loads a file called "config.m". config.m contains all the variables used in master.m so that they can be changed easily without editing any of the code. Problem is, I am trying to get the main function in master.m to load config.m based on the user input. So basically I want the user to be able to specify the name of the file to load. For instance if config.m was called testing.m then the user could type at the matlab prompt:

    >> master(testing.m)
    

    and it would load up the file. BUT I can't figure out how to do this properly, I have looked into the eval function but it gives me an error. Here is the code I have as of now in master.m:

    function [X,Y] = master(file)
    eval(file)
    

    However when I run at the matlab prompt:

    >> master(config.m)  
    ??? Attempt to execute SCRIPT config as a function:
    /home/myusername/config.m
    

    I have also tried master('config.m'), master('./config.m'), master(config) and master(config.m) but to no avail

    Any ideas?

  • E.Cross
    E.Cross about 12 years
    Wow that was so simple! I suck at matlab syntax, but this worked!