问题描述
我正在尝试在普通的MATLAB脚本中使用'KeyPressFcn',但是遇到了问题.我可以在一个函数中很好地使用它,(就像这里),但是我想像这样在普通脚本中使用它.
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.
我的简单脚本是:
%Entry Point
clear all
N = 100;
x = randn(1,N);
figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', myFunction(~, eventDat,x,N))
这是位于同一目录中的函数"myFunction":
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
现在,如果我运行此命令,它将不起作用,因为(我怀疑)我调用myFunction的方式出了点问题,但由于我是菜鸟,所以我无法弄清楚到底是什么问题使用KeyPressFcn.对于这个问题的帮助将不胜感激.谢谢!
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!
推荐答案
您需要通过匿名函数来做到这一点:
You need to do it through anonymous functions:
在脚本文件中,例如称为test.m
:
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));
在与test.m相同的文件夹中的名为myFunction.m
的文件中
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);
如何从myFunction返回值?有几种方法可以执行此操作.这取决于你想做什么.但是很快您可以为此使用可变变量,例如containers.Map
.这是对此的一个例子.返回的变量是newN
.
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
.
在脚本文件中,例如称为test.m
:
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
在名为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的'keyPressFcn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!