[英]Two vectors x and y. How do I point to the maximum element in y and pick its corresponding element in x?
I have two vectors x_values
and y_values
, each of the same length but y_values
is computed from the x_values
. 我有两个向量x_values
和y_values
,每个向量的长度相同,但是y_values
是从x_values
计算得出的。 How can I take the maximum element in y_values
and pick its corresponding element in x_values
? 我怎么可以在最大元素y_values
,并挑选其相应的元素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
. 例如,如果y_values
的最大元素为31
,则程序应将其在x_values
对应值返回为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. max()
可以返回两个值。 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. 我的建议是更像MATLAB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.