Matlab GUI not showing line plot graph data - matlab

I'm working with my Matlab GUI file to play video and plot the mean value from the color channel (RGB). It has 2 axes, the first one for the video player and second axis for the mean graph, but the second axis is not showing any data, it just updates the x and y coordinate but not showing anything.
I've tried to change the handles, changes the next plot setting in the property inspector but it doesn't work
function main_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
video = vision.VideoFileReader();
handles.video = video;
frameCount = 0;
handles.frameCount = frameCount;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes main wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = main_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
handles.output = hObject;
varargout{1} = handles.output;
% --- Executes on button press in Browse.
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)
[ video_file_name,video_file_path ] = uigetfile({'*.avi'},'Pick a video file'); %;*.png;*.yuv;*.bmp;*.tif'},'Pick a file');
if(video_file_path == 0)
return;
end
input_video_file = [video_file_path,video_file_name];
fullpath = strcat(video_file_path,video_file_name);
set(handles.edit1,'String',fullpath);
video = vision.VideoFileReader(input_video_file);
vidFrame = step(video);
axes(handles.axes1);set(handles.StartButton,'String','Start');
frameCount = 1;
imshow(vidFrame);
drawnow;
axis(handles.axes1,'off');
for nChannel = 1:3
colorChannel = vidFrame(:,:,nChannel);
rawColorSignal(nChannel,frameCount) = mean(mean(colorChannel));
end
%plot(frameCount,rawColorSignal(1, :),frameCount,rawColorSignal(2, :),frameCount,rawColorSignal(3, :), handles.axes2);
axes(handles.axes2)
plot(frameCount,rawColorSignal(1, :));
grid on
drawnow;
axes(handles.axes1)
% Display Frame Number
%Update handles
handles.video = video;
guidata(hObject,handles);
% --- Executes on button press in StartButton.
function StartButton_Callback(hObject, eventdata, handles)
% hObject handle to StartButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if strcmp(get(handles.StartButton,'String'),'Pause')
set(handles.StartButton,'String','Start');
else
set(handles.StartButton,'String','Pause');
end
video = handles.video;
if isDone(video)
reset(video)
frameCount = 0;
handles.frameCount = frameCount;
end
frameCount = handles.frameCount;
while ~isDone(video) && strcmp(get(handles.StartButton,'String'),'Pause')
vidFrame = step(video);
imshow(vidFrame,'Parent',handles.axes1); %plot frame is specific axis
drawnow;
frameCount = frameCount + 1;
for nChannel = 1:3
colorChannel = vidFrame(:,:,nChannel);
rawColorSignal(nChannel,frameCount) = mean(mean(colorChannel));
end
plot(frameCount,rawColorSignal(1, :),'Parent',handles.axes2);
grid on
drawnow;
end
%plot(frameCount,rawColorSignal(1, :),'r',frameCount,rawColorSignal(2, :),'g',frameCount,rawColorSignal(3, :),'b','Parent', handles.axes2);
%drawnow;
set(handles.StartButton,'String','Start');
% --- Executes on button press in PauseButton.
function PauseButton_Callback(hObject, eventdata, handles)
% hObject handle to PauseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%axes(handles.axes2)
%surf(membrane(3))
What I expected is the line plot is visible and updating alongside the axes.

