Closing MATLAB GUI application programmatically without using error() - matlab

I am trying to make it so the application/gui closes completely if the user clicks cancel or exit of an input dialog. The tag of my gui is called window however using close(handles.window); leads to the program looping through once and then (after the user clicks cancel or exit again) reaching the close(handles.window); line which, of course, leads to an Invalid figure handle error.
Is there any method to close the application without the need for producing an error and not closing the entire MATLAB environment (like quit and exit). The error() is my temporary fix which works but I don't want the application to seem like it has crashed.
I have tried close all but that has no effect. It's worth noting that the application does reach inside the if statement if the user clicks cancel or exit.
I have also tried setting a variable and having the close commands outside the while loop.
apa = getAvailableComPort();
apList = '';
i = 0;
for idx = 1:numel(apa)
if i == 0
apList = apa(idx);
else
apList = strcat(apList, ', ', apa(idx));
end
i = i + 1;
end
prompt = {'Enter COM PORT:'};
title = 'COM PORT';
num_lines = 1;
def = apList;
COM_PORT = inputdlg(prompt,title,num_lines,def);
% Keep asking for a COM PORT number until user gives a valid one
while sum(ismember(apa, COM_PORT)) == 0 % If the COM port comes up in the available COM ports at least once
% If user clicks cancel, close the guide
if isempty(COM_PORT) == 1
error('Closing...'); % HERE IS THE PROBLEM
end
prompt = {'Invalid COM PORT'};
title = 'Invalid COM PORT';
COM_PORT = inputdlg(prompt,title,num_lines,def);
end
The function getAvailableComPort is found at http://www.mathworks.com/matlabcentral/fileexchange/9251-get-available-com-port
This entire piece of code is at the top of the gui_OpeningFcn() function.

Have you tried putting a break after the close(handles.window). The break will exit the while loop so it won't hit that line again.
if isempty(COM_PORT) == 1
close(handles.window)
break
end
This way the while loop stops after closing the window. IF you need to do more cleanup besides just closing the window then set an error flag .
%Above while loop
errorFlag = False;
if isempty(COM_PORT) == 1
close(handles.window)
errorFlag = True;
break
end
%OutSide of While loop
if errorFlag
%Do some more clean-up / return / display an error or warning
end
Also FYI, you don't need to do isempty(COM_PORT) == 1 ... isempty(COM_PORT) will return true/false without the == 1

Your requirements aren't really clear, but can't you just protect the close operation by doing
if ishandle(handle.window)
close(handle.window)
end
This will prevent the close from being attempted if the window has already been destroyed.

Why don't you use a simple return and a msgbox to inform that user has clicked on Cancel?
if isempty(COM_PORT)
uiwait(msgbox('Process has been canceled by user.', 'Closing...', 'modal'));
delete(your_figure_handle_here);
return;
end

I tried using the return statement in conjunction with close(handles.window) but received the error:
Attempt to reference field of non-structure array.
Error in ==> gui>gui_OutputFcn at 292 varargout{1} = handles.output;
So it seems just removing that line on 292 solved the issue.

Related

Why is KbCheck in Psychtoolbox not registering keyboard input?

