I have two vectors x_values
and y_values
, each of the same length but y_values
is computed from the x_values
. How can I take the maximum element in y_values
and pick its corresponding element in x_values
?
For example if the maximum element in y_values
is 31
, the program should return its corresponding value in x_values
as 5
. Here is my effort:
function maxValue = maximumValue()
x_values = -5:5;
y_values = [];
for i = x_values
y = i^3 - 3*i^2 - 3*i - 4;
y_values = [y_values, y];
end
for j = 1:length(y_values)
if max(y_values(j))
maxValue = x_values(j);
end
end
end
>> x_values = -5:5;
>> y_values = x_values.^3 - 3 * x_values.^2 - 3 * x_values - 4;
>> [ymax, index_ymax] = max(y_values);
>> disp(x_values(index_ymax))
.^
is an element-wise exponentiation.
max()
can return two values. First one is the maximum value, and the second one is its corresponding index.
>> help max
max Largest component.
For vectors, max(X) is the largest element in X. For matrices,
max(X) is a row vector containing the maximum element from each
column. For N-D arrays, max(X) operates along the first
non-singleton dimension.
[Y,I] = max(X) returns the indices of the maximum values in vector I.
If the values along the first non-singleton dimension contain more
than one maximal element, the index of the first one is returned.
And my suggestion is more MATLAB-ish.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.