这里有一些代码可以帮助您使用setappdata 和getappdata。这是非常基本的,有些事情我没有提到(例如使用句柄结构或将变量作为输入参数传递给函数),但使用setappdata 和getappdata 是一种安全的方法。
我创建了 2 个程序化 GUI。代码看起来与使用 GUIDE 设计 GUI 时的代码有些不同,但原理完全相同。花时间检查它并了解一切的作用;这不是太复杂。
每个 GUI 都由一个按钮和一个轴组成。在第一个 GUI (sine_signal) 中创建并显示正弦波。按下按钮打开第二个 GUI (gui_filtering) 并调用 setappdata。一旦按下第二个 GUI 的按钮,就会调用 setappdata 来获取数据并绘制它。
这是两个 GUI 的代码。您可以将它们保存为 .m 文件,然后在 sine_signal 函数中按“运行”。
1) 正弦信号
function sine_signal
clear
clc
%// Create figure and uicontrols. Those will be created with GUIDE in your
%// case.
hFig_sine = figure('Position',[500 500 400 400],'Name','sine_signal');
axes('Position',[.1 .1 .8 .8]);
uicontrol('Style','push','Position',[10 370 120 20],'String','Open gui_filtering','Callback',@(s,e) Opengui_filt);
%// Create values and plot them.
xvalues = 1:100;
yvalues = sin(xvalues).*cos(xvalues);
plot(xvalues,yvalues);
%// Put the x and y values together in a single array.
AllValues = [xvalues;yvalues];
%// Use setappdata to associate "AllValues" with the root directory (0).
%// This way the variable is available from anywhere. You could also
%// associate the data with the GUI itself, using "hFig_sine" instead of "0".
setappdata(0,'AllValues',AllValues);
%// Callback of the pushbutton. In this case it is simply used to open the
%// 2nd GUI.
function Opengui_filt
gui_filtering
end
end
和
2) gui_filtering
function gui_filtering
%// Same as 1st GUI.
figure('Position',[1000 1000 400 400],'Name','sine_signal')
axes('Position',[.1 .1 .8 .8])
%// Pushbutton to load data
uicontrol('Style','push','Position',[10 370 100 20],'String','Load/plot data','Callback',@(s,e) LoadData);
%// Callback of the pushbutton
function LoadData
%// Use "getappdata" to retrieve the variable "AllValues".
AllValues = getappdata(0,'AllValues');
%// Plot the data
plot(AllValues(1,:),AllValues(2,:))
end
end
为了向您展示预期的输出,以下是在以下情况下获得的 3 个屏幕截图:
1) 您运行第一个 GUI (sine signal):
2) 按下按钮打开第二个 GUI 后:
3) 按下第二个 GUI 的按钮加载/显示数据后:
就是这样。希望对您有所帮助!