您需要通過匿名函數來做到這一點:
在腳本文件,例如名爲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返回值? 有這樣做的few ways。這取決於你想做什麼。但很快你可以使用可變的變量,例如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;