matlab - 在简单的程序中使用 MATLAB 的 'keyPressFcn'

标签 matlab user-interface matlab-figure

我尝试在普通 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/

相关文章:

matlab - "Simple"边缘-线-检测

python - 如何测试更快的 GUI 应用程序?

c++ - QT 窗口可以完全设计样式吗,包括在 Windows 7 或 Vista 上运行时的菜单栏吗?

matlab - 不支持使用 conv2 N-D 数组时出错

image - Matlab - 缩放图像的颜色条

matlab - 如何选择从 shell 或 Matlab 启动时启动哪个 Matlab 版本?

matlab - 将可变参数传递给 plot() 函数

python - 在 Python 中从控制台使用断点进行调试

user-interface - 如何将Widget注入(inject)自定义子Widget并使用子Widgets迭代索引?

matlab - MATLAB图中轴标签与轴之间的距离