How to evaluate an imported function, using uigetfile

Hello,
I'm importing a .m file using uigetfile, as follows
[file,path] = uigetfile('*.m','Select code file');
both of the returned values, file and path, are strings. What I'm trying to do is to evaluate a function, using as input the imported file, it would look something like this
function(file);
But because file is a string, it returns the error: Subscript indices must either be real positive integers or logicals, which makes sense
How can I evaluate the function using the file string?
I appreciate any suggestions. Thank you!

Answers (1)

Walter Roberson
Walter Roberson on 11 Jul 2015
Edited: Walter Roberson on 17 Jul 2015
Your code does not import that file, only finds its name.
The meaning of "importing" a .m file is not clear. Are you looking for a single continuous string which is the content of the file? A cell array of strings, one per line, that is the content of the file? Does the .m file contain a list of comma separated values? A bunch of data separated by spaces? Does the .m file need to be executed to produce data to import? If so then does the .m file contain a function that returns a value when run with no inputs? Does the .m file contain a script that when run will leave the relevant data in a variable with a known name?

2 Comments

Thank you for the answer. The file I'm trying to import has no data, it is in fact a function that takes as an input frequency . What I'm looking for is to import a function, say
imported_function.m
And I want to be able to execute that function.
I'm bulding a GUI and I'd like to let the user choose that function from any path in the computer, and then use imported_function.m in the the code I already have, instead of function.m (which is the function that is in my code). Have I explained that okay?
Thank you!
[file,path] = uigetfile('*.m','Select code file');
[~, name, ext] = fileparts(file);
path_here = pwd();
cd(path);
imported_function = str2func(name);
cd(path_here);
Now imported_function is a variable that is a function handle. It can be saved, passed around, and the function can be invoked
result = imported_function(arguments)
There are circumstances under which a different function, other than the file, could be invoked when you ask to run imported_function(), but you are not likely to run into those circumstances.

Sign in to comment.

Categories

Find more on App Building in Help Center and File Exchange

Asked:

on 10 Jul 2015

Commented:

on 17 Jul 2015

Community Treasure Hunt

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

Start Hunting!