Ayshaya
Ayshaya

Reputation: 57

In a Matlab gui how do you execute a .m file returned as a result of uigetfile?

I have a Matlab gui with a button that calls uigetfile. The user picks the file they want to run, and then my gui should execute that .m file, returning the results to the gui for further processing.

Uigetfile works great and I can capture the filename and filepath:

[filename, pathname] = uigetfile('*.m', 'Pick a .m file');

When I try to execute the filename:

total = [pathname filename];

% copy into current directory since files user selects could be in other directories
copyfile(total);   

% attempt to execute .m function the user selected
[a, b] = filename();

I get this error:

Indexing cannot yield multiple results.

My research suggests this is because I have a variable named "filename" so Matlab thinks I'm trying to use the variable, rather than call the function. This makes good sense to me, but then I don't know how to get around this!

How can I call the result of uigetfile without it also being a variable? Or, how else can I run a .m file selected by the user in a gui?

Thanks!

Upvotes: 1

Views: 905

Answers (2)

matlabgui
matlabgui

Reputation: 5672

I know this has already been answer and accepted but you might want to look at:

output = feval ( str2func ( filename(1:end-2) ) )

The (1:end-2) is to remove the .m

This way you can store the output of your function in the variable output. If your m-files have variable number of outputs you could store them in a struct or a cell array.

Just because a function has no inputs - I would not consider that the same as a script - your "script" could overwrite a lot of variables in your calling function and you wouldn't know... -> and thus it would be a nightmare to debug...

Upvotes: 1

brodoll
brodoll

Reputation: 1881

If you are in the same folder as the m.file, you can enclose the whole uigetfile call to the run function to execute it:

run(uigetfile('*.m', 'Pick a .m file'))

This way you avoid the naming conflict with you previously defined filename variable and call the result of uigetfile without storing its output. However if you want to run the script from a different folder, I'd suggest store the results of uigetfile with different names:

[filename, pathname] = uigetfile('*.m', 'Pick a .m file');
run([filepath filename])

This enables you to run the mfile without the need to copy it to the current folder, and still avoids any conflicts with your previously defined variable.

Upvotes: 1

Related Questions