I want to find the value and the position of the maximum in an interval 1 and the maximum in interval 2 in a vector (as depicted on the example figure). The borders of the interval 1 and 2 are given.
NEW VERSION - CODE MORE REUSEABLE
Uses only one interval as Dennis Jaheruddin suggested and is written as a function.
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
THIS IS THE OLD VERSION
I have a solution but my code seems pretty complicated to me. Has someone solution more straight forward (or simply the right MATLAB-function?). This is my solution so far:
%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)