您需要通过匿名函数来做到这一点:
在脚本文件中,例如称为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));
myFunction.m
在与 test.m 相同的文件夹中调用的文件中
function myFunction(~, eventDat, x, N)
mean = sum(x)/N;
disp(mean);
key = eventDat.Key;
disp(key);
如何从 myFunction 返回值?有几种方法可以做到这一点。这取决于你想做什么。但很快您就可以为此使用可变变量,例如containers.Map
. 这是一个例子。返回的变量是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;