Note that there are some explanatory texts on larger screens.

plurals
  1. POFind maximum in an interval of a vector
    primarykey
    data
    text
    <p>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.</p> <p><img src="https://i.stack.imgur.com/PIdKD.png" alt="example"></p> <p>NEW VERSION - CODE MORE REUSEABLE</p> <p>Uses only one interval as Dennis Jaheruddin suggested and is written as a function.</p> <pre><code>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&gt;=interval(1) &amp; x &lt;= 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&gt;=interval(1) &amp; x &lt;= interval(2); y_temp = y(index); x_temp = x(index); [maxValue,indexMax] = max(y_temp); maxValuePositon = x_temp(indexMax); end </code></pre> <p>THIS IS THE OLD VERSION</p> <p>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:</p> <pre><code>%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&gt;=interval1(1) &amp; x_total &lt;= interval1(2); index2 = x_total&gt;=interval2(1) &amp; x_total &lt;= 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) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload