Use MATLAB's 'keyPressFcn' in a simple program

半世苍凉 提交于 2019-12-11 00:46:33

问题


I am trying to use the 'KeyPressFcn' in a normal MATLAB script, but I am having problems. I can use it nicely WITHIN a function, (like here), but I would like to use it in a normal script like so.

My simple script is:

%Entry Point
clear all

N = 100;
x = randn(1,N);

figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', myFunction(~, eventDat,x,N))

Here is the function 'myFunction' that sits in the same directory:

function myFunction(~, eventDat,x,N)

    mean = sum(x)/N;
    disp(mean);
    key = eventDat.Key;
    disp(key);

end

Now, if I run this, it does not work, because, (I suspect), something is wrong with the way I am calling myFunction, but I cannot figure out what the problem is exactly, since I am a noob at using KeyPressFcn. Help would be appreciated for this problem. Thanks!


回答1:


You need to do it through anonymous functions:

In script file, for example called test.m:

%Entry Point
clear all

N = 100;
x = randn(1,N);

figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', ...
    @(fig_obj , eventDat) myFunction(fig_obj, eventDat, x, N));

In a file called myFunction.m in the same folder as test.m

function myFunction(~, eventDat, x, N)

    mean = sum(x)/N;
    disp(mean);
    key = eventDat.Key;
    disp(key);

How to return value from myFunction? There are few ways of doing this. It depends on what u want to do. But quickly you could use mutable variables for this, such as, containers.Map. This is one example of ding this. The returned variable is newN.

In script file, for example called test.m:

%Entry Point
clear all

N = 100;
x = randn(1,N);

% this map will store everything u want to return from myFunction.
returnMap = containers.Map;

figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', ...
    @(fig_obj , eventDat) myFunction(fig_obj, eventDat, x, N, returnMap));


% wait till gui finishes in this example.
waitfor(figHandle);

newN = returnMap('newN');

% display newN
newN

In a file called myFunction.m:

function myFunction(handle, eventDat, x, N, returnMap)

    mean = sum(x)/N;
    disp(mean);
    key = eventDat.Key;
    disp(key);

    newN = 435;

    returnMap('newN') = newN;


来源:https://stackoverflow.com/questions/19579194/use-matlabs-keypressfcn-in-a-simple-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!