2

I have a question regarding max command in MATLAB

let's say I have x and y matrices:

x = [1 2 3 4 5 6  7 8  9]
y = [1 4 6 2 3 64 7 67 6]

Now, I know how to find x value at which y is maximum

xIndex = find(y==max(y));
maxXValue = x(xIndex);

something like this..

My questions are:

  • Do I have to plot(x, y) in order to find x value at which y is max?
  • Is there any way I can find that value without plotting?
  • I would like to find it without plotting (or at least plot but not actually show it)
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58
Joonie
  • 129
  • 6

2 Answers2

1

The second output of max/min is the index in the array at which that value occurs. Assuming x and y share indices you can use this to map between the two.

For example:

x = [1 2 3 4 5 6 7 8 9];
y = [1 4 6 2 3 64 7 67 6];

[miny, minidx] = min(y);
[maxy, maxidx] = max(y);

fprintf('Ymin: %d, Xval: %u\nYmax: %d, Xval: %u\n', miny, x(minidx), maxy, x(maxidx))

Returns:

Ymin: 1, Xval: 1
Ymax: 67, Xval: 8
sco1
  • 12,154
  • 5
  • 26
  • 48
0

You can use logical indexing to get the x value(s) corresponding to the maximum y directly like this:

x(y==max(y))

If there are duplicate maximum values of y then you will get each matching/corresponding value of x as well.

informaton
  • 1,462
  • 2
  • 11
  • 20