Olarik Surinta
Olarik Surinta

Reputation: 119

Find local maximum value in the vector

Somebody could help me. I use Matlab program.

Suppose, I have vector A,

A = [0 0 1 2 3 5 0 0 0 0 0 2 3 6 7 0 0 0 0 1 1 2 3 4 1]

I would like to get local maximum values and location from the vector A. So, the answer that I would like to get is following.

maxValue = 5, 7 and 4;

maxLocation = 6, 15 and 24;

thank you for your kind.

Upvotes: 1

Views: 12252

Answers (4)

Glen O
Glen O

Reputation: 733

I assume you are seeking local maximum values - that is, values that are greater than those around them.

My solution would be this:

Loc = find(diff(A)(2:end)<0 & diff(A)(1:(end-1))>0)+1;
Val = A(Loc);

Loc will contain the positions of the local maxima, and Val will contain the values at those local maxima. Note that it will NOT find maxima at the edges, as written. If you want to detect those as well, you must modify it slightly:

Loc = find([A(1)>A(2),(diff(A)(2:end)<0 & diff(A)(1:(end-1))>0),A(end)>A(end-1)]);
Val = A(Loc);

Upvotes: 2

user85109
user85109

Reputation:

You need to be far more clear about your goals. It looks like you wish to find the local maxima in a vector.

Will you always have vectors (NOT really arrays, which is usually a word to denote a thing with two non-unit dimensions) that have a local maximum that you wish to find? Will you choose to find all local maxima? If so, then this will work...

A = [0 0 1 2 3 5 0 0 0 0 0 4 5 6 7 0 0 0 0 1 1 2 3 4 1];

n = numel(A);
ind = 2:(n-1);

maxLoc = ind(find((diff(ind-1) > 0) & (diff(ind) < 0)));

% in case the max occurs at an end
if A(2) < A(1)
  maxLoc = [1,maxLoc];
end
if A(n) < A(n-1)
  maxLoc = [maxLoc,n];
end

maxVal = A(maxLoc);

But what about the vector

A = [0 1 2 2 1 0];

What do you wish to see now?

Again, you need to think out your requirements. What are your needs. What is the goal?

Once you have done so, then your problems will be easier to solve, and easier for someone to answer.

Upvotes: 2

richyo1000
richyo1000

Reputation: 190

you want to find every occurence of 4,5 and 7? try:

Output = find(A>3)

this will return a 1xN vector with the positions of anything over 3... not sure if this is what you want though

Upvotes: -2

Bjoern H
Bjoern H

Reputation: 600

If you have the Signal Processing toolbox then findpeaks should be what you want:

[pks,locs] = findpeaks(A)

For future reference you should know that what you want to find are local maxima. Saying that you want to find the maximum value makes it seem as if you want the global maxima (which would be 7 in this case).

Upvotes: 7

Related Questions