I'm trying to run a programme coded in Psychtoolbox-3 that should register a keypress. But when I run it, even just this section from the command window, it doesn't respond to the E, P keys (or any) and I have to stop the operation using Ctrl-C. I have tried changing it to {e, p} (which are the names I found using KbName('KeyNames')), but it doesn't work.
The same code works on my supervisor's computer - I am using a Mac with OS 11.1.
KbName('UnifyKeyNames');
keyresp = KbName({'E','P'});
key = 0;
while ~key
[key,tkey] = CheckKeyPress(keyresp);
end
The CheckKeyPress is this function (and it works - gives output 0):
function [key,tkey] = CheckKeyPress(whichkeys)
if nargin < 1 || isempty(whichkeys)
whichkeys = 1:256;
end
key = 0;
[iskeydown,tkey,keys] = KbCheck(-1);
if any(keys(whichkeys))
key = find(keys(whichkeys),1);
end
end
I have also tried looking at PsychHID('Devices') and my keyboard is there (and no other keyboards).
Thanks for any help!
Solved! It was a simple mac problem :)
After I tried KbQueueCreate and got an error message I found the same one on another thread - the only problem is I had to allow Matlab to access keyboard input on my laptop.
Settings - Security and Privacy - Input Monitoring
It is always a big pain in MacOs. I use this code:
close all
clear all
clc
ListenChar(0);
Devices=PsychHID('Devices');
keyboardsIDs = [];
for iiD = 1:numel(Devices)
try
KbQueueCreate(Devices(iiD).index);
KbQueueStart(Devices(iiD).index);
keyboardsIDs(end+1,1) = Devices(iiD).index;
end
end
stopScript = 0;
while ~stopScript
for iiD = 1:numel(keyboardsIDs)
[keyIsDown, firstPress]=KbQueueCheck(keyboardsIDs(iiD));
if keyIsDown
keyID = find(firstPress)
disp(keyID)
if any(keyID ==20), stopScript =1; end
end
end
end
for iiD = 1:numel(keyboardsIDs)
KbQueueStop(keyboardsIDs(iiD));
end
ListenChar();
UPDATE
This is a bit dirty workaround, but it will works in any situation.
Press 'q' to exit the loop

Matlab Psychtoolbox fprintf error with multiple keypresses within a trial

