繁体   English   中英

两个向量x和y。 如何指向y中的最大元素并选择x中的相应元素?

[英]Two vectors x and y. How do I point to the maximum element in y and pick its corresponding element in x?

我有两个向量x_valuesy_values ,每个向量的长度相同,但是y_values是从x_values计算得出的。 我怎么可以在最大元素y_values ,并挑选其相应的元素x_values

例如,如果y_values的最大元素为31 ,则程序应将其在x_values对应值返回为5 这是我的努力:

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

结束

>> 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))

.^是逐元素的幂。

max()可以返回两个值。 第一个是最大值,第二个是其对应的索引。

>> 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.

我的建议是更像MATLAB。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM