2016-09-16 20 views
0

我有兩個矢量x_valuesy_values,每個長度相同,但y_values是從x_values計算出來的。如何獲取y_values中的最大元素並在x_values中選取其對應的元素?兩個向量x和y。我如何指向y中的最大元素並在x中選擇其相應的元素?

例如,如果在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 

回答

3
>> 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-ISH。

+0

謝謝你Jeon。是的,我更喜歡MATLAB – user7479

相關問題