1、首先生成一组0-100的随机数,组内共有100个数据;
yy=randi([0,100],[1,100]);
2、求这组数据的功率谱密度,并绘图;
m=size(yy,2); xdft = fft(yy);
% 计算功率谱密度
psd = (1/m) * abs(xdft).^2; x=1:m;
loglog(x,psd,'Linewidth',1.5); grid on;
3、在图上分别标注功率谱密度的最值和某些极值
①[maxVal, maxIdx] = max(psd); [minVal, minIdx] = min(psd); % 最值和对应的索引
text(x(1,maxIdx),maxVal, sprintf('%.2e',maxVal), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",13)
text(x(1,minIdx),minVal, sprintf('%.2e',minVal), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",13)
②[peaks1, locs1] = findpeaks(psd); [peaks2, locs2]= findpeaks(-psd); %极值和对应的索引
%%选出一些较为明显的极值进行标注
for ii=[1,2]
text(x(locs1(1,ii)),peaks1(1,ii), sprintf('%.2e',peaks1(1,ii)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",10);
end
for ii=[1,13]
text(x(locs2(1,ii)),-1*peaks2(1,ii), sprintf('%.2e',-1*peaks2(1,ii)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",10);
end
示例代码如下:
clearvars -except yy
close all;
yy=randi([0,100],[1,100]);
m=size(yy,2);
xdft = fft(yy);
% 计算功率谱密度
psd = (1/m) * abs(xdft).^2; x=1:m;
loglog(x,psd,'Linewidth',1.5); grid on;
xlabel('Frequency (Hz)','Fontname','Time New Roman',"FontSize",15);
ylabel('PSD','Fontname','Time New Roman',"FontSize",15);
[maxVal, maxIdx] = max(psd); [minVal, minIdx] = min(psd); % 最值和对应的索引
text(x(1,maxIdx),maxVal, sprintf('%.2e',maxVal), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",13)
text(x(1,minIdx),minVal, sprintf('%.2e',minVal), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",13)
[peaks1, locs1] = findpeaks(psd); [peaks2, locs2]= findpeaks(-psd); %极值和对应的索引
%选出一些较为明显的极值进行标注
for ii=[1,2]
text(x(locs1(1,ii)),peaks1(1,ii), sprintf('%.2e',peaks1(1,ii)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",10);
end
for ii=[1,13]
text(x(locs2(1,ii)),-1*peaks2(1,ii), sprintf('%.2e',-1*peaks2(1,ii)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom',"FontSize",10);
end
如有问题,欢迎随时联系交流! 多多点赞加倍支持,不甚感激😂😂😂