Updating GUI by using the function out of GUI

3 views (last 30 days)
Hi,
I'm trying to use my own function which is outside of GUI .m file and update GUI component (e.g updating static text). I don't wanna put the function in GUI m file, cuz there're a bunch of function I need and it'll be too nasty putting all functions in GUI m file. So I just wanna call funtion from GUI. Following is the script in GUI m file.
function pushbutton2_Callback(hObject, eventdata, handles
test();
This is my function.
function test()
set(handles.display, 'String','Hello');
But Matlab gives me error as followings.
-------------------------------------------------------------------
??? Error: File: f_gui.m Line: 273 Column: 1 Function definition is misplaced or improperly nested.
??? Undefined variable "handles" or class "handles.display".
Error in ==> test at 2 set(handles.display, 'String','Select either ''All'' or the numbers of HA'); Error in ==> f_gui>pushbutton2_Callback at 143 test();
Error in ==> gui_mainfcn at 96 feval(varargin{:});
Error in ==> f_gui at 42 gui_mainfcn(gui_State, varargin{:});
Error in ==> @(hObject,eventdata)f_gui('pushbutton2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
----------------------------------------------------------------
It seems that I can't access the GUI component from the function out of GUI. Can I use my function out of GUI? Then what is the prblem with my way?
Thanks.

Answers (1)

Steffen
Steffen on 6 Jan 2012
In any given function only variables that were given as input or defined within the function itself are known. While your function "test" is executed, the structure "handles" with the handles to the GUI objects is not defined. If you want to manipulate anything in your external function you need to give the handles as an input.
e.g.
function [handles_out] = test(handles)
set(handles.display, 'String','Hello');
handles_out = handles;
to make sure the handles structure is updated within your gui main function you need to update it
function pushbutton2_Callback(hObject, eventdata, handles)
handles = test(handles);
guidata(hObject, handles);
  1 Comment
YoungKwang
YoungKwang on 6 Jan 2012
I think I was not myself. I just missed a basic thing.
Thanks for reminding me, Steffen.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!