I have a main script in MATLAB in which I am calling four different functions each has been defined in a separate script.
function[] = main()
[par_1] =function_1(inp_1);
[par_2] = function_2(inp_2);
[par_3] = function_3(inp_3);
end
Now I want to define here that while for example function_1 is being called and is running, by pressing a key, for example 'esc', function_1 stops and return and function_2 starts running and so on. I don't know how to do this in MATLAB.

 採用された回答

Walter Roberson
Walter Roberson 2017 年 1 月 11 日

0 投票

In MATLAB, you can only do that with the cooperation of the function itself. You would define a callback such as a figure WindowKeyPressFcn callback, that would set a "key was pressed!" flag in a common space, and the functions being run would have to periodically check whether the flag was set and voluntarily exit if it found the flag set.

5 件のコメント

Nick Matin
Nick Matin 2017 年 1 月 11 日
Thanks for your answer. I am trying to do this but since the event listener is undocumented in matlab, I am having some problem. First of all should I use the event class as follows?
event.addlistener (Hsourse, 'KeyPressFcn',@CallbackFunction)
If yes, how should I define Hsource? Also how should I define the 'CallbackFunction' ? If you could refer me to an example in this regard, I appreciate that.
Walter Roberson
Walter Roberson 2017 年 1 月 12 日
It is not an event listener, it is a Figure property. The ability to listen to keypresses is associated with figures in MATLAB.
set(gcf, 'Windowkeypressfcn', @(src, event) set(src, 'UserData' true) )
Then when the cooperating routine starts, it should
set(gcf, 'UserData', false); %reset key-has-been-pressed
And assuming it is in a loop, from time to time it should
drawnow(); %give the graphics queue a chance to process the callback
if get(gcf, 'UserData') %was key pressed?
%the user pressed a key. Gracefully exit the loop
break;
end
Nick Matin
Nick Matin 2017 年 1 月 12 日
thank you so much.
Thomas
Thomas 2019 年 9 月 4 日
Need a comma after that first line's 'UserData'
Walter Roberson
Walter Roberson 2019 年 9 月 5 日
You are correct, Thomas, it should have been
set(gcf, 'Windowkeypressfcn', @(src, event) set(src, 'UserData', true) )

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeDesktop についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by