参考GPT和自己的思路,下面是一个简单的 Matlab GUI 程序实现你的需求。该程序包括一个主窗口,其中有两个按钮 "Select File" 和 "Stop",以及四个 axes 组件分别用于显示两个信号的时域波形和频谱。
程序实现步骤如下:
1 创建 GUI 窗口并定义需要用到的变量
function myGUI
% 创建 GUI 窗口并定义需要用到的变量
% 创建主窗口
f = figure('Visible','off','Position',[360,500,600,400]);
% 定义需要用到的变量
fs = 120; % 采样频率
T = 3*60; % 信号长度(秒)
N = fs*T; % 信号长度(采样点数)
t = (0:N-1)/fs; % 时间向量
data = []; % 存储读入的信号数据
timer_interval = 0.05; % 定时器触发间隔
timer1 = timer('ExecutionMode', 'fixedRate', 'Period', timer_interval, 'TimerFcn', @updatePlot); % 定义定时器1
timer2 = timer('ExecutionMode', 'fixedRate', 'Period', timer_interval, 'TimerFcn', @updateFFT); % 定义定时器2
isRunning = false; % 用于判断程序是否在运行
stopFlag = false; % 用于停止定时器
% 定义 UI 控件
btn_select_file = uicontrol('Style', 'pushbutton', 'String', 'Select File', 'Position', [10 350 80 30], 'Callback', @selectFile);
btn_stop = uicontrol('Style', 'pushbutton', 'String', 'Stop', 'Position', [100 350 80 30], 'Callback', @stopTimer);
ax1 = axes('Units','pixels','Position',[60,60,250,250]);
ax2 = axes('Units','pixels','Position',[350,60,250,250]);
% 显示 GUI 窗口
f.Visible = 'on';
end
2 创建回调函数
% 回调函数1:读入文件并显示时域波形
function selectFile(~,~)
% 选择文本文件
[filename, path] = uigetfile('*.txt', 'Select a text file');
if isequal(filename,0)
return;
end
% 读入文件
fid = fopen(fullfile(path,filename),'r');
data = fscanf(fid,'%f %f\n',[2 inf]);
fclose(fid);
% 在 axes1 中显示信号1
axes(ax1);
plot(t, data(1,:), 'r');
xlim([0 max(t)]);
xlabel('Time (s)');
ylabel('Amplitude');
title('Signal 1');
% 在 axes2 中显示信号2
axes(ax2);
plot(t, data(2,:), 'b');
xlim([0 max(t)]);
xlabel('Time (s)');
ylabel('Amplitude');
title('Signal 2');
% 启动定时器
if ~isRunning
startTimer();
end
end
% 回调函数2:定时器1触发,更新时域波形
function updatePlot(~,~)
if stopFlag
stopTimer();
return;
end
% 更新时域波形
axes(ax1);
xlim([max(0, t(end)-T), t(end)]);
plot(t, data(1,:), 'r');
xlabel('Time (s)');
ylabel('Amplitude');
title('Signal 1');
axes(ax2);
xlim([max(0, t(end)-T), t(end)]);
plot(t, data(2,:), 'b');
xlabel('Time (s)');
ylabel('Amplitude');
title('Signal 2');
end
% 回调函数3:定时器2触发,更新频谱
function updateFFT(,)
if stopFlag
stopTimer();
return;
end
% 计算频谱
S1 = fft(data(1,:));
S2 = fft(data(2,:));
f = (0:N-1)*(fs/N);
% 更新频谱
axes(ax1);
plot(f, abs(S1), 'r');
xlim([0 fs/2]);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Spectrum of Signal 1');
axes(ax2);
plot(f, abs(S2), 'b');
xlim([0 fs/2]);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Spectrum of Signal 2');
end
% 回调函数4:启动定时器
function startTimer(,)
if isempty(data)
return;
end
isRunning = true;
start(timer1);
start(timer2);
end
% 回调函数5:停止定时器
function stopTimer(,)
stopFlag = true;
stop(timer1);
stop(timer2);
isRunning = false;
end
3 运行程序
将上面的代码保存为一个 Matlab 脚本文件,运行该文件即可启动 GUI 程序。在 GUI 窗口中点击 "Select File" 按钮,选择文本文件并加载数据。然后点击 "Stop" 按钮即可停止程序运行。