Using a GUI to select a .m file, run the .m file and store the variables from .m file in workspace

2 views (last 30 days)
Hi,
I would like to open a GUI=>click a button to open a file browser for a .m file=>Select my .m file=> Display the selected file path and name on GUI=> run the .m file and store variables from .m file in the work space.
I cannot seem to have any luck with running the .m file from the GUI. The code I have written is:
% function CmdSelectFile_Callback(hObject, eventdata, handles)
% hObject handle to CmdSelectFile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[StrFileName,StrPathName] = uigetfile('*.m','Select the MATLAB code file');
StrFullPathName = strcat(StrPathName,StrFileName);
set(handles.TxtFileName,'String',StrFullPathName);
addpath(StrPathName);
StrRunFile = strrep(StrFileName, '.m', '')
run(StrRunFile)
Any help is much appreciated.
Cheers

Answers (1)

Walter Roberson
Walter Roberson on 6 May 2015
You do not need to remove the .m suffix; run() will remove it.
You do not need to addpath.
Remember that what you get out of uigetfile for the path does not include the directory separator character.
[StrFileName,StrPathName] = uigetfile('*.m','Select the MATLAB code file');
if ~ischar(StrFileName)
disp('User cancelled');
return
end
StrFullPathName = fullfile(StrPathName, StrFileName);
run(StrFullPathName);

Categories

Find more on Entering Commands in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!