Get data cursor callback in Matlab GUI - matlab

How can I set the Matlab GUI data cursor callback for a specific GUI axes?
I was able to add the data cursor icon in GUI toolbar. I can selected 3D point on the plotted data, but I need to add more info in the data cursor text and also do some other stuff with the coordinates it is getting.
I tried to follow "How to add additional info to the data cursor?", but doesn't work for GUI.
GUI axes are not figures, so I'm getting this error:
Error using datacursormode (line 149)
Invalid figure handle
I need the same here, but for GUI axes (figures?):
function test_main
% Plots graph and sets up a custom data tip update function
fig = figure('DeleteFcn','doc datacursormode');
X = 0:60;
t = (X)*0.02;
Y = sin(-16*t);
plot(X,Y)
dcm_obj = datacursormode(fig); % tried here "handles.MyFigHandle"
set(dcm_obj,'UpdateFcn',{#myupdatefcn,t})
function txt = myupdatefcn(~,event_obj,t)
% Customizes text of data tips
pos = get(event_obj,'Position');
I = get(event_obj, 'DataIndex');
txt = {['X: ',num2str(pos(1))],...
['Y: ',num2str(pos(2))],...
['I: ',num2str(I)],...
['T: ',num2str(t(I))]};
For now I can get only the default datacursor behavior, like this image:

I've not found any difference between the use of the data cursor in a GUI and in a figure.
Re-using part of your code, I've created a GUI in which a checkbox enable / disable the datacursormode.
The GUI contains two axes in which two lines and a 3D surface are plotted respectively.
Also three radiobuttons control the string that will be printed in the textbox generated when the datacursormode is enabled.
The tags of the GUI are the folowing:
left axes: axes_2d
right axes: axes_3d
left pushbutton: pushbutton_2d
right pushbutton: pushbutton_3d
checkbox: checkbox_enable_dc
left radiobutton: radiobutton1
middle radiobutton: radiobutton2
righ radiobutton: radiobutton3
The GUI works this way:
the pushbuttons plot in the axes and enable the checkbox
the checkbox enable / disable the datacursormode
by default, the left radiobutton is selected and sets the default string
the other two radiobutton set a different string
Based on the selected radiobutton, the first line of the string in the textbox will be either:
DEFAULT STRING
STRING OPTION ONE
STRING OPTION TWO
the string to be written in the textbox is created in your myupdatefcn that has been modified to handle the options selected by the radiobutton.
Notice: in order not to limit the modification to your version of the myupdatefcn function, I've hard coded the t array.
This is the .m file of the GUI:
function varargout = gui_datacursormode(varargin)
% GUI_DATACURSORMODE MATLAB code for gui_datacursormode.fig
% GUI_DATACURSORMODE, by itself, creates a new GUI_DATACURSORMODE or raises the existing
% singleton*.
%
% H = GUI_DATACURSORMODE returns the handle to a new GUI_DATACURSORMODE or the handle to
% the existing singleton*.
%
% GUI_DATACURSORMODE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI_DATACURSORMODE.M with the given input arguments.
%
% GUI_DATACURSORMODE('Property','Value',...) creates a new GUI_DATACURSORMODE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_datacursormode_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_datacursormode_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui_datacursormode
% Last Modified by GUIDE v2.5 02-Apr-2017 17:45:45
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #gui_datacursormode_OpeningFcn, ...
'gui_OutputFcn', #gui_datacursormode_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui_datacursormode is made visible.
function gui_datacursormode_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui_datacursormode (see VARARGIN)
% Choose default command line output for gui_datacursormode
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui_datacursormode wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = gui_datacursormode_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbutton_2d.
function pushbutton_2d_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_2d (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Plot two lines in the first axes
t=0:.1:2*pi;
plot(handles.axes_2d,t,sin(t),'r');
hold(handles.axes_2d,'on')
plot(handles.axes_2d,t,cos(t),'b');
% Enable the checkbox that will set datacorsormode on
handles.checkbox_enable_dc.Enable='on';
% --- Executes on button press in pushbutton_3d.
function pushbutton_3d_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_3d (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Plot a 3D graph in the second axes
axes(handles.axes_3d);
peaks
% Enable the checkbox that will set datacorsormode on
handles.checkbox_enable_dc.Enable='on';
function txt = myupdatefcn(~,event_obj,t)
% Customizes text of data tips
% Get the handles of the GUI to access to the radiobuttons
my_guidata=guidata(gcf);
% Define the additional string to be written
if(my_guidata.radiobutton1.Value)
str='DEFAULT STRING ';
elseif(my_guidata.radiobutton2.Value)
str='STRING OPTION ONE ';
else
str='STRING OPTION TWO ';
end
% Get the datacursor data
pos = get(event_obj,'Position');
I = get(event_obj, 'DataIndex');
% Create the whole string to be written
txt = {[str], ...
['X: ',num2str(pos(1))],...
['Y: ',num2str(pos(2))],...
['I: ',num2str(I)],...
['T: ',num2str(t(I))]}
% --- Executes on button press in checkbox_enable_dc.
function checkbox_enable_dc_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_enable_dc (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% If the checkbox is set
if(hObject.Value)
% enable the radiobuttons that control the string to be written
handles.radiobutton1.Enable='on';
handles.radiobutton1.Value=1;
handles.radiobutton2.Enable='on';
handles.radiobutton3.Enable='on';
% Create the datacursormode object
dcm_obj = datacursormode(gcf)
t=rand(1,10000);
set(dcm_obj,'DisplayStyle','datatip',...
'SnapToDataVertex','off','Enable','on', ...
'UpdateFcn',{#myupdatefcn,t})
else
% If the checkbox is not set, disable the datacursormode
datacursormode 'off'
end
% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
% Toggle the other radiobuttons
handles.radiobutton2.Value=0
handles.radiobutton3.Value=0
% --- Executes on button press in radiobutton1.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
% Toggle the other radiobuttons
handles.radiobutton1.Value=0
handles.radiobutton3.Value=0
% --- Executes on button press in radiobutton1.
function radiobutton3_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
% Toggle the other radiobuttons
handles.radiobutton1.Value=0
handles.radiobutton2.Value=0
Hope this helps,
Qapla'

Related

Connecting MATLAB GUI to .m file

I have a m file, which chops the signal and applies filter according to the cut off frequency(Fc).
M file:
classdef Container < handle
properties
segments = struct('signal', {}, 'time', {},'ref',{}); %empty structure with correct fields
end
methods
function this = addsignal(this, signal, time,fc)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%chopping of the signals%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
interval = diff(time);
[~, locations] = findpeaks(interval,'THRESHOLD',0.7);
edges = [0; locations; numel(signal)+1];
newsegments = struct('signal', cell(numel(edges)-1, 1), 'time', cell(numel(edges)-1, 1));
%this loop works for no peaks, 1 peak and more than one peak (because of the 0 and numel+1)
for edgeidx = 1 : numel(edges) - 1
newsegments(edgeidx).signal = signal(edges(edgeidx)+1 : edges(edgeidx+1)-1);
newsegments(edgeidx).time = time(edges(edgeidx)+1 : edges(edgeidx+1)-1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%filtering%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f = ltiFilter.PT1(); % another class which has filters
f.Ts = mean(diff(time));
f.fc = fc; % i want to set this value from the slider%%%%%
f.zeroPhaseShift = 1;
for i = 1:length(newsegments)
newsegments(i).ref = f.eval(newsegments(i).signal,newsegments(i).signal(1)); % application of the filter.
newsegments(i).ref = newsegments(i).ref';
end
this.segments = [this.segments; newsegments];
end
end
end
I created a GUI which has a plot and a slider(for cut off frequcy) which is shown in code as f.fc
when i created the GUI, Matlab automatically created a Code for me(i must say, I din't understand that much)
GUI code:
function varargout = GUI(varargin)
% GUI MATLAB code for GUI.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before GUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help GUI
% Last Modified by GUIDE v2.5 15-Jul-2016 09:37:09
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #GUI_OpeningFcn, ...
'gui_OutputFcn', #GUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before GUI is made visible.
function GUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to GUI (see VARARGIN)
% Choose default command line output for GUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes GUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = GUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- 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)
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
What i want to do is, i want to connect the GUI to my m script, when user sildes the slider . it should show the change in graph automatically and when he clicks on apply. the value of slider should be taken and should be available in my m file.
Any leads will be helpful.
From code sample pasted, I'm assuming you are using MATLAB GUIDE. Let's assume name of slider control is "slider1".
Add a callback function for "slider" using GUIDE.
It will create a function "function slider1_Callback(hObject, eventdata, handles)" in your code.
Now, to get value selected from slider movement use "get" function with "hObject".
E.g. SliderVal=get(hObject,'Value');
Now if you want to know value of slider selection from other callbacks (such as Apply button)
use handles structure.
E.g.: SliderVal=get(handles.slider1,'Value');
Based on slider value, received you need to re-draw plot area.
I hope this helps as clue you are expecting.
Edit1:
For followup comment, how to get data from other M-file:
This will be very tricky. Because, you need to know handle of slider control in other M-file.
One of the ways would be to get handle of figure first.
Set "HandleVisibility" property of GUI figure (via GUIDE) to "ON".
Call "figures = get(0,'Children');" from M-script to get list of all open figures. This will give vector of figure handles.
Scan through list of children and get handle of your application. (This can be done via using property get(figures(1),'Name')).
Let's assume you found that handle, repeat same process again to get children from it. get(figHandle,'Children').
Scan through children and find slider control handle similar to approach as in step 3.
Now you have access to control and it's data.
I hope you understood it.

Create a gui in matlab

I want to create a gui in matlab with a push button and a panel.
Requirements: Upon clicking the button the dialogue must open to choose a file and after selecting image from this dialogue the image must be shown to that panel of gui.
How do I do this?
How to show the image on the gui panel?
My current status so far:
function pushbutton1_Callback(hObject, eventdata, handles)
[filename, pathname] = ...
uigetfile({'*.jpg';'*.png';'*.jpeg';'*.bmp';'*.*'},'File Selector');
set(handles.axes2, 'Visible','on');
imshow(IMG,'Parent',TheAxisHandleToDrawOn)
if isequal(filename,0)
disp('Image upload Canceled')
end
I tried this but it's not working, how to do this?
With respect to your callback you have first to read the selected image by using imread; you can use fullfile to build the complete filename.
Then you use the matrix returned by imread as input for the imshow function.
Edit following the comments
In order to show the image within a uipanel you have to add an axes in the panel and use it as parent in the call to imshow.
If the image you want to display is not in the current folder or in a folder on the MATLAB path, you have to specify the full path name (ref. imread).
In the following you can find the .m file of the GUI I've build for test.
The GUI contains:
an axes (tag: axes2)
a uipanel (tag: uipanel1)
an axes (tag: axes_up) embedded in the uipanel
two radiobuttons (tag: radiobutton1 and radiobutton2) to select the axes on which to show the image
two statictext fields (tag: text2 and text3) to show the filename of the selected images
a pushbutton (tag: pushbutton1) to select the image to be displayed
a pushbutton (tag: pushbutton3) to run the imcontrast tool in case of selection of a .dcm image
The code has been tested on R2012b and 2015b.
function varargout = disp_fig(varargin)
% DISP_FIG MATLAB code for disp_fig.fig
% DISP_FIG, by itself, creates a new DISP_FIG or raises the existing
% singleton*.
%
% H = DISP_FIG returns the handle to a new DISP_FIG or the handle to
% the existing singleton*.
%
% DISP_FIG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DISP_FIG.M with the given input arguments.
%
% DISP_FIG('Property','Value',...) creates a new DISP_FIG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before disp_fig_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to disp_fig_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help disp_fig
% Last Modified by GUIDE v2.5 25-Apr-2016 14:18:18
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #disp_fig_OpeningFcn, ...
'gui_OutputFcn', #disp_fig_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before disp_fig is made visible.
function disp_fig_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to disp_fig (see VARARGIN)
% Choose default command line output for disp_fig
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes disp_fig wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = disp_fig_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- 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)
% Select the image to be displayed
[filename, pathname] = ...
uigetfile({'*.jpg';'*.png';'*.jpeg';'*.bmp';'*.*'},'File Selector');
% Build the full filename
img_file=fullfile(pathname,filename)
% Split the filename to get its extension
[the_path,the_name,the_ext]=fileparts(img_file);
% Set the current StaticText uicontrol based on the selected RadioButton
curr_txt=handles.text2;
if(get(handles.radiobutton2,'value'))
curr_txt=handles.text3;
end
% Check for image valid selection
if isequal(filename,0)
disp('Image upload Canceled')
set(curr_txt,'string','Image upload Canceled')
else
% If an image has been selected
set(curr_txt,'string',img_file)
% If the image is a ".dcm"
if(strcmp(the_ext,'.dcm'))
% Read it with dicomread and enable the pushbutton to run the
% IMCONTRAST tool
IMG=dicomread(img_file);
set(handles.pushbutton3,'visible','on')
else
% If the image is a ".jpg", ".bmp", ...
% Read it with imread and disable the pushbutton to run the
% IMCONTRAST tool
IMG=imread(img_file);
set(handles.pushbutton3,'visible','off')
end
% Identify the axes on which to display the image according to the
% selected radiobutton
if(get(handles.radiobutton1,'value'))
the_parent=handles.axes2;
set(handles.axes2, 'Visible','on');
else
the_parent=handles.axes_up;
end
% Showthe image
imshow(IMG,'Parent',the_parent)
end
% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
% If the first radiobutton has been selected, disable the second onre
r1=get(handles.radiobutton1,'value');
if(r1)
set(handles.radiobutton2,'value',0);
end
% --- Executes on button press in radiobutton2.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton2
% If the second radiobutton has been selected, disable the first one
r2=get(handles.radiobutton2,'value');
if(r2)
set(handles.radiobutton1,'value',0);
end
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Run the IMCONTRAST tool to the proper axes according to the selected
% radiobutton
r1=get(handles.radiobutton1,'value');
if(r1)
imcontrast(handles.axes2)
else
imcontrast(handles.axes_up)
end
Structure of the GUI
The GUI ... working
To test the .dcm image display I've used, as examples, the images from DICOM sample image sets.
Hope this helps.
Qapla'
this is the final solution for the problem
function browse_Callback(hObject, eventdata, handles)
% hObject handle to browse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname]=uigetfile( {'.jpg';'.gif';'.png';'.bmp'},'Select file');
MyImage = strcat(pathname, filename);
%This code checks if the user pressed cancel on the dialog.
if isequal(filename,0) || isequal(pathname,0)
uiwait(msgbox ('User pressed cancel','failed','modal') )
hold on;
else
uiwait(msgbox('User selected image sucessfully','sucess','modal'));
hold off;
imshow(MyImage,'Parent',handles.axes1);
end
global Imagevariable;
Imagevariable=MyImage;
handles.output = hObject;
guidata(hObject, handles);

Supply inputs to a GUI and catch the output in order to use it in another function

I have created a GUI function as follows. what I am trying to do is to put this GUI in a loop so that I can use it for different elements. for the output I have two vectors that are 6 by 1. What I am trying to do is, when I choose different radio buttons and put different values in the edit text of the GUI, to have the results saved in different positions of the output vector depending on the radio buttons. I am trying to give the GUI a title as the input.
Thanks in advance.
function varargout = distributedloads(varargin)
% DISTRIBUTEDLOADS MATLAB code for distributedloads.fig
% DISTRIBUTEDLOADS, by itself, creates a new DISTRIBUTEDLOADS or raises the existing
% singleton*.
%
% H = DISTRIBUTEDLOADS returns the handle to a new DISTRIBUTEDLOADS or the handle to
% the existing singleton*.
%
% DISTRIBUTEDLOADS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DISTRIBUTEDLOADS.M with the given input arguments.
%
% DISTRIBUTEDLOADS('Property','Value',...) creates a new DISTRIBUTEDLOADS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before distributedloads_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to distributedloads_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help distributedloads
% Last Modified by GUIDE v2.5 28-Feb-2016 14:52:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #distributedloads_OpeningFcn, ...
'gui_OutputFcn', #distributedloads_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before distributedloads is made visible.
function distributedloads_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to distributedloads (see VARARGIN)
imshow('disloads.png')
% Choose default command line output for distributedloads
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes distributedloads wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = distributedloads_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
varargout = str2double(handles.DATA.EL);
function ELNUM_Callback(hObject, eventdata, handles)
% hObject handle to ELNUM (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ELNUM as text
% str2double(get(hObject,'String')) returns contents of ELNUM as a double
EL = get(hObject , 'String');
handles.DATA.EL = EL;
guidata(hObject,handles)
% --- Executes during object creation, after setting all properties.
function ELNUM_CreateFcn(hObject, eventdata, handles)
% hObject handle to ELNUM (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function LOADVAL_Callback(hObject, eventdata, handles)
% hObject handle to LOADVAL (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of LOADVAL as text
% str2double(get(hObject,'String')) returns contents of LOADVAL as a double
Load = get(hObject , 'String');
handles.DATA.Load = Load;
guidata(hObject , handles)
% --- Executes during object creation, after setting all properties.
function LOADVAL_CreateFcn(hObject, eventdata, handles)
% hObject handle to LOADVAL (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in CONFIRM.
function CONFIRM_Callback(hObject, eventdata, handles)
% hObject handle to CONFIRM (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete(handles.figure1)
% --------------------------------------------------------------------
function buttongroup_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to buttongroup (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Type = get(hObject , 'selectedObject');
handles.DATA.Type = Type;
guidata(hObject , handles)
I wrote an example script that creates GUI and a one callback function.
In the GUI there is vector of handles to Radio Buttons, Push Button and axes with line to visualize the results.
The script code:
close all % close all figures
figure % open a figure for GUI
Values=zeros(3,1); % Variable of the interest
UIGroup=uibuttongroup('parent',gcf,'position',[0 0 1 1]); % Group for Radio Buttons
for ii=1:3 % create 3 Radio buttons, for example
RB(ii)=uicontrol('style','radiobutton',...
'units','normalized','position',[.05, ii/10 0.15 0.1],...
'parent',UIGroup,'string',['Button ' num2str(ii)]);
end
% Push Button that runs DoIt function
uicontrol('style','pushbutton','string','DO',...
'units','normalized','position',[0.45 0.05 0.1 0.1],...
'callback','Values=DoIt(RB,L,Values);')
% Axes and Line just for example
ax=axes('units','normalized','position',[0.25 0.2 0.6 0.7],...
'xlim',[-0.1 3.1],'ylim',[-0.1 1.1]);
L=line('xdata',1:3,'ydata',Values,'marker','.','linestyle','none')
This script defines Values variable and content of the GUI.
Push Button runs the DoIt function which assigns new content to Values according to RB handle. Values are needed only to keep other values in Values, L is used only to visualize the changes.
DoIt code:
function[OutValues]=DoIt(RadioHandle,LineHandle,InValues)
OutValues=InValues; % Copy Values from input to output variable
%% Find which radio button is active
M=max(size(RadioHandle));
for ii=1:M
Radios(ii)=get(RadioHandle(ii),'value');
end
RadioChecked=find(Radios==1); % This RadioButton is active
OutValues(RadioChecked)=ProcessIt; % Process the chosen position.
set(LineHandle,'ydata',OutValues);% Visualize the change
function[OUT]=ProcessIt()
OUT=rand; % this function will just return random value, for example.
The DoIt function reads handle to radio buttons RB and determines which button is active. Then it change the appropriate value in Value variable and return it and changes y-values in line with handle L.
In this example it will assign random value to the defined point but You can pass any variable from workspace / parent function and call any function.

matlab eventdata of uitable returned empty

I'm trying to run a GUIDE app in Matlab, but I encounter a problem: when I try to access the location of the selected cell in a ui table, the variable holding it (eventdata.Indices) quickly changes back to an empty vector.
Here's my CellSelectionCallback function:
function varargout = ChannelMatrix(varargin)
% CHANNELMATRIX MATLAB code for ChannelMatrix.fig
% CHANNELMATRIX, by itself, creates a new CHANNELMATRIX or raises the existing
% singleton*.
%
% H = CHANNELMATRIX returns the handle to a new CHANNELMATRIX or the handle to
% the existing singleton*.
%
% CHANNELMATRIX('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CHANNELMATRIX.M with the given input arguments.
%
% CHANNELMATRIX('Property','Value',...) creates a new CHANNELMATRIX or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ChannelMatrix_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ChannelMatrix_OpeningFcn via varargin.
%
% *See GUI Options on GUIDEs Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help ChannelMatrix
% Last Modified by GUIDE v2.5 14-Oct-2015 17:06:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #ChannelMatrix_OpeningFcn, ...
'gui_OutputFcn', #ChannelMatrix_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before ChannelMatrix is made visible.
function ChannelMatrix_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to ChannelMatrix (see VARARGIN)
clc
% Choose default command line output for ChannelMatrix
handles.output = hObject;
%CONNECT TO SWITCHER
matrixes=cell(12,6,26);
setappdata(0,'matrixes',matrixes);
set(handles.listbox1,'Value',1);
setappdata(0,'index_selected',1); %force Alpha for deafult selection
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes ChannelMatrix wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = ChannelMatrix_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes when selected cell(s) is changed in uitable1.
function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject handle to uitable1 (see GCBO)
% eventdata structure with the following fields (see UITABLE)
% Indices: row and column indices of the cell(s) currently selecteds
% handles structure with handles and user data (see GUIDATA)
% --- Executes when selected cell(s) is changed in uitable1.
try
currow = eventdata.Indices(1);
curcol = eventdata.Indices(2);
adata=get(handles.uitable1,'Data');
if adata{currow,curcol} == 'V'
adata{currow,curcol} = '';
else
adata{currow,curcol} = 'V';
end
set(hObject,'Data',adata);
end
% --- Executes on button press in cls_ch.
function cls_ch_Callback(hObject, eventdata, handles)
% hObject handle to cls_ch (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
index_selected = getappdata(0,'index_selected'); %get the number of selected item in listbox
matrixes = getappdata(0,'matrixes'); %get current selection of measurments
table = get(handles.uitable1,'data'); %get the selected channels for this measure
for i=3:14
for j=1:6
if table{i-2,j}=='V'
matrixes{i-2,j,index_selected}='V'; %preform scan and check - add to matrixes selcted values
end
end
end
%save changes
set(handles.uitable3,'Data',matrixes(:,:,index_selected));
setappdata(0,'matrixes',matrixes);
guidata(hObject, handles);
% --- Executes on button press in opn_ch.
function opn_ch_Callback(hObject, eventdata, handles)
% hObject handle to opn_ch (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
index_selected = getappdata(0,'index_selected'); %get the number of selected item in listbox
matrixes = getappdata(0,'matrixes'); %get current selection of measurments
table = get(handles.uitable1,'data'); %get the selected channels for this measure
for i=3:14
for j=1:6
if table{i-2,j}=='V'
matrixes{i-2,j,index_selected}=''; %preform scan and check - add to matrixes selcted values
end
end
end
%save changes
set(handles.uitable3,'Data',matrixes(:,:,index_selected));
setappdata(0,'matrixes',matrixes);
guidata(hObject, handles);
% --- Executes on button press in opn_all.
function opn_all_Callback(hObject, eventdata, handles)
% hObject handle to opn_all (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
matrixes=cell(12,6,26);
setappdata(0,'matrixes',matrixes); %sets up a new matrix
set(handles.uitable1,'Data',cell(12,6));
set(handles.uitable3,'Data',cell(12,6));
set(handles.listbox1,'Value',1);
guidata(hObject, handles);
% --- Executes on button press in clr_selection_btn.
function clr_selection_btn_Callback(hObject, eventdata, handles)
% hObject handle to clr_selection_btn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.uitable1,'Data',cell(12,6));
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
matrixes=getappdata(0,'matrixes');
index_selected=get(hObject,'Value');
setappdata(0,'index_selected',index_selected);
set(handles.uitable3,'Data',matrixes(:,:,index_selected));
set(handles.uitable1,'Data',cell(12,6));
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
What's wrong here?
Thanks!
I think there is nothing anything wrong in the definition of your uitable1_CellSelectionCallback function.
I've built a simple GUI consisting of just a uitable and executing step by step the callback in debug mode this is what actually happens:
when you left-click on a cell's table, the uitable1_CellSelectionCallback is correctly called
everything goes right up to the set(hObject,'Data',adata); instruction and eventdata.Indices array contains the row and column index of the selected cell (ref. to the Function Call Stack in the following picture)
as the set(hObject,'Data',adata); function is executed, automatically a new call to uitable1_CellSelectionCallback is made by MatLab (probably somehow triggered by set. In the next picture, you can see the second (recursive) call to uitable1_CellSelectionCallback in the Function Call Stack and the white and green pair of arrows in the edit window the debug mode
since the second call is not generated by an actual user selection of a cell, the eventdata.Indices is empty therefore an error is generated when the currow = eventdata.Indices(1); is executed
So, this is why when you click on a cell, its content is correctly set to "V" or to an empty string as you expeced but, at the same time (actually, after the time MatLab needs to make second call to uitable1_CellSelectionCallback) the GUI crashes.
I do not know if this might be considered a MatLab's bug, nevertheless I did not find any way to prevent the second call to uitable1_CellSelectionCallback.
A possible solution, not so far from yours (using try-catch) could be insert the present callback code in a if block checking if isempty(eventdata.Indices) (that is to replace try with if).
This will prevent the second call be "effective" and the generation of the error, which is not avoided by using try-catch (even if does not prevent the second call to happen).
Hope this helps.

How do I show different images with radio buttons in matlab GUIDE?

This is all of the code as of right now. The correct image is displayed when you change the selected button in the button group but no image is displayed until you change the selected button. I want the first image to be FloorPlan{1} as it says in axes1_CreateFcn but it is not working. The axes are simply not there until you change the button.
function varargout = selectfloorplan(varargin)
% SELECTFLOORPLAN MATLAB code for selectfloorplan.fig
% SELECTFLOORPLAN, by itself, creates a new SELECTFLOORPLAN or raises the existing
% singleton*.
%
% H = SELECTFLOORPLAN returns the handle to a new SELECTFLOORPLAN or the handle to
% the existing singleton*.
%
% SELECTFLOORPLAN('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SELECTFLOORPLAN.M with the given input arguments.
%
% SELECTFLOORPLAN('Property','Value',...) creates a new SELECTFLOORPLAN or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before selectfloorplan_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to selectfloorplan_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help selectfloorplan
% Last Modified by GUIDE v2.5 18-Apr-2014 11:16:48
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #selectfloorplan_OpeningFcn, ...
'gui_OutputFcn', #selectfloorplan_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before selectfloorplan is made visible.
function selectfloorplan_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to selectfloorplan (see VARARGIN)
% Choose default command line output for selectfloorplan
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes selectfloorplan wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = selectfloorplan_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
global FloorPlans floorplanselection
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
%Hint: place code in OpeningFcn to populate axes1
imagesc(FloorPlans{1})
floorplanselection=FloorPlans{1};
axis off
axis('image')
colormap(gray)
% --- Executes when selected object is changed in uipanel1.
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
global FloorPlans floorplanselection
% hObject handle to the selected object in uipanel1
% eventdata structure with the following fields (see UIBUTTONGROUP)
% EventName: string 'SelectionChanged' (read only)
% OldValue: handle of the previously selected object or empty if none was selected
% NewValue: handle of the currently selected object
% handles structure with handles and user data (see GUIDATA)
switch get(eventdata.NewValue,'Tag')
case 'rad1'
axes(handles.axes1)
imagesc(FloorPlans{1})
floorplanselection=FloorPlans{1};
axis off
axis('image')
colormap(gray)
case 'rad2'
axes(handles.axes1)
imagesc(FloorPlans{2})
floorplanselection=FloorPlans{2};
axis off
axis('image')
colormap(gray)
case 'rad3'
axes(handles.axes1)
imagesc(FloorPlans{3})
floorplanselection=FloorPlans{3};
axis off
axis('image')
colormap(gray)
case 'rad4'
axes(handles.axes1)
imagesc(FloorPlans{4})
floorplanselection=FloorPlans{4};
axis off
axis('image')
colormap(gray)
case 'rad5'
axes(handles.axes1)
imagesc(FloorPlans{5})
floorplanselection=FloorPlans{5};
axis off
axis('image')
colormap(gray)
case 'rad6'
axes(handles.axes1)
imagesc(FloorPlans{6})
floorplanselection=FloorPlans{6};
axis off
axis('image')
colormap(gray)
end
% --- Executes on button press in nectbtn.
function nectbtn_Callback(hObject, eventdata, handles)
% hObject handle to nectbtn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
selectrobot
delete(get(hObject, 'parent'));
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mainmenu
delete(get(hObject, 'parent'));
% --- Executes during object creation, after setting all properties.
function uipanel1_CreateFcn(hObject, eventdata, handles)
% hObject handle to uipanel1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
The ID for your graphics objects are stored in the handles structure that GUIDE stores and passes between callbacks. The reason axis1 doesn't work as an input is because it's not defined in the scope of your callback function so the function has no way to address it. This is why your global workaround 'fixes' the problem.
If you substitute handles.axes1 (or whatever your axes object tag is) for axis1 in your axes() calls, it should perform as you're expecting.