I have an experiment that collects keypresses ('x' or 'n') and reaction time in response to a stimulus display. If the participant presses either button once per trial the experiment runs fine. However, if they press the keyboard repeatedly or hold down a key, it will often crash. (I work with children and even if we ask them not to, this often will still happen).
The error that comes up when it crashes is:
Function is not defined for 'cell' inputs.
Error in Experiment (line 682)
fprintf(dataFile, formatString, SJNB, Date, Age, block, trial, trialFaceLabel, trialLoadLabel, Target, keyStroke, tStart, keyTime, Correct, RT, FaceGen);
Although it says 'Function is not defined for 'cell' inputs' (which is related to this post), this function does appear to work properly at all other times, so I can't see that it is simply not defined properly. It is only when too many keypresses have been pressed in a row (e.g. if the key has been held down), that this error occurs.
What changes can I make to ensure the experiment is robust and doesn't crash, even if there are multiple keypresses per trial? Any help would be appreciated.
I have included the code below.
Here's some additional info, in case this is helpful:
Prior to the experimental trial there is a practice loop which is set up in very much the same way but with two main differences, 1) the stimuli displayed to the screen are different and 2) the keypresses are not recorded. This loop doesn't seem to ever crash.
After crashing, the keypress responses are printed to the command line.
I have had a look at other similar posts, e.g. this post, but as far as I understand it, the keypress loop that I have written should also exit as soon as a key has been pressed - so I'm not sure why mine is not working in the same way.
The code below is all included in an experimental loop. What it's doing is:
1) searching for a keypress
2) calculating response time based on the keypress
3) beeping if the response was incorrect
4) printing to file (this is just before the end of the trial) (this is the line that the error references)
%searching for keypress
timedout = false;
pressed = 0;
%while pressed < 1;
while ~timedout && ~pressed
[keyIsDown, keyTime, keyCode] = KbCheck;
if keyIsDown && ((keyTime-tStart) < max_stimulus_shown)
keyStroke = KbName(keyCode);
if any(strcmpi(keyStroke,leftKey)) || any(strcmpi(keyStroke,rightKey)) %|| any(strcmpi(keyStroke,exitKey))
pressed = 1;
WaitSecs(remainer-(keyTime-stimulus_shown));
break;
elseif any(strcmpi(keyStroke,exitKey))
disp('*** Experiment terminated ***');
break;
sca;
end
elseif ((keyTime-tStart) > max_stimulus_shown)
keyStroke = 'None';
timedout = true;
RT = 0;
Correct = 0;
pressed = 2; % 2 = not pressed
KbQueueStop();
end
end
%calculate response times
if pressed == 1 && (~timedout)
RT = round((keyTime-tStart)*1000); % RT in ms
if any(strcmpi(keyStroke,leftKey)) % pressed left (X)
if any(strcmpi(Target, 'X')) % target was an X
Correct = 1;
else % target was X, but pressed right (N)
Correct = 0;
end
elseif any(strcmpi(keyStroke,rightKey)) % they pressed right
if any(strcmpi(Target, 'N')) % target was an N
Correct = 1;
else % target was N, but pressed right
Correct = 0;
end
elseif any(strcmpi(keyStroke,exitKey))
disp('ESC');
break;
end
end
Screen('TextSize',Screen_wid, star_size);
DrawFormattedText(Screen_wid, '.', 'center', 'center');
WaitSecs(feedback);
Screen('Flip', Screen_wid);
%say when to beep
if Correct == 0 && ~timedout
PsychPortAudio('Start', pahandle, repetitions, startCue, waitForDeviceStart);
WaitSecs(remainer-beepLengthSecs);
elseif Correct == 0 && timedout
PsychPortAudio('Start', pahandle, repetitions, startCue, waitForDeviceStart);
Screen('TextSize',Screen_wid, text_size);
DrawFormattedText(Screen_wid, 'missed trial', 'center', 'center');
Screen('Flip', Screen_wid);
WaitSecs(beepLengthSecs+feedback);
elseif Correct == 1
WaitSecs(remainer+beepLengthSecs);
end
%WaitSecs(stimulus_shown); %stimulus shown for 0.2 seconds
Screen('Flip', Screen_wid);
dataFile = fopen(dataFileName, 'a');
fprintf(dataFile, formatString, SJNB, Date, Age, block, trial, trialFaceLabel, trialLoadLabel, Target, keyStroke, tStart, keyTime, Correct, RT, FaceGen);
fclose(dataFile);
The function KbName returns the name string of key(s) input, via either a vector of key codes ( key_name = KbName([21 22]) ), or a logical vector, as returned by KbCheck.
If only only key is provided / is True, it is returned as a string. But, if more than one key is pressed at the same time, it is returned as a cell array of strings.
For example, look at the output of:
% for key name consistency across operating systems
KbName('UnifyKeyNames')
% one key
KbName(21)
ans =
r
% more than one key
KbName([21 22])
ans =
1×2 cell array
'r' 's'
Your issue is that when more than one key is pressed at the same time (with respect to the key checking loop), keyStroke is a cell array containing the keys that were pressed. You seem to be processing the cell array appropriately within most of your code, with the exception of the call to fprintf, which expects a single string, not a cell array of strings.
If you want to save a record of all keys pressed, you can convert the cell array of strings to a single string with delimiter between elements, for example by adding the following line prior to the call to fprintf:
if iscell(keyStroke)
keyStroke = strjoin(keyStroke, '_');
end
But, also keep in mind that you might want to change the logic of your experiment to reject trials in which two keys were pressed, or otherwise treat them differently than single key responses. You currently have the 'left' key taking precedence, in other words if the participant has the left key pressed and the target is an 'X', the trial will be marked correct, even if the right key is also pressed. Conversely if the participant has the left key pressed and the target is a 'N', the trial will be marked as incorrect, even if the right key is also pressed.

Break / Stop while loop from user input at the Matlab command line

I am attempting to create a while loop that will loop continuously until input from the user at the command line.
I have tried two implementations of this the first, the first derived from this bit of python. The problem being that you must enter something other than exit every time you want to iterate through loop.
global active
active = true;
while active == true
userInput = input('enter: ','s');
inputHandler(userInput)
disp(rand)
pause(1);
end
function inputHandler(value)
global active
if value == 'exit'
active = false;
end
end
The second was
global loopFlag
loopFlag = true
while loopFlag == true
%some awesome code happens here
end
with the idea being that you could enter at the command line loopFlag = false while the code was executing and it would stop.
I know this can be done through the use of a toggle button but I would prefer not to have to go that route unless absolutely necessary.
active = true;
while active == true
active = input('Enter true or false ' );
disp(rand)
pause(1)
end

Matlab - Is there a way to capture messages sent to the workspace?

