我尝试在普通 MATLAB 脚本中使用“KeyPressFcn”,但遇到问题。我可以在函数( like here )中很好地使用它,但我想在普通脚本中使用它,就像这样。
我的简单脚本是:
%Entry Point
clear all
N = 100;
x = randn(1,N);
figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', myFunction(~, eventDat,x,N))
这是位于同一目录中的函数“myFunction”:
function myFunction(~, eventDat,x,N)
mean = sum(x)/N;
disp(mean);
key = eventDat.Key;
disp(key);
end
现在,如果我运行这个,它不起作用,因为,(我怀疑),我调用 myFunction 的方式有问题,但我无法弄清楚问题到底是什么,因为我是一个菜鸟使用 KeyPressFcn。对于这个问题,我们将不胜感激。谢谢!
最佳答案
您需要通过匿名函数来完成:
在脚本文件中,例如名为 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));
在与 test.m 位于同一文件夹中的名为 myFunction.m
的文件中
function myFunction(~, eventDat, x, N)
mean = sum(x)/N;
disp(mean);
key = eventDat.Key;
disp(key);
如何从 myFunction 返回值?
有few ways这样做的。这取决于你想做什么。但很快您就可以使用可变变量来实现此目的,例如 containers.Map
。这是 ding this 的一个例子。返回的变量是newN
。
在脚本文件中,例如名为 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
在名为 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;
关于matlab - 在简单的程序中使用 MATLAB 的 'keyPressFcn',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579194/