簡體   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