I'm working on a GUI (without GUIDE) in Matlab. The GUI will ultimately be compiled to an application and released to my coworkers.
My GUI calls some custom functions I wrote ages ago. These custom functions display status/progress messages to the workspace window.
As I understand it, I could have my executable write those messages to a log file, but then that leaves the user without any status updates on the GUI while the program is running.
I'm working on some pretty intensive 3D data manipulation, which has the potential to run for 5-10 minutes between function calls, so while I could provide status updates between function calls, it still leaves the end user with no idea what's going on and/or the appearance that the program locked up.
What I would like to do is to have something that works akin to the 'try-catch' method, where there's some way I can execute a function and capture messages intended for the workspace and redirect them to a uicontrol text box.
:EDIT:
I'm adding this for posterity, in the event anyone wants to use it. This is a functional demo that shows how to implement Peter's answer below.
First, create and save a function called "EndlessLoop":
function EndlessLoop(handles,loopCallback)
if nargin<1
handles = [];
loopCallback = #loop_Callback;
else
disp('Callback already set!');
end
tic;
abort = false;
while true
statusText = sprintf('Current Elapsed Time:\n%.2f',toc);
abort = loopCallback(handles,statusText);
if abort
statusText = sprintf('Abort request processed.\nEnding now.');
[~] = loopCallback(handles,statusText);
break;
end
pause(0.1);
end
return;
function abort = loop_Callback(~,myText)
clc;
abort = false;
disp(myText)
return;
Then, create a GUI that calls on EndlessLoop:
function TestGUI
close all;
myTest = figure('Visible','on','Units','normalized','Position',[0.1 0.1 0.8 0.8],'Name','Test GUI','NumberTitle','off');
set(myTest,'menubar','none');
handles = guihandles(myTest);
handles.goButton = uicontrol('Style','pushbutton','Units','normalized','Position',[0 0.5 0.5 0.5],'String','Go');
handles.abortButton = uicontrol('Style','pushbutton','Units','normalized','Position',[0 0 0.5 0.5],'String','Abort','Enable','off');
handles.statusText = uicontrol('Style','text','Units','normalized','Position',[0.5 0 0.5 1],'String','Press Go when ready.');
set(handles.goButton,'Callback',#goButton_Callback,'interruptible','on');
set(handles.abortButton,'Callback',#abortButton_Callback,'interruptible','on');
handles.abortButton.UserData = false;
guidata(myTest,handles);
return;
function goButton_Callback(hObject,~)
handles = guidata(gcbo);
hObject.Enable = 'off';
handles.abortButton.Enable = 'on';
EndlessLoop(handles,#StatusUpdate)
handles.abortButton.String = 'Abort';
handles.abortButton.Enable = 'off';
hObject.Enable = 'on';
pause(0.5);
handles.statusText.String = 'Press Go to start again.';
handles.abortButton.UserData = false;
guidata(gcbo,handles);
return;
function abortButton_Callback(hObject,~)
handles = guidata(gcbo);
if handles.abortButton.UserData
handles.abortButton.UserData = false;
hObject.String = 'Abort';
else
handles.abortButton.UserData = true;
hObject.String = sprintf('Abort pending...');
end
guidata(gcbo,handles);
return;
function abort = StatusUpdate(handles,statusText)
clc;
abort = handles.abortButton.UserData;
disp(handles.abortButton.UserData)
handles.statusText.String = statusText;
return;
A couple things I found when playing with this trying to get it to work:
I have been just adding variables to the handles structure for whatever I needed. In this case it would have been handles.abortRequest = false;. However, it appears that when I pass handles to the EndlessLoop function it becomes stale - handles never updates again. To get around this, I had to store what I wanted in the UserData section of the abortButton. I think this is because the handle to abortButton is still valid, because it hasn't changed, and I get fresh UserData because I'm able to poll with the valid handle. I can't access handles.abortRequest because it's not an object - I can't poll it; it simply exists, and it exists in the "snapshot" that was when I sent handles to EndlessLoop. At least, this is my understanding.
I needed to set the 'Interruptible' property of the goButton callback to 'on' in order for the abortButton to function while the process "hung" on EndlessLoop. With Interruptible set to off no other callbacks may be processed until that particular callback completes, which will never happen with endless loop.
So, in conclusion, this is a complete functional example that answers my question. Thanks to Peter for the answer - this also includes his ProTip of being able to pass an abort option back to the process that's taking a long time to complete. I've never used callbacks like this before so hopefully others will find this useful in the future.
This answer elaborates on my comment to the question.
Assume you have function that outputs stuff to the command window:
function out = longcomputation(param1, param2)
%
while(for_a_long_time)
process_one_step();
percent_complete = something;
fprintf('Step result: %f Complete: %f', stuff, percent_complete);
end
You can make the output function configurable by passing a function handle. Here I'm making it optional by testing nargin:
function out = longcomputation(param1, param2, outputfcn)
function display_progress_to_console(msg, percentage)
sprintf('%s, Complete %f', msg, percentage);
end
if(nargin < 3) % Supply a default output function if none passed in
outputfcn = #display_progress_to_console;
end
while(for_a_long_time)
process_one_step();
percent_complete = something;
msg = sprintf('Step result: %f', stuff);
outputfcn(msg, percent_complete);
end
Now, in your GUI, you can define and pass in a different output callback. This can live right in your GUI code so that the function has access to the GUI objects you need.
ProTip: In addition, have this callback function return true or false to signal the user's desire to abort. The GUI can then present a cancel button to drive that return value, and the long-running code can periodically send the status message AND check if abort has been requested.
You could potentially use the built-in diary functionality to accomplish something similar to what you're trying to do.
diary on % Uses "diary" for filename
diary('logfile.log') % Custom filename
This will write all command line output to the specified file. Then you can periodically poll this file and update your uicontrol with the contents (or last few lines if you want).
logfile = 'logfile.log';
diary(logfile);
u = uicontrol('style', 'text');
% Check every 5 seconds
t = timer('Period', 5, ...
'ExecutionMode', 'FixedRate', ...
'TimerFcn', #(s,e)populate(s));
start(t);
function populate(src)
fid = fopen(logfile, 'rb');
contents = fread(fid, '*char').';
set(src, 'String', contents);
fclose(fid);
end

While debugging with an input from the keyboard, I want to able to skip the execution of a few lines of code in MATLAB

Currently I have this excerpt of code I am trying to debug:
if (white_flag == 1)
keyboard;
imshow(rl_img);
N = N+1;
times(times_index,1) = index;
while(white_flag == 1)
imshow(rl_img);
index = index+1;
%%% If statement for when the loop has run out
if (index >= frames)
break
end
%%% Initial Image Pre-Processing
rl_img = ones(mod_height,width);
pre_rl_img = medfilt2(vreader.read(index));
for i = 1:mod_height
for j = 1:width
rl_img(i,j) = pre_rl_img(i,j);
end
end
white_flag = detect_white( rl_img, white_flag );
end
times(times_index,2) = index;
times_index = times_index+1;
else
index = index+ 1;
end
Now, as you can see, the debug keyboard input call keybaord is on the second line. While this allows me to efficiently see each step of the execution of my program, I do not understand how to skip over the part below:
for i = 1:mod_height
for j = 1:width
rl_img(i,j) = pre_rl_img(i,j);
end
end
This is a rather sizable picture(rl_img), so waiting for keyboard input while I scrawl through the code manually wastes a lot of time. Can someone please tell me how to skip the user input execution of these lines of code while I debug the program?
Please do not hesitate to ask me any questions that can clarify this problem. Thank you for all your answers!
The answer is quite straightforward:
you set a breakpoint after the lengthy loop,
when you decide to run automatically all the rest of the loop up to the breakpoint you just set, press [F5] (Continue).
This assumes that you debug your code in the normal MATLAB IDE.
If I understand your problem correctly, you don't want to step through each loop iteration.
You can either follow CST-Link's advice or you can avoid creating additional breakpoints by placing your cursor somewhere after the loop
and clicking
on the editor's debug panel.