我想在矢量中找到区间1中的最大值和区间2中的最大值(如示例图所示)。给出了区间1和2的边界。
新版本 - 代码更可重复使用
只使用Dennis Jaheruddin建议的一个区间,并将其作为函数编写。
function test
%% Test data
x=0:0.1:10-0.1;
x_total=0:0.1:20-0.1;
y=-(x-5.8).^2+25;
y_total=[y,y+10];
figure(1);
plot(x_total,y_total); grid on;
interval=[12,18];
[maxValue,maxValuePositon] = findMaxInInterval(x_total,y_total,interval)
[maxValue,maxValuePositon] = findMaxInInterval2(x_total,y_total,interval)
end
%% Algorithm
function [maxValue,maxValuePositon] = findMaxInInterval(x,y,interval)
index = x>=interval(1) & x <= interval(2);
offset = find(index == 1,1,'first') -1;
[maxValue,indexMax] = max(y(index));
maxValuePositon = x(indexMax+offset);
end
%% Algorithm - Alternative
function [maxValue,maxValuePositon] = findMaxInInterval2(x,y,interval)
index = x>=interval(1) & x <= interval(2);
y_temp = y(index);
x_temp = x(index);
[maxValue,indexMax] = max(y_temp);
maxValuePositon = x_temp(indexMax);
end
这是旧版本
我有一个解决方案,但我的代码对我来说似乎很复杂。有人解决方案更直接(或简单的正确MATLAB功能?)。到目前为止,这是我的解决方案:
%Generate test function
x=0:0.1:10-0.1;
x_total=0:0.1:20-0.1;
y=-(x-5).^2+25;
y_total=[y,y+10];
figure(1);
plot(x_total,y_total); grid on;
interval1=[2,8];
interval2=[12,18];
%Algorithm
index1 = x_total>=interval1(1) & x_total <= interval1(2);
index2 = x_total>=interval2(1) & x_total <= interval2(2);
offset1 = find(index1 == 1,1,'first') -1;
offset2 = find(index2 == 1,1,'first') -1;
disp('Maximum 1 and 2:');
[max1,indexMax1] = max(y_total(index1))
[max2,indexMax2] = max(y_total(index2))
disp('Position of Maximum 1 and 2:');
x_total(indexMax1+offset1)
x_total(indexMax2+offset2)
答案 0 :(得分:2)
如果您拥有信号处理工具箱,则可以使用findpeaks
,它还为您提供了一些方便的附加选项。 (documentation)
x=0:0.1:10-0.1;
x_total=0:0.1:20-0.1;
y=-(x-5).^2+25;
y_total=[y,y+10];
[y_peaks,idx] = findpeaks(y_total);
x_peaks = x_total(idx);
返回:
x_peaks =
5.0000 15.0000
y_peaks =
25.0000 35.0000
与您的算法之后的结果相同。对于图像中的信号,它会发现更多的峰值,但您可以随后选择您喜欢的峰值。
% lower bound of your interval
int_lb = 10;
% upper bound of your interval
int_ub = 20;
% arguments and values of peaks in your specified interval
x_peaks_int = x_peaks( find(x_peaks > int_lb & x_peaks < int_ub) )
y_peaks_int = y_peaks( find(x_peaks > int_lb & x_peaks < int_ub) )
返回:
x_peaks_int =
15.0000
y_peaks_int =
35.0000
答案 1 :(得分:0)
正如你所说:在区间内简单使用max
函数:)
% peak in the first interval
ids1 = find(x_total >= interval1(1), 1) : find(x_total >= interval1(2), 1);
[value1, index1] = max( y_total(ids1) );
% peak in the second interval
ids2 = find(x_total >= interval1(1), 1) : find(x_total >= interval1(2), 1);
[value2, index2] = max( y_total(ids2) );