I think I found the problem:
Replace: plot(frameCount,rawColorSignal(1, :));
With: plot(1:frameCount,rawColorSignal(1, :));
Replace: plot(frameCount,rawColorSignal(1, :),'Parent',handles.axes2);
With: plot(1:frameCount,rawColorSignal(1, :),'Parent',handles.axes2);
plot(frameCount,... uses the scalar frameCount as X coordinates.
You want the X coordinates in your plot to be a vector that goes from 1 to frameCount.
In case you are getting an error, try:
plot(1:length(rawColorSignal(1, :)), rawColorSignal(1, :), 'Parent', handles.axes2);
I created the following sample code for demonstrating the problem:
Following sample is not plotting:
frameCount = 0;
rawColorSignal = [];
for i = 1:10
frameCount = frameCount + 1;
rawColorSignal(frameCount) = i;
end
plot(frameCount, rawColorSignal);
grid on
drawnow;
When replacing plot(frameCount, rawColorSignal); with plot(1:frameCount, rawColorSignal); it does:
frameCount = 0;
rawColorSignal = [];
for i = 1:10
frameCount = frameCount + 1;
rawColorSignal(frameCount) = i;
end
plot(1:frameCount, rawColorSignal);
grid on
drawnow;

Related

My matlab while loop isn't recognising my function button press

I have a script that runs when a button is pressed causing a while loop to initiate. When my stop button is pressed it is supposed to cause the loop condition to be untrue thus stopping the loop. My stop button doesn't seem to stop the loop during testing. it would seem the value I assigned in the pushDisconnect button isn't updating to the while loop and i'm not sure why this is occurring.
% --- Executes on button press in pushConnect.
function pushConnect_Callback(hObject, eventdata, handles)
% hObject handle to pushConnect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.pushDisconnect,'Enable','on')
set(handles.pushConnect,'Enable','off')
handles.myDevice.StartAcquisition;
sampleRate_BP = double(handles.myDevice.BioPotentialSignals.SamplesPerSecond);
axis_handles = zeros(1,handles.numEnabledBPChannels);
BioPotentialSignals = cell(1,handles.numEnabledBPChannels);
handles.CheckFinger = cell(1,5);
handles.stopNow = 0;
for ch = 1:handles.numEnabledBPChannels
axis_handles(ch) = subplot(length(axis_handles),1,ch,'Parent',handles.uipanelGraph);
if ch==1
title(char(handles.deviceName))
end
ylabel([char(handles.myDevice.BioPotentialSignals.Item(ch-1).Name) ' (V)']);
hold on
end
xlabel('Time (s)')
linkaxes(axis_handles,'x')
plotWindow = 5;
plotGain_BP = 1;
while handles.stopNow == 0
for ch = 1:handles.numEnabledBPChannels
BioPotentialSignals{ch} = [BioPotentialSignals{ch};handles.myDevice.BioPotentialSignals.Item(ch-1).GetScaledValueArray.double'];
if length(BioPotentialSignals{ch}) <= plotWindow*sampleRate_BP
cla(axis_handles(ch))
t = (0:(length(BioPotentialSignals{ch})-1))*(1/sampleRate_BP);
plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch});
xlim([0 plotWindow])
else
if ch==1
t = ((length(BioPotentialSignals{ch})-(plotWindow*sampleRate_BP-1)):length(BioPotentialSignals{ch}))*(1/sampleRate_BP);
end
cla(axis_handles(ch))
plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch}(end-plotWindow*sampleRate_BP+1:end));
xlim([t(end)-plotWindow t(end)])
end
end
% Update handles structure
guidata(hObject, handles);
pause(0.1)
disp(handles.stopNow)
end
% Stop signal
handles.myDevice.StopAcquisition;
% Disconnect from all sensors
handles.myDevice.Disconnect;
msgbox('Device requires cycling, in order to restablish connection. Closing program.')
% Close window
close all;
% --- Executes on button press in pushDisconnect.
function pushDisconnect_Callback(hObject, eventdata, handles)
% hObject handle to pushDisconnect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.pushDisconnect,'Enable','off')
handles.stopNow = 1;
% Update handles structure
guidata(hObject, handles);
Final Working Code, if anyone is interested:
% --- Executes on button press in pushConnect.
function pushConnect_Callback(hObject, eventdata, handles)
% hObject handle to pushConnect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.pushDisconnect,'Enable','on')
set(handles.pushConnect,'Enable','off')
handles.myDevice.StartAcquisition;
sampleRate_BP = double(handles.myDevice.BioPotentialSignals.SamplesPerSecond);
axis_handles = zeros(1,handles.numEnabledBPChannels);
BioPotentialSignals = cell(1,handles.numEnabledBPChannels);
handles.CheckFinger = cell(1,5);
handles.stopNow = 0;
for ch = 1:handles.numEnabledBPChannels
axis_handles(ch) = subplot(length(axis_handles),1,ch,'Parent',handles.uipanelGraph);
if ch==1
title(char(handles.deviceName))
end
ylabel([char(handles.myDevice.BioPotentialSignals.Item(ch-1).Name) ' (V)']);
hold on
end
xlabel('Time (s)')
linkaxes(axis_handles,'x')
plotWindow = 5;
plotGain_BP = 1;
% Update handles structure
guidata(hObject, handles);
while handles.stopNow == 0
for ch = 1:handles.numEnabledBPChannels
BioPotentialSignals{ch} = [BioPotentialSignals{ch};handles.myDevice.BioPotentialSignals.Item(ch-1).GetScaledValueArray.double'];
if length(BioPotentialSignals{ch}) <= plotWindow*sampleRate_BP
cla(axis_handles(ch))
t = (0:(length(BioPotentialSignals{ch})-1))*(1/sampleRate_BP);
plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch});
xlim([0 plotWindow])
else
if ch==1
t = ((length(BioPotentialSignals{ch})-(plotWindow*sampleRate_BP-1)):length(BioPotentialSignals{ch}))*(1/sampleRate_BP);
end
cla(axis_handles(ch))
plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch}(end-plotWindow*sampleRate_BP+1:end));
xlim([t(end)-plotWindow t(end)])
end
end
handles = guidata(hObject);
drawnow
pause(0.1)
end
% Stop signal
handles.myDevice.StopAcquisition;
% Disconnect from all sensors
handles.myDevice.Disconnect;
msgbox('Device requires cycling, in order to restablish connection. Closing program.')
% Close window
close all;
% --- Executes on button press in pushDisconnect.
function pushDisconnect_Callback(hObject, eventdata, handles)
% hObject handle to pushDisconnect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.pushDisconnect,'Enable','off')
handles.stopNow = 1;
% Update handles structure
guidata(hObject, handles);
Kill the guidata(hObject, handles) line, and replace it by handles=guidata(hObject) since you're overwriting the GUI state with whatever was current at the time the loop started, and you want to be polling the GUI state instead. Put the guidata(hObject, handles)-line before the loop, to ensure that handles.stopNow is indeed reset to 0.
If that doesn't help, an additional problem may be that Matlab waits with processing commands from one button callback until the other callback is done running.
Two things you can try: Add a drawnow command before the pause. This will force the GUI to update, and processes all the interactions. Also, make sure that the pushbutton callback for pushConnect is interruptible.

display a screen/frame to display dicom image in matlab

I have a matlab program to upload a folder of dicom images. I want to display a black screen/frame where in the image would be loaded. Now, the image is displayed over the browse button.
Is there a way to do it ?
Here's my code:
function varargout = ui(varargin)
% UI MATLAB code for ui.fig
% UI, by itself, creates a new UI or raises the existing
% singleton*.
%
% H = UI returns the handle to a new UI or the handle to
% the existing singleton*.
%
% UI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in UI.M with the given input arguments.
%
% UI('Property','Value',...) creates a new UI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ui_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 ui
% Last Modified by GUIDE v2.5 17-Nov-2015 13:11:51
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #ui_OpeningFcn, ...
'gui_OutputFcn', #ui_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
end
% --- Executes just before ui is made visible.
function ui_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 ui (see VARARGIN)
% Choose default command line output for ui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes ui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
end
% --- Outputs from this function are returned to the command line.
function varargout = ui_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;
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)
global files;
global dname;
dname = uigetdir('Select the dicom image folder');
set(handles.text2, 'String', dname);
files = dir(fullfile(dname, '*.dcm'));
dname = [dname '\'];
global indexSelected;
indexSelected = 1;
filePath = [dname files(1).name];
fileRead = dicomread(filePath);
imshow(fileRead, []);
end
function text2_Callback(hObject, eventdata, handles)
% hObject handle to text2 (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 text2 as text
% str2double(get(hObject,'String')) returns contents of text2 as a double
% --- Executes during object creation, after setting all properties.
end
function text2_CreateFcn(hObject, eventdata, handles)
% hObject handle to text2 (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
end
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global indexSelected;
global files;
global dname;
if(indexSelected == 1)
indexSelected = length(files);
filePath = [dname files(indexSelected).name];
fileRead = dicomread(filePath);
imshow(fileRead, []);
else
indexSelected = indexSelected - 1;
filePath = [dname files(indexSelected).name];
fileRead = dicomread(filePath);
imshow(fileRead, []);
end
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)
global indexSelected;
global files;
global dname;
if(indexSelected == length(files))
indexSelected = 1 ;
filePath = [dname files(1).name];
fileRead = dicomread(filePath);
imshow(fileRead,[]);
else
indexSelected = indexSelected + 1;
filePath = [dname files(indexSelected).name];
fileRead = dicomread(filePath);
imshow(fileRead,[]);
end
end
In short:
You can fix your problem by adding an axes in your GUI in the position (and with the size) in which you want to display the image
You should add in your callback some checks in order to catch the following situations:
the users selects Cancel when selecting the folder
the selected folder does not contains any .dcm files
pushbutton2 and pushbutton3 should be disabled when the GUI is opened and then enabled in the pushbutton1 callback if the users selected a right folder. You can disable them either using GUIDE or setting their enable property off in the GUI CreateFcn
Also you can avoid using global varaibles; you can actually store and share variables among the callback by using the guidata built-in function.
Adding the axes
After having added the axes (with, for example, tag axes1) you can set its appearence in the CreateFcn:
you can set a black background color using set function
you can remove X-axis and Y-axis ticks using set function as well
You can insert this callback in your code
% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% 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
% Set axes background color to black
set(hObject,'color','k')
% Remove X-axis and Y-axis ticks
set(gca,'xtick',[],'ytick',[])
% Disable pushbutton2 and pusbutton 3 (they will be enabled in pushbutton1
% callback)
set(handles.pushbutton2,'enable','off')
set(handles.pushbutton3,'enable','off')
When the imshow function is called in your pushbutto callback the DICOM image will be displayed in the right position.
Adding checks on folder selection
You can simply test the value returned by uigetdir: it is set to 0 when the user pushes Cancel or
Using GUI data instead of flobal variables
You can store the varaibles you want to share among the callback adding them to the GUI data struct.
In the GUI OpeningFcn you can initialize (if needed) the varaibles you want to share by adding the following code:
% Add "indexSelected" to handles struct and initialize it
my_gui_data=guidata(gcf)
my_gui_data.indexSelected=0;
guidata(gcf,my_gui_data);
The function guidata is used at the beginning to get the GUI data from the GUI (at the beginning it only contains the GUI handles).
Then you can add the indexSelected to the GUI data struct and set the updated GUI data struct by calling again guidata.
When you need to retrieve and / or update the variables in the callback you just have to use the same approach. For example, to store the dname varaible in the pushbutton1_Callback
my_gui_data=guidata(gcf)
my_gui_data.dname=dname;
guidata(gcf,my_gui_data);
I've created a GUI (dcom_gui) to test the above suggestions:
function varargout = ui(varargin)
% UI MATLAB code for ui.fig
% UI, by itself, creates a new UI or raises the existing
% singleton*.
%
% H = UI returns the handle to a new UI or the handle to
% the existing singleton*.
%
% UI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in UI.M with the given input arguments.
%
% UI('Property','Value',...) creates a new UI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ui_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 ui
% Last Modified by GUIDE v2.5 21-Nov-2015 17:35:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #ui_OpeningFcn, ...
'gui_OutputFcn', #ui_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 ui is made visible.
function ui_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 ui (see VARARGIN)
% Choose default command line output for ui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% Add "indexSelected" to handles struct and initialize it
my_gui_data=guidata(gcf)
my_gui_data.indexSelected=0;
guidata(gcf,my_gui_data);
% Disable pushbutton2 and pusbutton 3 (they will be enabled in pushbutton1
% callback)
set(handles.pushbutton2,'enable','off')
set(handles.pushbutton3,'enable','off')
% UIWAIT makes ui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = ui_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)
% Get GUI data
my_gui_data=guidata(gcf)
% Use guidata data struct instead of "global" variables
% global files;
% global dname;
dname = uigetdir('Select the dicom image folder');
% Check for directory selection validity
if(dname == 0)
set(handles.text2,'string','Dir selection aborted')
else
set(handles.text2, 'String', dname);
files = dir(fullfile(dname, '*.dcm'));
% Check for files presence
if(length(files) == 0)
set(handles.text2,'string',['No ".dcm" file in ' dname ' folder'])
else
% Enable pushbutton2 and pusbutton 3
set(handles.pushbutton2,'enable','on')
set(handles.pushbutton3,'enable','on')
% Use guidata data struct instead of "global" variables
% global indexSelected;
% Not needed, use fullfile to build the full file name
% dname = [dname '\'];
indexSelected = 1;
% filePath = [dname files(1).name];
filePath = fullfile(dname,files(1).name);
fileRead = dicomread(filePath);
imshow(fileRead, []);
% Store GUI data
my_gui_data.dname=dname;
my_gui_data.files=files;
my_gui_data.indexSelected=indexSelected;
my_gui_data.filePath=filePath;
guidata(gcf,my_gui_data);
end
end
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Use guidata data struct instead of "global" variables
% global indexSelected;
%
% global files;
% global dname;
my_gui_data=guidata(gcf);
indexSelected=my_gui_data.indexSelected;
files=my_gui_data.files;
dname=my_gui_data.dname;
if(indexSelected == 1)
indexSelected = length(files);
% Use "fullfile" to build the file name
% filePath = [dname files(indexSelected).name];
filePath = fullfile(dname,files(indexSelected).name);
fileRead = dicomread(filePath);
imshow(fileRead, []);
else
indexSelected = indexSelected - 1;
% Use "fullfile" to build the file name
% filePath = [dname files(indexSelected).name];
filePath = fullfile(dname,files(indexSelected).name);
fileRead = dicomread(filePath);
imshow(fileRead, []);
end
% Store GUI data
my_gui_data.filePath=filePath;
my_gui_data.indexSelected=indexSelected;
guidata(gcf,my_gui_data);
% --- 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)
% Use guidata data struct instead of "global" variables
% global indexSelected;
%
% global files;
% global dname;
my_gui_data=guidata(gcf);
indexSelected=my_gui_data.indexSelected;
files=my_gui_data.files;
dname=my_gui_data.dname;
if(indexSelected == length(files))
indexSelected = 1 ;
% Use "fullfile" to build the file name
% filePath = [dname files(1).name];
filePath = fullfile(dname,files(1).name);
fileRead = dicomread(filePath);
imshow(fileRead,[]);
else
indexSelected = indexSelected + 1;
% Use "fullfile" to build the file name
% filePath = [dname files(indexSelected).name];
filePath = fullfile(dname,files(indexSelected).name);
fileRead = dicomread(filePath);
imshow(fileRead,[]);
end
% Store GUI data
my_gui_data.filePath=filePath;
my_gui_data.indexSelected=indexSelected;
guidata(gcf,my_gui_data);
% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% 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
% Set axes background color to black
set(hObject,'color','k')
% Remove X-axis and Y-axis ticks
set(gca,'xtick',[],'ytick',[])
The GUI just opened
The GUI with a DCOM image
Hope this helps.

How to pass data from one GUI to an other? Matlab

I am using a sub GUI to open the main GUI. In the sub GUI a pushbutton aLLows the user to select the data files they would like to upload. The first file is dealt with seperately and is then passed to the main GUI using setappdata and getappdata. Here is the code for the push button in the sub GUI:
% --- Executes on button press in ManualMultiple.
function ManualMultiple_Callback(hObject, eventdata, handles)
% hObject handle to ManualMultiple (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName,FilterIndex] = uigetfile('*.txt*','MultiSelect','on');
numfiles = size(FileName,2);
setappdata(0,'files',numfiles)
FileData= cell(1,numfiles);
for ii = 1:numfiles
FileName{ii};
A=[];
entirefile =fullfile(PathName,FileName{ii});
fid = fopen(entirefile);
tline = fgets(fid);
while ischar(tline)
parts = textscan(tline, '%f;');
if numel(parts{1}) > 0
A = [ A ; parts{:}' ];
end
tline = fgets(fid);
end
fclose(fid);
FileData{ii} = A;
A = FileData{ii};
X1 = A(:,1);
Y1 = A(:,5);
DataToUse{ii} = [X1, Y1];
end
FirstLoopX1Y1 = DataToUse{1};
X = FirstLoopX1Y1(:,1);
Y = FirstLoopX1Y1(:,2);
setappdata(0,'XValue',X)
setappdata(0,'YValue',Y)
for i = 2:numfiles
OtherLoopsXY = DataToUse{i};
X3 = OtherLoopsXY(:,1);
Y3 = OtherLoopsXY(:,2);
DataUseLater{i} = [X3,Y3]
end
setappdata(handles.ManualMultiple,'Data',DataUseLater)
GUImainwindow
Then when I push a button in the main GUI i should get the data sent from the sub to preform calculations on this data. Here is the code:
% --- Executes on button press in CalculateIntensity.
function CalculateIntensity_Callback(hObject, eventdata, handles)
% hObject handle to CalculateIntensity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Trapz function
starting_value = getappdata(0,'StartValue');
ending_value = getappdata(0,'EndValue');
StartingValue = str2num(starting_value);
EndingValue = str2num(ending_value);
A = getappdata(0,'XYarray');
%line 122 and 123 finds location of data in the entire spectrum
[~,indx1]=ismember(StartingValue,A,'rows');
[~,indx2]=ismember(EndingValue,A,'rows');
arrayfortrapz = A(indx1:indx2,1:2);
setappdata(0,'arraytapz',arrayfortrapz);
[value,index] = max(arrayfortrapz(:,2)); %finds max intensity / peak value
PeakValue = arrayfortrapz(index,1);
handles.Peak_Value = PeakValue;
guidata(hObject,handles);
X1 = arrayfortrapz(1:end,1);
Y1 = arrayfortrapz(1:end,2);
AUC = trapz(X1,Y1); %intergration
str = num2str(AUC);
[s,v] = listdlg('PromptString','Calculated Intensity:','SelectionMode','single','ListString',str,'ListSize',[200 200]);
IntensityValue = str(s,:);
setappdata(0,'IV',IntensityValue);
DataUseLater = getappdata(handles.ManualMultiple,'Data')
But when I push this button in the main GUI i get the errors:
Reference to non-existent field 'ManualMultiple'.
Error in MichelleLaycockGUImainwindow>CalculateIntensity_Callback (line 207)
DataUseLater = getappdata(handles.ManualMultiple,'Data')
Can anyone tell me how I could resolve this problem or even help me see where I am going wrong? Thanks in advance
What if you add guidata(hObject,handles) after this line:
setappdata(handles.ManualMultiple,'Data',DataUseLater) in your main window? It looks as if the handles structure was not updated after you created handles.ManualMultiple

Matlab GUI/GUIDE Appending item to vector stored in in a handle

I'm working on a program that records user button-presses in response to a sequence of tones. I am storing the timing of the button presses in a vector (pushTimes), which I am storing in GUIDE's "handles" structure, and I would like the new time of each button press to be appended to the pushTimes vector. However, handles doesn't seem to be storing the new vector with the appended value, leaving me with an empty vector after the button is pressed.
Edit: Because people were having difficulty reproducing the error, I'm posting the whole file The relevant code is in the callBack pushButton1. pushButton2 and pushButton3 are "pause" and "start" buttons, respectively. The error occurs even when I don't pause the program.
function varargout = simpleGui(varargin)
% SIMPLEGUI M-file for simpleGui.fig
% SIMPLEGUI, by itself, creates a new SIMPLEGUI or raises the existing
% singleton*.
%
% H = SIMPLEGUI returns the handle to a new SIMPLEGUI or the handle to
% the existing singleton*.
%
% SIMPLEGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SIMPLEGUI.M with the given input arguments.
%
% SIMPLEGUI('Property','Value',...) creates a new SIMPLEGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before simpleGui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to simpleGui_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 simpleGui
% Last Modified by GUIDE v2.5 27-May-2014 11:00:12
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #simpleGui_OpeningFcn, ...
'gui_OutputFcn', #simpleGui_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 simpleGui is made visible.
function simpleGui_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 simpleGui (see VARARGIN)
[soundVec, codeVec] = FourToneDifDirection();
handles.soundVec = soundVec;
handles.codeVec = codeVec;
handles.toneTimes = zeros(1,length(soundVec));
handles.pushTimes = [];
handles.toneNum = 1;
% Choose default command line output for simpleGui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes simpleGui wait for user response (see UIRESUME)
% --- Outputs from this function are returned to the command line.
function varargout = simpleGui_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 handles = 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)
dv = datevec(now);
%get the seconds from datevec
sec = dv(6);
%append to the pushTimes vector
handles.pushTimes = [handles.pushTimes sec]
%debugging line, should return a large vector after button is pressed multiple times but only returns a single value.
handles.pushTimes
guidata(hObject, handles)
% --- Executes on button press in pushbutton2.
function pushbutton2_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)
UIresume
guidata(hObject, handles);
soundVec = handles.soundVec
n = 1;
while(n<length(soundVec))
guidata(hObject, handles);
n = handles.toneNum
midigen(handles.soundVec(n), 0.25);
dv = datevec(now);
sec = dv(6);
handles.toneTimes(n) = sec;
n = n+1;
handles.toneNum = n;
end
guidata(hObject, handles)
% --- 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)
guidata(hObject, handles);
codeVec = handles.codeVec;
toneTimes = handles.toneTimes;
pushTimes = handles.pushTimes
calculateHitRate(codeVec, toneTimes, pushTimes,1,handles.toneNum);
guidata(hObject, handles)
uiwait(handles.figure1);
function out = isWithin(x, low, high)
out = x > low & x < high;
function [d1hr, d2hr, d3hr, d4hr] = calculateHitRate(codeVec, toneTimes, pushTimes, start, finish)
d1Ct = sum(codeVec(start:finish) == 9);
d2Ct = sum(codeVec(start:finish) == 10);
d3Ct = sum(codeVec(start:finish) == 11);
d4Ct = sum(codeVec(start:finish) == 12);
d1Push = 0;
d2Push = 0;
d3Push = 0;
d4Push = 0;
for i = 1:length(pushTimes)
pushTime = pushTimes(i)
stimTime = pushTime - 2;
for j = start:finish
%if the stimulus was within 1.5 seconds before the push
if codeVec(j) == 9 && isWithin(toneTimes(j), stimTime, pushTime)
d1Push = d1Push+1;
elseif codeVec(j) == 10 && isWithin(toneTimes(j), stimTime, pushTime)
d2Push = d2Push+1;
elseif codeVec(j) == 10 && isWithin(toneTimes(j), stimTime, pushTime)
d3Push = d3Push+1;
elseif codeVec(j) == 10 && isWithin(toneTimes(j), stimTime, pushTime)
d4Push = d4Push+1;
end
end
end
d1hr = d1Push/d1Ct
d2hr = d2Push/d2Ct
d3hr = d3Push/d3Ct
d4hr = d4Push/d4Ct

Updating GUI handles when using callback

I have a GUI made from GUIDE and I cannot figure out how to update a GUI handle when I call a callback in a callback. So for instance in the function which calls the function all I have is the following:
function start_ss_Callback(hObject, eventdata, handles)
% hObject handle to start_ss (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 start_ss as text
% str2double(get(hObject,'String')) returns contents of start_ss as a double
start_hh_Callback(hObject, eventdata, handles)
and in start_hh_Callback I have the code given below but my handles.plot_holds doesn't update regardless of the fact that I have guidata(hObject, handles). Is this because I'm using it as a function? If I just go through the start_hh_Callback itself not through start_ss_Callback, it updates. However, if I use it within a callback like start_ss_Callback it does not update.
I hope my question is clear, let me know if you need clarification.
function start_hh_Callback(hObject, eventdata, handles)
% hObject handle to start_hh (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 start_hh as text
% str2double(get(hObject,'String')) returns contents of start_hh as a double
axes(handles.axes1)
if isempty(handles.plot_holds)
cla
plot_button_Callback(hObject, eventdata, handles)
else
% in the event the time is changed after more than 1 plot is held then
% the additional plot times will be re evaluated for each parameter and
% the new indicies will take into affect.
myParams = get(handles.load_params_button,'string');
mystartDD = str2num(get(handles.start_dd,'string'));
mystartHH = str2num(get(handles.start_hh,'string'));
mystartMM = str2num(get(handles.start_mm,'string'));
mystartSS = str2num(get(handles.start_ss,'string'));
myendDD = str2num(get(handles.end_dd,'string'));
myendHH = str2num(get(handles.end_hh,'string'));
myendMM = str2num(get(handles.end_mm,'string'));
myendSS = str2num(get(handles.end_ss,'string'));
startFromStart = (mystartDD)*60*60*24 + (mystartHH-handles.startHour)*60*60 ...
+ (mystartMM-handles.startMinute)*60 + (mystartSS-handles.startSecond);
endFromStart = (myendDD)*60*60*24 + (myendHH-handles.startHour)*60*60 ...
+ (myendMM-handles.startMinute)*60 + (myendSS-handles.startSecond);
iStart = find(handles.load.dataGST.(handles.myParams{handles.plot_holds(1,1)}).(handles.myPackets{handles.plot_holds(1,1)}{handles.plot_holds(1,2)}).Time > (startFromStart+handles.startTimeOffset),1);
iEnd = find(handles.load.dataGST.(handles.myParams{handles.plot_holds(1,1)}).(handles.myPackets{handles.plot_holds(1,1)}{handles.plot_holds(1,2)}).Time > (endFromStart+handles.startTimeOffset),1);
if isempty(iEnd)
iEnd = length(handles.load.dataGST.(handles.myParams{handles.plot_holds(1,1)}).(handles.myPackets{handles.plot_holds(1,1)}{handles.plot_holds(1,2)}).Time);
end
cla
hold off
plot(handles.load.dataGST.(handles.myParams{handles.plot_holds(1,1)}).(handles.myPackets{handles.plot_holds(1,1)}{handles.plot_holds(1,2)}).Time(iStart:iEnd),...
handles.load.dataGST.(handles.myParams{handles.plot_holds(1,1)}).(handles.myPackets{handles.plot_holds(1,1)}{handles.plot_holds(1,2)}).Data(iStart:iEnd))
grid minor
box on
handles.plot_holds(1,3) = iStart;
handles.plot_holds(1,4) = iEnd;
if size(handles.plot_holds,1)>1
hold all
for ii = 2:size(handles.plot_holds)
iStart = find(handles.load.dataGST.(handles.myParams{handles.plot_holds(ii,1)}).(handles.myPackets{handles.plot_holds(ii,1)}{handles.plot_holds(ii,2)}).Time > (startFromStart+handles.startTimeOffset),1);
iEnd = find(handles.load.dataGST.(handles.myParams{handles.plot_holds(ii,1)}).(handles.myPackets{handles.plot_holds(ii,1)}{handles.plot_holds(ii,2)}).Time > (endFromStart+handles.startTimeOffset),1);
if isempty(iEnd)
iEnd = length(handles.load.dataGST.(handles.myParams{handles.plot_holds(ii,1)}).(handles.myPackets{handles.plot_holds(ii,1)}{handles.plot_holds(ii,2)}).Time);
end
plot(handles.load.dataGST.(handles.myParams{handles.plot_holds(ii,1)}).(handles.myPackets{handles.plot_holds(ii,1)}{handles.plot_holds(ii,2)}).Time(iStart:iEnd),...
handles.load.dataGST.(handles.myParams{handles.plot_holds(ii,1)}).(handles.myPackets{handles.plot_holds(ii,1)}{handles.plot_holds(ii,2)}).Data(iStart:iEnd))
handles.plot_holds(ii,3) = iStart;
handles.plot_holds(ii,4) = iEnd;
end
end
end
legend(handles.myLegends{1:length(handles.myLegends)})
guidata(hObject, handles);
You'll have to load the handles again, after any handles-modifying function:
% this modifies and writes the handles to the guidata
start_hh_Callback(hObject, eventdata, handles);
% now read back the updated value
handles = guidata(hObject);
Alternatively you could also make handles the return value of you callback.
Usually this will be ignored when it's really used as a callback and when used as a "normal" function it avoids the need to re-read from guidata.
Your code could then look like this:
handles = start_hh_Callback(hObject, eventdata, handles);
with your callback redefined to:
function [handles] = start_hh_Callback(hObject, eventdata, handles)
...
end