MATLAB: Pushbutton callback problem to update the colors in GUI. I want to update the background colors when the button is pushed and save the existing color values.

callbackguiguideMATLABpushbutton

This is my Opening function.
function untitled1_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for untitled1
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
z=rand()
background1=[z z z]
set(handles.axes1,'Color',background1);
i=rand()
background2=[i i i]
set(handles.axes2,'Color',background2);
a=rand()
b=rand()
c=rand()
backgroundStim=[a b c]
set(handles.axes3,'Color',backgroundStim);
set(handles.axes4,'Color',backgroundStim);
This is my pushbutton callback.
function pushbutton1_Callback(hObject, eventdata, handles)
handles=guidata(hObject);
bg1 = get(handles.axes1,'Color')
bg2 = get(handles.axes2,'Color')
bgStim = get(handles.axes3,'Color')
save('Output.mat','bg1','bg2','bgStim')
guidata(hObject, handles)
I want to present the next random colors in the GUI. In order to do that i need to call the opening function again right? I also want to save the existing color values and update the GUI.

Best Answer

Akshay - in your m-file, just create a separate function that randomly assigns colours to your four axes. This function will be called by both the OpeningFcn and the pushbutton callback. Something like
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% assign random colours to axes backgrounds

assignRandomColourBackgrounds(handles);
function pushbutton1_Callback(hObject, eventdata, handles)
% save colours
% assign random colours to axes backgrounds
assignRandomColourBackgrounds(handles);
function assignRandomColourBackgrounds(handles)
z=rand();
background1=[z z z];
set(handles.axes1,'Color',background1);
i=rand();
background2=[i i i];
set(handles.axes2,'Color',background2);
a=rand();
b=rand();
c=rand();
backgroundStim=[a b c];
set(handles.axes3,'Color',backgroundStim);
set(handles.axes4,'Color',backgroundStim);
So there is no need to call the opening function again. Instead we just call the function that assigns the random colour backgrounds whenever we need it.
As for saving the background colours to file, you will have to come up with a scheme to prevent you overwriting the colours saved to file on the last time the user pressed the button. You may just want to collect all the colours in an array (for each axes) and then when the GUI closes, save all the random colours to file then.