data1 = load('out3.txt'); %加载数据到变量data1中 data = data1(:, 1); %取出变量data1中第1列中的数据到变量data中 %对数据进行平滑处理 data_smooth = smoothdata(data, 'movmean', 5); IndMin = find(diff(sign(diff(data_smooth))) > 0) + 1; %获得局部最小值的位置 IndMax = find(diff(sign(diff(data_smooth))) < 0) + 1; %获得局部最大值的位置 figure; %绘制图形 hold on; box on; plot(1:length(data_smooth), data_smooth); plot(IndMin, data_smooth(IndMin), 'r^'); plot(IndMax, data_smooth(IndMax), 'k*'); legend('曲线','波谷点','波峰点'); title('计算离散节点的波峰波谷信息', 'FontWeight', 'Bold'); 优化这段代码
时间: 2023-12-31 10:06:04 浏览: 90
这段代码已经比较简洁明了,但是可以考虑一些小的优化:
1. 加载数据和提取数据可以合并成一步,避免创建不必要的变量。
```MATLAB
data = load('out3.txt');
data_smooth = smoothdata(data(:,1), 'movmean', 5);
```
2. 可以将重复的代码封装成函数,提高代码的可复用性。
```MATLAB
function [IndMin, IndMax] = findExtrema(data_smooth)
%获得局部最小值的位置
IndMin = find(diff(sign(diff(data_smooth))) > 0) + 1;
%获得局部最大值的位置
IndMax = find(diff(sign(diff(data_smooth))) < 0) + 1;
end
```
3. 可以利用 MATLAB 的 subplot 函数将图形排版更加美观。
```MATLAB
figure;
subplot(2,1,1);
plot(data_smooth);
hold on;
plot(IndMin, data_smooth(IndMin), 'r^');
plot(IndMax, data_smooth(IndMax), 'k*');
box on;
legend('曲线','波谷点','波峰点');
title('计算离散节点的波峰波谷信息', 'FontWeight', 'Bold');
subplot(2,1,2);
plot(data);
box on;
title('原始数据', 'FontWeight', 'Bold');
```
这样修改后的代码如下:
```MATLAB
data = load('out3.txt');
data_smooth = smoothdata(data(:,1), 'movmean', 5);
[IndMin, IndMax] = findExtrema(data_smooth);
figure;
subplot(2,1,1);
plot(data_smooth);
hold on;
plot(IndMin, data_smooth(IndMin), 'r^');
plot(IndMax, data_smooth(IndMax), 'k*');
box on;
legend('曲线','波谷点','波峰点');
title('计算离散节点的波峰波谷信息', 'FontWeight', 'Bold');
subplot(2,1,2);
plot(data);
box on;
title('原始数据', 'FontWeight', 'Bold');
function [IndMin, IndMax] = findExtrema(data_smooth)
%获得局部最小值的位置
IndMin = find(diff(sign(diff(data_smooth))) > 0) + 1;
%获得局部最大值的位置
IndMax = find(diff(sign(diff(data_smooth))) < 0) + 1;
end
```
阅读全文