Reputation: 975
I have a simple MATLAB GUI Code, find attached. All it does is when a button is pressed it runs a function.
However when I press this button twice, it is throwing an error
Undefined function 'GUI' for input arguments of type 'struct'.
Error in @(hObject,eventdata)GUI('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.pushbutton1, 'enable','off');
output = randomFunction();
a = 1
while(1)
a = a+1
if a == 4
break;
end
end
set(handles.pushbutton1, 'enable','on');
Upvotes: 0
Views: 374
Reputation: 65470
The issue is that randomFunction
must either change the current working directory or modify your PATH
such that the GUI function (GUI.m
) is no longer on the path and able to be found when you click the button the second time.
If you'd like to stop this behavior you have two options
The preferred option would be to modify randomFunction
to not make this modification. A function should always the user's environment to the way that it was before being called. You can easily do this by using onCleanup
within randomFunction
function randomFunction()
folder = pwd;
cleanup = onCleanup(@()cd(folder));
% Normal contents of randomFunction
end
The other option within randomFunction
though is to never use cd
. This is the best practice. You can use full file paths instead to access files
filename = fullfile(folder, 'image.png');
imread(filename)
If you can't modify randomFunction
you can modify your callback to remember what the current directory was before calling the function and then change it back after randomFunction
completes. I would actually recommend using onCleanup
to do this to ensure that the directory is changed back even if randomFunction
errors out
function pushbutton1_Callback(hObject, eventdata, handles)
set(handles.pushbutton1, 'enable', 'off');
% Make sure that when this function ends we change back to the current folder
folder = pwd;
cleanup = onCleanup(@()cd(folder));
output = randomFunction();
a = 1
while(1)
a = a+1
if a == 4
break;
end
end
set(handles.pushbutton1, 'enable','on');
Upvotes: 1